diff --git a/.cursor/rules/clean-code.mdc b/.cursor/rules/clean-code.mdc new file mode 100644 index 000000000..562ac0f03 --- /dev/null +++ b/.cursor/rules/clean-code.mdc @@ -0,0 +1,54 @@ +--- +alwaysApply: true +--- +# Clean Code Guidelines + +## Constants Over Magic Numbers +- Replace hard-coded values with named constants +- Use descriptive constant names that explain the value's purpose +- Keep constants at the top of the file or in a dedicated constants file + +## Meaningful Names +- Variables, functions, and classes should reveal their purpose +- Names should explain why something exists and how it's used +- Avoid abbreviations unless they're universally understood + +## Smart Comments +- Don't comment on what the code does - make the code self-documenting +- Use comments to explain why something is done a certain way +- Document APIs, complex algorithms, and non-obvious side effects + +## Single Responsibility +- Each function should do exactly one thing +- Functions should be small and focused +- If a function needs a comment to explain what it does, it should be split + +## DRY (Don't Repeat Yourself) +- Extract repeated code into reusable functions +- Share common logic through proper abstraction +- Maintain single sources of truth + +## Clean Structure +- Keep related code together +- Organize code in a logical hierarchy +- Use consistent file and folder naming conventions + +## Encapsulation +- Hide implementation details +- Expose clear interfaces +- Move nested conditionals into well-named functions + +## Code Quality Maintenance +- Refactor continuously +- Fix technical debt early +- Leave code cleaner than you found it + +## Testing +- Write tests before fixing bugs +- Keep tests readable and maintainable +- Test edge cases and error conditions + +## Version Control +- Write clear commit messages +- Make small, focused commits +- Use meaningful branch names \ No newline at end of file diff --git a/.cursor/rules/codequality.mdc b/.cursor/rules/codequality.mdc new file mode 100644 index 000000000..177799ab8 --- /dev/null +++ b/.cursor/rules/codequality.mdc @@ -0,0 +1,46 @@ +--- +alwaysApply: true +--- +# Code Quality Guidelines + +## Verify Information +Always verify information before presenting it. Do not make assumptions or speculate without clear evidence. + +## File-by-File Changes +Make changes file by file and give me a chance to spot mistakes. + +## No Apologies +Never use apologies. + +## No Understanding Feedback +Avoid giving feedback about understanding in comments or documentation. + +## No Whitespace Suggestions +Don't suggest whitespace changes. + +## No Summaries +Don't summarize changes made. + +## No Inventions +Don't invent changes other than what's explicitly requested. + +## No Unnecessary Confirmations +Don't ask for confirmation of information already provided in the context. + +## Preserve Existing Code +Don't remove unrelated code or functionalities. Pay attention to preserving existing structures. + +## Single Chunk Edits +Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file. + +## No Implementation Checks +Don't ask the user to verify implementations that are visible in the provided context. + +## No Unnecessary Updates +Don't suggest updates or changes to files when there are no actual modifications needed. + +## Provide Real File Links +Always provide links to the real files, not x.md. + +## No Current Implementation +Don't show or discuss the current implementation unless specifically requested. \ No newline at end of file diff --git a/.cursor/rules/dms/biz.mdc b/.cursor/rules/dms/biz.mdc new file mode 100644 index 000000000..7804fe1e8 --- /dev/null +++ b/.cursor/rules/dms/biz.mdc @@ -0,0 +1,48 @@ +--- +description: +globs: +alwaysApply: false +--- + + +#### Biz Layer Implementation Guidelines (`internal/dms/biz/`) +- Use usecase pattern for business logic: + ```go + type SomeUsecase struct { + repo Repository + // Other dependencies + } + ``` +- Define clear domain models: + ```go + type DomainModel struct { + UID string + // Domain-specific fields + } + ``` +- Implement business validation: + ```go + func (u *SomeUsecase) validateData(ctx context.Context, data *DomainModel) error { + if err := u.validateBusinessRules(data); err != nil { + return fmt.Errorf("business validation failed: %v", err) + } + return nil + } + ``` +- Handle state transitions: + ```go + func (u *SomeUsecase) UpdateState(ctx context.Context, model *DomainModel, newState State) error { + if !model.CanTransitionTo(newState) { + return pkgErr.ErrInvalidStateTransition + } + // Update state + } + ``` +- Define repository interfaces: + ```go + type DBModelRepository interface { + Create(ctx context.Context, model *DomainModel) error + Update(ctx context.Context, model *DomainModel) error + // Other methods + } + ``` diff --git a/.cursor/rules/dms/dms-api-standards.mdc b/.cursor/rules/dms/dms-api-standards.mdc new file mode 100644 index 000000000..001340d2e --- /dev/null +++ b/.cursor/rules/dms/dms-api-standards.mdc @@ -0,0 +1,69 @@ +--- +description: DMS project API architecture, development standards, and implementation guidelines. Apply these rules when working with DMS API code to ensure consistency with existing patterns and maintainability. +globs: + - "internal/apiserver/**/*.go" + - "api/**/*.go" + - "pkg/dms-common/**/*.go" +--- + +# DMS API Standards + +## Framework and Architecture +- Use Echo v4 as the web framework for all HTTP handling +- Maintain Go 1.19+ compatibility +- Follow layered architecture: API -> Service -> Business Logic +- Support both v1 and v2 API versions with proper versioning strategy +- Use JWT authentication with echo-jwt middleware + +## API Versioning +- Implement versioned routes: `/v1/dms/`, `/v2/dms/` +- Keep v1 APIs backward compatible +- Introduce new features in v2 first +- Use route groups for version management +- Mark deprecated endpoints with `DeprecatedBy()` function + + +## Routing Standards +- Organize routes in `router.go` by functional modules +- Use Echo route groups for logical separation +- Apply middleware selectively to specific route groups +- Support RESTful resource patterns: `GET /resource`, `POST /resource`, `PUT /resource/:id`, `DELETE /resource/:id` +- Implement proper HTTP method handling for each endpoint + +## Request and Response Handling +- Use `base.GenericResp` for consistent response structure +- Implement proper request validation with validator tags +- Support JSON and form data binding +- Return standardized error codes using `apiError.ErrorCode` +- Include proper HTTP status codes in responses + +## Data Models +- Define all API models in `api/dms/service/v1/` and `api/dms/service/v2/` +- Use consistent naming: `{Action}{Resource}Req` for requests, `{Action}{Resource}Reply` for responses +- Include proper JSON tags and validation rules +- Support pagination, filtering, and sorting where appropriate +- Use `UidWithName` struct for common identifier patterns + +## Error Handling +- Implement centralized error handling in controllers +- Use predefined error codes from `apiError` package +- Log errors with appropriate context and stack traces +- Return user-friendly error messages +- Support internationalization for error messages + +## Security Implementation +- Enable HTTPS with TLS 1.2+ configuration +- Implement JWT token validation and refresh +- Use role-based access control (RBAC) +- Validate all input parameters and request data +- Implement proper session management and timeout + +## Middleware Usage +- Apply authentication middleware to protected routes +- Use compression middleware for response optimization +- Implement logging middleware for request tracking +- Apply rate limiting where necessary +- Use custom middleware for business-specific concerns + +## Swagger Documentation Standards +@swagger-documentation-standards.mdc diff --git a/.cursor/rules/dms/dms-development.mdc b/.cursor/rules/dms/dms-development.mdc new file mode 100644 index 000000000..88e61ef2e --- /dev/null +++ b/.cursor/rules/dms/dms-development.mdc @@ -0,0 +1,123 @@ +--- +alwaysApply: true +--- +# DMS Architecture Standards + +## Layered Architecture Design + +### API Definition Layer (`api/`) +- Define Request and Response structures +@dms-api-standards.mdc +- Version-controlled API definitions (v1, v2, etc.) + +### API Layer (`internal/apiserver/service/route.go`) +- Implement RESTful API design standards +- Handle HTTP requests and responses +- Implement request parameter binding and validation +- Unified error handling and response format +- Route registration and middleware configuration + +#### Controller Implementation Guidelines(`internal/apiserver/service/*_controller.go`) +- Use `DMSController` struct for controller implementation +- Include service dependencies and logger in controller struct +- Use swagger annotations for API documentation +@dms-api-standards.mdc +- Follow standard error handling pattern: + ```go + func (ctl *DMSController) MethodName(c echo.Context) error { + req := new(aV1.RequestStruct) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // Business logic + return NewOkRespWithReply(c, reply) + } + ``` + + +### Service Layer (`internal/dms/service/`) +- Implement business process orchestration without specific business rules +- Handle transaction control and concurrency +- Combine multiple Biz layer interfaces to complete business functions +- Business parameter validation + +#### Service Implementation Guidelines +- Use service struct with required dependencies: + ```go + type DMSService struct { + // Biz layer dependencies + BusinessUsecase *biz.BusinessUsecase + // Other dependencies + } + ``` +- Follow standard method signature pattern: + ```go + func (d *DMSService) MethodName(ctx context.Context, req *dmsV1.RequestStruct, currentUserUid string) (reply *dmsV1.ReplyStruct, err error) + ``` +- Handle request transformation: + ```go + // Transform API request to biz layer args + args := &biz.SomeStruct{ + Field1: req.Field1, + Field2: req.Field2, + } + ``` +- Proper error handling and wrapping: + ```go + if err != nil { + return nil, fmt.Errorf("operation failed: %v", err) + } + ``` +- Standard response structure: + ```go + return &dmsV1.ReplyStruct{ + Data: struct { + Field string `json:"field"` + }{Field: value}, + }, nil + ``` + +### Biz Layer (`internal/dms/biz/`) +- Implement core business logic of domain models +- Define domain object behaviors and rules +- Independent of specific storage implementations +- Include business rule validation +- Implement core features like permission verification +@biz.mdc + +### Storage Layer (`internal/{module}/storage/`) +- Implement data access interfaces +- Implement DBModelRepository interface,Handle database CRUD operations +- Support multiple storage implementations +- Contains no business logic +@storage.mdc + + +## Development Standards + +### Dependency Principles +- Each layer maintains single responsibility, no cross-layer calls +- Upper layers depend on lower layers, no reverse dependencies +- Isolate dependencies through interfaces +- Follow Clean Code principles + +### Testing Requirements +- Write unit tests for all controller methods +- Implement integration tests for complete API flows +- Use `testify` library for assertions and mocking +- Maintain test coverage above 80% +- Test both success and error scenarios + +### Logging Standards +- Use structured logging with consistent field naming +- Include essential context fields in all log entries +- Follow proper log level classification for different types of messages +- Ensure logs are searchable and traceable across distributed systems + +### Module Development Guidelines +- Each module should follow the layered architecture +- Implement related functionality in corresponding directories +- When adding new APIs, first define interfaces and data structures in the api directory +- Then implement corresponding functionality in each layer +- Maintain module independence and low coupling \ No newline at end of file diff --git a/.cursor/rules/dms/storage.mdc b/.cursor/rules/dms/storage.mdc new file mode 100644 index 000000000..d39a2903b --- /dev/null +++ b/.cursor/rules/dms/storage.mdc @@ -0,0 +1,61 @@ +--- +description: +globs: +alwaysApply: false +--- + +### Storage Implementation Guidelines (`internal/{module}/storage/`) +- Use GORM for database operations: + ```go + var _ biz.DBModelRepo = (*DBModelRepo)(nil) + type DBModelRepo struct { + *Storage + log *utilLog.Helper + } + func NewDBModelRepo(log utilLog.Logger, s *Storage) *DBModelRepo { + return &SmsDBModelRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.DBModel"))} + } + ``` +- Use proper table naming and tags: + ```go + type DBModel struct { + gorm.Model + Name string `gorm:"column:name;type:varchar(255)"` + // Other fields + } + + func (DBModel) TableName() string { + return "table_name" + } + ``` +- Handle transactions: + ```go + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Create(convertBizModel1(u)).Error; err != nil { + return fmt.Errorf("failed to save model1: %v", err) + } + if err := tx.WithContext(ctx).Delete(convertBizModel2(u)).Error; err != nil { + return fmt.Errorf("failed to delete model2: %v", err) + } + return nil + }); err != nil { + return err + } + ``` +- Implement repository interfaces,filtering and pagination: + ```go + func (s *DBModelRepo) Create(ctx context.Context, model *Model) error { + return s.db.WithContext(ctx).Create(model).Error + } + func (s *DBModelRepo) List(ctx context.Context, opt *ListOption) ([]*Model, error) { + query := s.db.WithContext(ctx) + // Apply filters + for _, filter := range opt.Filters { + query = query.Where(filter.Condition, filter.Value) + } + // Apply pagination + query = query.Offset(opt.Offset).Limit(opt.Limit) + var models []*Model + return models, query.Find(&models).Error + } + ``` \ No newline at end of file diff --git a/.cursor/rules/dms/swagger-documentation-standards.mdc b/.cursor/rules/dms/swagger-documentation-standards.mdc new file mode 100644 index 000000000..92af50663 --- /dev/null +++ b/.cursor/rules/dms/swagger-documentation-standards.mdc @@ -0,0 +1,507 @@ +--- +alwaysApply: false +globs: + - "internal/apiserver/**/*.go" + - "api/**/*.go" + - "pkg/dms-common/**/*.go" +--- +## Swagger Documentation Standards +- Use Swaggo toolchain for Swagger documentation generation +- Required tools: `github.com/go-swagger/go-swagger`, + + +### Swagger Comment Format +- Use declarative comment format following go-swag standards!!!(https://goswagger.io/go-swagger/generate-spec/) +- Every API endpoint must have complete swagger annotations +- Include comprehensive parameter descriptions and validation rules + +### API Operation Definition +```go +// swagger:operation {HTTP_METHOD} {PATH} {TAG} {OPERATION_ID} +// +// {DESCRIPTION} +// +// --- +// parameters: +// - name: {PARAM_NAME} +// description: {PARAM_DESCRIPTION} +// in: {PARAM_LOCATION} +// required: {REQUIRED} +// type: {PARAM_TYPE} +// requestBody: +// description: {REQUEST_DESCRIPTION} +// required: {REQUIRED} +// content: +// application/json: +// schema: +// "$ref": "#/definitions/{REQUEST_MODEL_NAME}" +// responses: +// '{STATUS_CODE}': +// description: {RESPONSE_DESCRIPTION} +// schema: +// "$ref": "#/definitions/{MODEL_NAME}" +``` + +### Request Definition +```go +// swagger:parameters {OPERATION_ID} +type RequestModel struct { + // Path parameters + // in: path + // required: true + ParamName string `param:"param_name" json:"param_name" validate:"required"` + + // Query parameters + // in: query + QueryParam string `query:"query_param" json:"query_param"` + + // Body parameters + // in: body + BodyData interface{} `json:"body_data"` + + // Header parameters + // in: header + HeaderParam string `header:"header_param" json:"header_param"` +} +``` + +### Request Body Definition +```go +// swagger:model {REQUEST_MODEL_NAME} +type RequestModel struct { + // Field description + // Required: true + // Example: "example_value" + FieldName string `json:"field_name" validate:"required"` + + // Optional field + OptionalField *string `json:"optional_field,omitempty"` + + // Array field + ArrayField []string `json:"array_field"` + + // Nested object + NestedObject *NestedType `json:"nested_object"` +} +``` + +### Model Definition +```go +// swagger:model {MODEL_NAME} +type ModelName struct { + // Field description + // Required: true + // Example: "example_value" + FieldName string `json:"field_name" validate:"required"` + + // Optional field + OptionalField *string `json:"optional_field,omitempty"` + + // Array field + ArrayField []string `json:"array_field"` + + // Nested object + NestedObject *NestedType `json:"nested_object"` + + // Enum field with swagger:enum + Status Status `json:"status"` +} + +// swagger:enum Status +type Status string + +const ( + StatusOK Status = "正常" + StatusDisable Status = "被禁用" +) +``` + +### Response Definition +```go +// swagger:response {RESPONSE_NAME} +type ResponseName struct { + // swagger:file + // in: body + File []byte +} + +// swagger:model {RESPONSE_MODEL_NAME} +type ResponseModel struct { + // Response data + Data interface{} `json:"data"` + + // Generic response + base.GenericResp +} +``` + +### Pagination Response Structure +```go +// swagger:model ListResourceReply +type ListResourceReply struct { + // List resource reply + Data []*Resource `json:"data"` + + // Total count of resources + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +// swagger:parameters ListResource +type ListResourceReq struct { + // The maximum count of resources to be returned + // in: query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + + // The offset of resources to be returned, default is 0 + // in: query + PageIndex uint32 `query:"page_index" json:"page_index"` + + // Order by field, multiple of ["name"], default is ["name"] + // in: query + OrderBy ResourceOrderByField `query:"order_by" json:"order_by"` + + // Filter by name + // in: query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + + // Filter by UIDs + // in: query + FilterByUids string `query:"filter_by_uids" json:"filter_by_uids"` +} +``` + +### Common Business Models +```go +// swagger:model UidWithName +type UidWithName struct { + // Resource UID + Uid string `json:"uid"` + + // Resource name + Name string `json:"name"` +} + +// swagger:model AddResourceReply +type AddResourceReply struct { + // Add resource reply + Data struct { + // Resource UID + Uid string `json:"uid"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:model UpdateResourceReq +type UpdateResourceReq struct { + // Resource UID (path parameter) + // swagger:ignore + ResourceUid string `param:"resource_uid" json:"resource_uid" validate:"required"` + + // Resource update data + Resource *UpdateResource `json:"resource" validate:"required"` +} + +// swagger:model FileResponse +type FileResponse struct { + // swagger:file + // in: body + File []byte +} +``` + +### Complete API Operation Example +```go +// swagger:operation GET /v1/dms/users User ListUsers +// +// List all users with pagination and filtering. +// +// --- +// parameters: +// - name: page_size +// description: The maximum count of users to be returned +// in: query +// required: true +// type: integer +// format: uint32 +// - name: page_index +// description: The offset of users to be returned, default is 0 +// in: query +// required: false +// type: integer +// format: uint32 +// - name: order_by +// description: Order by field, multiple of ["name"], default is ["name"] +// in: query +// required: false +// type: string +// enum: [name] +// - name: filter_by_name +// description: Filter the user name +// in: query +// required: false +// type: string +// responses: +// '200': +// description: List users successfully +// schema: +// "$ref": "#/definitions/ListUserReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +``` + +### Documentation Generation Process +1. Install Swaggo CLI: `go install github.com/swaggo/swag/cmd/swag@latest` +2. Generate documentation: `swag init -g internal/apiserver/service/service.go` +3. Integrate with Echo: Register `/swagger/*` route with `echoSwagger.WrapHandler` +4. Keep documentation synchronized with code changes + +### Best Practices +- Ensure comment completeness for all API endpoints +- Use `$ref` to reference defined models consistently +- Define all possible response statuses and formats +- Organize APIs with meaningful tags for better documentation structure +- Validate generated Swagger documentation for accuracy + +## Performance Considerations +- Implement proper connection pooling +- Use goroutines for concurrent operations where beneficial +- Optimize database queries and reduce N+1 problems +- Implement caching strategies for frequently accessed data +- Monitor API response times and resource usage + +## Cluster Mode Support +- Enable cluster mode configuration +- Implement service discovery and registration +- Support load balancing across multiple instances +- Handle cluster node failures gracefully +- Maintain data consistency in distributed environment + + +## Data Format Standards +- Maintain consistent data format across all API endpoints +- Follow industry standards for data representation +- Ensure data compatibility and interoperability + +### JSON Field Naming Convention +- **All JSON fields must use snake_case naming** +- Maintain consistency across request/response models +- Follow Go struct tag conventions + +```go +// Correct JSON field naming examples +type User struct { + // User unique identifier + UID string `json:"uid" validate:"required"` + + // User display name + Name string `json:"name" validate:"required"` + + // User email address + Email string `json:"email"` + + // User phone number + Phone string `json:"phone"` + + // User WeChat ID + WxID string `json:"wxid"` + + // User password (never return in responses) + Password string `json:"password,omitempty"` + + // User group identifiers + UserGroupUids []string `json:"user_group_uids"` + + // User operation permissions + OpPermissionUids []string `json:"op_permission_uids"` + + // User authentication type + UserAuthenticationType string `json:"user_authentication_type"` + + // User creation timestamp + CreatedAt string `json:"created_at"` + + // User last update timestamp + UpdatedAt string `json:"updated_at"` +} + +// Incorrect examples (DO NOT USE) +type IncorrectUser struct { + UID string `json:"UID"` // Wrong: PascalCase + Name string `json:"userName"` // Wrong: camelCase + Email string `json:"EMAIL"` // Wrong: UPPER_CASE + Phone string `json:"phone_number"` // Wrong: inconsistent with existing +} +``` + +### Time Field Format Standards +- **All time fields must use RFC3339 format with timezone information** +- Use string type for JSON serialization +- Include timezone offset or UTC designation + +```go +// Time field format examples +type TimeFields struct { + // Creation timestamp in RFC3339 format + CreatedAt string `json:"created_at" example:"2024-01-15T10:30:00Z"` + + // Update timestamp in RFC3339 format + UpdatedAt string `json:"updated_at" example:"2024-01-15T14:45:00+08:00"` + + // Expiration timestamp in RFC3339 format + ExpiresAt string `json:"expires_at" example:"2024-12-31T23:59:59-05:00"` + + // Last login timestamp in RFC3339 format + LastLoginAt string `json:"last_login_at" example:"2024-01-15T09:15:30Z"` +} + +// RFC3339 format examples +// UTC time: "2024-01-15T10:30:00Z" +// With timezone: "2024-01-15T18:30:00+08:00" +// With timezone: "2024-01-15T05:30:00-05:00" + +// Time handling in Go +import "time" + +func formatTimeRFC3339(t time.Time) string { + return t.Format(time.RFC3339) +} + +func parseTimeRFC3339(timeStr string) (time.Time, error) { + return time.Parse(time.RFC3339, timeStr) +} +``` + +### Enum Value Standards +- **All enum values must use fixed case, recommended UPPER_CASE** +- Maintain consistency across all enum definitions +- Use descriptive names that clearly indicate the value's purpose + +```go +// Enum value examples +// swagger:enum UserStatus +type UserStatus string + +const ( + // User is active and can access the system + UserStatusActive UserStatus = "ACTIVE" + + // User is disabled and cannot access the system + UserStatusDisabled UserStatus = "DISABLED" + + // User account is pending activation + UserStatusPending UserStatus = "PENDING" + + // User account is locked due to security reasons + UserStatusLocked UserStatus = "LOCKED" +) + +// swagger:enum AuthenticationType +type AuthenticationType string + +const ( + // Local DMS authentication + AuthenticationTypeDMS AuthenticationType = "DMS" + + // LDAP authentication + AuthenticationTypeLDAP AuthenticationType = "LDAP" + + // OAuth2 authentication + AuthenticationTypeOAuth2 AuthenticationType = "OAUTH2" + + // Unknown authentication type + AuthenticationTypeUnknown AuthenticationType = "UNKNOWN" +) + +// swagger:enum ProjectOrderByField +type ProjectOrderByField string + +const ( + // Order by project name + ProjectOrderByName ProjectOrderByField = "NAME" + + // Order by creation time + ProjectOrderByCreatedAt ProjectOrderByField = "CREATED_AT" + + // Order by update time + ProjectOrderByUpdatedAt ProjectOrderByField = "UPDATED_AT" +) + +// Incorrect enum examples (DO NOT USE) +type IncorrectEnum string + +const ( + IncorrectEnumValue1 IncorrectEnum = "value1" // Wrong: lowercase + IncorrectEnumValue2 IncorrectEnum = "Value2" // Wrong: PascalCase + IncorrectEnumValue3 IncorrectEnum = "VALUE_3" // Wrong: inconsistent with others +) +``` + +### Data Validation and Examples +Include proper validation rules and examples in Swagger annotations: + +```go +// swagger:model CreateUserReq +type CreateUserReq struct { + // User information + User *CreateUser `json:"user" validate:"required"` +} + +// swagger:model CreateUser +type CreateUser struct { + // User display name + // Required: true + // MinLength: 1 + // MaxLength: 100 + // Example: "John Doe" + Name string `json:"name" validate:"required,min=1,max=100"` + + // User email address + // Required: true + // Format: email + // Example: "john.doe@example.com" + Email string `json:"email" validate:"required,email"` + + // User phone number + // Format: phone + // Example: "+86-138-0013-8000" + Phone string `json:"phone"` + + // User status + // Required: true + // Enum: [ACTIVE, DISABLED, PENDING] + // Example: "ACTIVE" + Status UserStatus `json:"status" validate:"required,oneof=ACTIVE DISABLED PENDING"` + + // User creation timestamp + // Format: date-time (RFC3339) + // Example: "2024-01-15T10:30:00Z" + CreatedAt string `json:"created_at"` +} +``` + +### Migration Guidelines +When updating existing APIs to follow these standards: + +1. **JSON Field Names**: Update struct tags to use snake_case +2. **Time Fields**: Convert existing time formats to RFC3339 +3. **Enum Values**: Standardize enum values to UPPER_CASE +4. **Backward Compatibility**: Consider API versioning for breaking changes +5. **Documentation**: Update Swagger examples and documentation + +### Consistency Checklist +Before committing code, ensure: + +- [ ] All JSON fields use snake_case naming +- [ ] All time fields use RFC3339 format with timezone +- [ ] All enum values use consistent UPPER_CASE format +- [ ] Swagger examples match the actual data format +- [ ] Validation rules are properly defined +- [ ] Backward compatibility is maintained where required diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 000000000..6ada0a2e4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: LordofAvernus + +--- + + + +## 版本信息(Version) + +## 问题描述(Describe) + +## 截图或日志(Log) + +## 如何复现(To Reproduce) + + + +## 问题原因 + +## 解决方案 + +## 变更影响面 + +#### 受影响的模块或功能 + +#### 外部引用的潜在问题或风险 + +#### 版本兼容性 + +#### 测试建议 + \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/new-feature-.md b/.github/ISSUE_TEMPLATE/new-feature-.md new file mode 100644 index 000000000..80c32ac50 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new-feature-.md @@ -0,0 +1,29 @@ +--- +name: 'New feature ' +about: Suggest an feature for this project +title: '' +labels: '' +assignees: LordofAvernus + +--- + + + +## 需求描述(Describe) + + + + + +## 实现方案 + +## 变更影响面 + +#### 受影响的模块或功能 + +#### 外部引用的潜在问题或风险 + +#### 版本兼容性 + +#### 测试建议 + \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..4f374436f --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,15 @@ +## 关联的 issue + +## 描述你的变更 + +## 确认项(pr提交后操作) +> [!TIP] +> 请在指定**复审人**之前,确认并完成以下事项,完成后✅ +---------------------------------------------------------------------- +- [ ] 我已完成自测 +- [ ] 我已记录完整日志方便进行诊断 +- [ ] 我已在关联的issue里补充了实现方案 +- [ ] 我已在关联的issue里补充了测试影响面 +- [ ] 我已确认了变更的兼容性,如果不兼容则在issue里标记 `not_compatible` +- [ ] 我已确认了是否要更新文档,如果要更新则在issue里标记 `need_update_doc` +---------------------------------------------------------------------- diff --git a/.github/workflows/check-pr-files.yml b/.github/workflows/check-pr-files.yml new file mode 100644 index 000000000..8397c6e3f --- /dev/null +++ b/.github/workflows/check-pr-files.yml @@ -0,0 +1,16 @@ +name: prevent-file-change +on: + pull_request: + branches: + - '*-ee' +jobs: + prevent-file-change: + if: github.head_ref != 'main' && !startsWith(github.head_ref, 'release') + runs-on: ubuntu-latest + steps: + - uses: xalvarez/prevent-file-change-action@v1 + name: Prevent file change + with: + githubToken: ${{ secrets.GITHUB_TOKEN }} + pattern: ^(?!.*_ee\.go$)(?!.*_ee_test\.go$)(?!.*_ee\.md$)(?!.*_ee\.yml$)(?!.*_rel\.go$)(?!.*_rel_test\.go$)(?!go\.mod$)(?!go\.sum$)(?!\.github\/workflows\/check-pr-files\.yml$)(?!vendor\/.*)(?!.*_qa\.go$).* + trustedAuthors: xalvarez \ No newline at end of file diff --git a/.github/workflows/pr-agent.yml b/.github/workflows/pr-agent.yml new file mode 100644 index 000000000..30038d715 --- /dev/null +++ b/.github/workflows/pr-agent.yml @@ -0,0 +1,28 @@ +on: + pull_request: + types: [opened, reopened, ready_for_review, synchronize] +jobs: + pr_agent_job: + if: ${{ github.event.sender.type != 'Bot' && github.actor != 'actiontech-bot' }} + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + contents: write + name: Run pr agent on every pull request, respond to user comments + steps: + - name: PR Agent action step + id: pragent + uses: qodo-ai/pr-agent@main + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + github_action_config.pr_actions: '["opened", "reopened", "ready_for_review", "review_requested", "synchronize"]' + OPENAI_API_VERSION: ${{ vars.OPENAI_API_VERSION }} + github_action_config.auto_review: "true" + github_action_config.auto_describe: "true" + github_action_config.auto_improve: "true" + OPENAI_KEY: ${{ secrets.OPENAI_KEY }} + OPENAI.API_TYPE: "azure" + OPENAI.API_BASE: ${{ secrets.OPENAI_API_BASE }} + AZURE_API_VERSION: ${{ vars.AZURE_API_VERSION }} + OPENAI.DEPLOYMENT_ID: ${{ secrets.DEPLOYMENT_ID }} diff --git a/.github/workflows/trigger-ee-workflow.yml b/.github/workflows/trigger-ee-workflow.yml new file mode 100644 index 000000000..6cc8cb999 --- /dev/null +++ b/.github/workflows/trigger-ee-workflow.yml @@ -0,0 +1,22 @@ +name: Trigger dms-ee Workflow + +on: + push: + branches: + - main + - 'release*' + +jobs: + trigger-sync-workflow: + # this file will sync to dms-ee, we only execute job on actiontech/dms + if: github.repository == 'actiontech/dms' + name: Create workflow dispatch on dms-ee + runs-on: ubuntu-latest + steps: + - name: Trigger dms-ee workflow + uses: benc-uk/workflow-dispatch@v1 + with: + token: ${{ secrets.DOWNSTREAM_REPO_SECRET }} + repo: actiontech/dms-ee + workflow: Sync with DMS + ref: ${{ github.ref }}-ee \ No newline at end of file diff --git a/.gitignore b/.gitignore index 500479283..c1dc3845b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,8 @@ static .vscode bin process_record.json -*.db \ No newline at end of file +*.db +*.rpm +*.rpm.md5 +builddir/ +/.idea/ diff --git a/.pr_agent.toml b/.pr_agent.toml new file mode 100644 index 000000000..44b2ec2b8 --- /dev/null +++ b/.pr_agent.toml @@ -0,0 +1,60 @@ +[config] +response_language="zh-CN" +verbosity_level=2 + +[pr_reviewer] # /review # +# enable/disable features +# general options +extra_instructions = """ +- Please describe the issue_content,issue_header field in Chinese. +- In Golang code, using db.Query() and using stmt, err := db.Prepare() followed by stmt.Query() have the same effect. For example, db.Query(\"SELECT * FROM tb1 WHERE a = ? AND b = ?\", aa, bb) also uses parameter passing with ? placeholders. Please do not flag such cases as SQL injection risks. +- During review, if a specific type of code issue is encountered, please do not overlook this issue in subsequent reviews and continue to provide suggestions for all code blocks exhibiting the problem. +""" +final_update_message = true +# review labels +enable_review_labels_security=false +enable_review_labels_effort=false +# specific configurations for incremental review (/review -i) +enable_intro_text=false +enable_help_text=false + +[pr_description] # /describe # +publish_labels = false +add_original_user_description = true +generate_ai_title = false +use_bullet_points = true +extra_instructions = "Please describe all the contents of the Description field in Chinese." +enable_pr_type = false + +[pr_code_suggestions] # /improve # +extra_instructions = """ +- Please describe all the contents of the Suggestions field in Chinese. +- Please describe in Chinese why these code modification suggestions are being provided. +- When a new commit is submitted, please re-review all code changes and update the persistent review. +- When reviewing, if identical issues are found in multiple code blocks, please offer recommendations for each instance. +- In Golang code, using db.Query() and using stmt, err := db.Prepare() followed by stmt.Query() have the same effect. Please do not suggest replacing db.Query() with db.Prepare() in code review suggestions. +These issues require special attention, and should be highlighted in review suggestions along with explanations of their severity: +# Things about panic # +- Nil pointer dereferences. +- Array or slice out-of-bounds access. +- Invalid type assertions. +- Operations on nil or closed channels. +- Division by zero. +- Concurrent map access without proper synchronization. +- Use of uninitialized variables. +- Improper use of defer functions. +- Any other conditions that could trigger a panic. +- Failure to close an opened file leads to a file descriptor leak. This is a crucial issue that the AI should prioritize during code reviews to prevent resource exhaustion. +- Network connection leaks +- Database connection leaks +- Memory leaks +- Other system resource leaks +- Make certain that all the reviewer's questions have received corresponding suggestions. +""" + +[github_app] +# settings for "pull_request" event with "synchronize" action - used to detect and handle push triggers for new commits +handle_push_trigger = true + +[litellm] +drop_params = true diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..a612ad981 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Makefile b/Makefile index ad633b75a..824691b8a 100644 --- a/Makefile +++ b/Makefile @@ -1,53 +1,248 @@ -PROJECT_NAME = dms -VERSION = 99.99.99 -RELEASE ?= alpha -USER_NAME = actiontech-$(PROJECT_NAME) -GROUP_NAME = actiontech -GIT_LATEST_COMMIT_ID = $(shell git rev-parse HEAD) -DMS_UNIT_TEST_MYSQL_DB_CONTAINER = dms-mysql-unit-test-db -ARCH=$(shell uname -s| tr A-Z a-z) -DOCKER=$(shell which docker) -DOCKER_IMAGE_RPM = reg.actiontech.com/actiontech/$(PROJECT_NAME)-rpmbuild:v1 +# 当前 commit hash +HEAD_HASH = $(shell git rev-parse HEAD) +# 尝试获取稳定版标签 (不包含 -pre, -rc, -alpha, -beta 等后缀) +# grep -Ev '(-alpha|-beta|-rc|-pre)[0-9]*$$' 过滤掉带有预发布后缀的标签 +STABLE_TAG = $(shell git tag --points-at $(HEAD_HASH) | sort -rV | grep -Evi '(-pre)[0-9]*$$' | head -n 1 2>/dev/null) + +# 如果没有稳定版标签,则获取最新的预发布标签 +# 注意:这里我们重新获取所有标签,不再过滤,以确保能取到预发布版中最高的 +PRE_RELEASE_TAG = $(shell git tag --points-at $(HEAD_HASH) | sort -rV | head -n 1 2>/dev/null) + +# 如果存在稳定版标签,则使用稳定版;否则使用预发布版 +HEAD_TAG := $(if $(STABLE_TAG),$(STABLE_TAG),$(PRE_RELEASE_TAG)) + +# 当前分支名 +HEAD_BRANCH = $(shell git rev-parse --abbrev-ref HEAD) + +# 1. 如果HEAD存在tag,则GIT_VERSION=<版本名称>-<企业版/社区版> +# PS: 通常会在版本名称前增加字符“v”作为tag内容,当版本名称为 3.2411.0时,tag内容为v3.2411.0 +# e.g. tag为v3.2411.0时,社区版:GIT_VERSION=3.2411.0-ce a6355ff4cf8d181315a2b30341bc954b29576b11 +# e.g. tag为v3.2412.0-pre1-1时,社区版:GIT_VERSION=3.2412.0-pre1-1-ce f0bcb90e712cbdb6e16f122c1ebd623e90f9a905 +# 2. 如果HEAD没有tag,则GIT_VERSION=<分支名> +# e.g. 分支名为main时,GIT_VERSION=main a6355ff4cf8d181315a2b30341bc954b29576b11 +# e.g. 分支名为release-3.2411.x时,GIT_VERSION=release-3.2411.x a6355ff4cf8d181315a2b30341bc954b29576b11 +override GIT_VERSION = $(if $(HEAD_TAG),$(shell echo $(HEAD_TAG) | sed 's/^v//')-$(EDITION),$(HEAD_BRANCH))${CUSTOM} $(HEAD_HASH) +override GIT_COMMIT = $(shell git rev-parse HEAD) +override PROJECT_NAME = dms +override DOCKER = $(shell which docker) +override GOOS = linux +override OS_VERSION = el7 +override GO_BUILD_FLAGS = -mod=vendor +override CGO_ENABLED = 0 +override RPM_USER_GROUP_NAME = actiontech +override RPM_USER_NAME = actiontech-universe +override LDFLAGS = -ldflags "-X 'main.Version=${GIT_VERSION}' -X 'main.gitCommitID=${GIT_COMMIT}' -X 'main.defaultRunUser=${RPM_USER_NAME}'" + +DMS_GO_COMPILER_IMAGE ?= golang:1.24.1 +RPM_BUILD_IMAGE ?= rpmbuild/centos7 DOCKER_IMAGE_GO_SWAGGER = quay.io/goswagger/swagger -GIT_LATEST_COMMIT_ID = $(shell git rev-parse HEAD) -RPM_NAME = $(PROJECT_NAME)-$(VERSION)-${RELEASE}.el7.x86_64.rpm -RPM_BUILD_PATH = ./RPMS/x86_64/$(RPM_NAME) +DMS_UNIT_TEST_MYSQL_DB_CONTAINER = dms-mysql-unit-test-db +HOST_OS=$(shell uname -s| tr A-Z a-z) +HOST_ARCH=$(shell go env GOHOSTARCH) -gen_repo_fields: - go run ./internal/dms/cmd/gencli/gencli.go -d generate-node-repo-fields ./internal/dms/storage/model/ ./internal/dms/biz/ -build_dms: - GOOS=linux GOARCH=amd64 GOPROXY=https://goproxy.io,direct go build -tags ${RELEASE} -mod=vendor -ldflags "-X 'main.defaultRunUser=${USER_NAME}' -X 'main.version=${VERSION}' -X 'main.gitCommitID=${GIT_LATEST_COMMIT_ID}'" -o ./bin/dms ./internal/apiserver/cmd/server/main.go -dms_unit_test_prepare: - ./build/scripts/dms_run_unit_test_db_container.sh $(DMS_UNIT_TEST_MYSQL_DB_CONTAINER) -dms_unit_test_clean: - docker rm -f $(DMS_UNIT_TEST_MYSQL_DB_CONTAINER) -dms_test_dms: - go test -v -p 1 ./internal/dms/... -gen_swag: - ./internal/apiserver/cmd/swag/swagger_${ARCH}_amd64 generate spec -m -w ./internal/apiserver/cmd/server/ -o ./api/swagger.yaml - ./internal/apiserver/cmd/swag/swagger_${ARCH}_amd64 generate spec -i ./api/swagger.yaml -o ./api/swagger.json +GOARCH = amd64 +RPMBUILD_TARGET = x86_64 +ifeq ($(GOARCH), arm64) + RPMBUILD_TARGET = aarch64 +endif + +EDITION ?= ce +GO_BUILD_TAGS = dummyhead +ifeq ($(EDITION),ee) + GO_BUILD_TAGS :=$(GO_BUILD_TAGS),enterprise +else ifeq ($(EDITION),trial) + GO_BUILD_TAGS :=$(GO_BUILD_TAGS),trial +endif +RELEASE = qa +ifeq ($(RELEASE),rel) + GO_BUILD_TAGS :=$(GO_BUILD_TAGS),release +endif + +PRODUCT_CATEGORY = +ifeq ($(PRODUCT_CATEGORY),dms) + GO_BUILD_TAGS :=$(GO_BUILD_TAGS),dms +endif + +ifeq ($(IS_PRODUCTION_RELEASE),true) +# When performing a publishing operation, two cases: +# 1. if there is tag on current commit, means that +# we release new version on current branch just now. +# Set rpm name with tag name(v1.2109.0 -> 1.2109.0). +# +# 2. if there is no tag on current commit, means that +# current branch is on process. +# Set rpm name with current branch name(release-1.2109.x-ee or release-1.2109.x -> 1.2109.x). + PROJECT_VERSION = $(strip $(if $(HEAD_TAG),\ + $(shell echo $(HEAD_TAG) | sed 's/v\(.*\)/\1/'),\ + $(shell git rev-parse --abbrev-ref HEAD | sed 's/release-\(.*\)/\1/' | tr '-' '\n' | head -n1))) +else +# When performing daily packaging, set rpm name with current branch name(release-1.2109.x-ee or release-1.2109.x -> 1.2109.x). + PROJECT_VERSION = $(strip $(shell git rev-parse --abbrev-ref HEAD | sed 's/release-\(.*\)/\1/' | tr '-' '\n' | head -n1)) +endif + +override RPM_NAME = $(PROJECT_NAME)-$(EDITION)-$(PROJECT_VERSION).$(RELEASE).$(OS_VERSION).$(RPMBUILD_TARGET).rpm + +ADDITIONAL_PROJECT_NAME ?= +ifdef ADDITIONAL_PROJECT_NAME + override RPM_NAME := $(PROJECT_NAME)-$(ADDITIONAL_PROJECT_NAME)-$(EDITION)-$(PROJECT_VERSION).$(RELEASE).$(OS_VERSION).$(RPMBUILD_TARGET).rpm +endif + +override FTP_PATH = ftp://$(RELEASE_FTPD_HOST)/actiontech-$(PROJECT_NAME)/$(EDITION)/$(RELEASE)/$(PROJECT_VERSION)/$(RPM_NAME) + +############################### compiler ################################## +dlv_install: + CGO_ENABLED=$(CGO_ENABLED) GOOS=linux GOARCH=amd64 GOPROXY=https://goproxy.io,direct go build -gcflags "all=-N -l" $(GO_BUILD_FLAGS) ${LDFLAGS} -tags $(GO_BUILD_TAGS) -o ./bin/dms ./internal/apiserver/cmd/server/main.go + +install: + CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=$(GOARCH) go build $(GO_BUILD_FLAGS) ${LDFLAGS} -tags $(GO_BUILD_TAGS) -o ./bin/dms ./internal/apiserver/cmd/server/main.go + +docker_install: + $(DOCKER) run -v $(shell pwd):/universe --rm $(DMS_GO_COMPILER_IMAGE) sh -c "cd /universe && git config --global --add safe.directory /universe && make install $(MAKEFLAGS)" + +docker_rpm: docker_install + $(DOCKER) run -v $(shell pwd):/universe/dms --user root --rm -e VERBOSE=1 $(RPM_BUILD_IMAGE) sh -c "(mkdir -p /root/rpmbuild/SOURCES >/dev/null 2>&1);cd /root/rpmbuild/SOURCES; \ + (tar zcf ${PROJECT_NAME}.tar.gz /universe --transform 's/universe/${PROJECT_NAME}-$(GIT_COMMIT)/' >/tmp/build.log 2>&1) && \ + (rpmbuild --define 'group_name $(RPM_USER_GROUP_NAME)' --define 'user_name $(RPM_USER_NAME)' \ + --define 'commit $(GIT_COMMIT)' --define 'os_version $(OS_VERSION)' --define 'project_name $(PROJECT_NAME)' \ + --target $(RPMBUILD_TARGET) -bb -vv --with qa /universe/dms/build/dms.spec >>/tmp/build.log 2>&1) && \ + (cat /root/rpmbuild/RPMS/$(RPMBUILD_TARGET)/${PROJECT_NAME}-$(GIT_COMMIT)-$(OS_VERSION).$(RPMBUILD_TARGET).rpm) || (cat /tmp/build.log && exit 1)" > $(RPM_NAME) && \ + md5sum $(RPM_NAME) > $(RPM_NAME).md5 + +override PRE_DIR = $(dir $(CURDIR)) + +dms_sqle_provision_rpm_pre: docker_install + rm -rf builddir + + mkdir -p ./builddir/bin + mkdir -p ./builddir/config + mkdir -p ./builddir/static/logo + mkdir -p ./builddir/scripts + mkdir -p ./builddir/neo4j-community + mkdir -p ./builddir/lib + + # 前端文件 + cp -R ${PRE_DIR}dms-ui/packages/base/dist/* ./builddir/static/ + + # dms文件 + cp ./bin/dms ./builddir/bin/dms + cp ./config.yaml ./builddir/config/dms.yaml + cp ./build/service-file-template/dms.systemd ./builddir/scripts/dms.systemd + cp ./build/scripts/dms_sqle_provision.sh ./builddir/scripts/init_start.sh + cp ./build/logo/* ./builddir/static/logo/ + + # provision文件 + cp ${PRE_DIR}provision/bin/provision ./builddir/bin/provision + cp ${PRE_DIR}provision/build/service-file-template/neo4j.systemd ./builddir/scripts/neo4j.systemd + cp ${PRE_DIR}provision/build/service-file-template/provision.systemd ./builddir/scripts/provision.systemd + cp ${PRE_DIR}provision/config.yaml ./builddir/config/provision.yaml + cp -R ${PRE_DIR}provision/build/neo4j-community/* ./builddir/neo4j-community/ + cp -R ${PRE_DIR}provision/lib/* ./builddir/lib/ + + # sqle文件 + cp ${PRE_DIR}sqle/config.yaml.template ./builddir/config/sqle.yaml + cp ${PRE_DIR}sqle/bin/sqled ./builddir/bin/sqled + cp ${PRE_DIR}sqle/bin/scannerd ./builddir/bin/scannerd + cp ${PRE_DIR}sqle/scripts/sqled.systemd ./builddir/scripts/sqled.systemd + cp -R ${PRE_DIR}sqle/jdk ./builddir/jdk + + # 合并配置文件 + touch ./builddir/config/config.yaml + cat ./builddir/config/dms.yaml >> ./builddir/config/config.yaml + cat ./builddir/config/sqle.yaml >> ./builddir/config/config.yaml + cat ./builddir/config/provision.yaml >> ./builddir/config/config.yaml + rm ./builddir/config/dms.yaml ./builddir/config/sqle.yaml ./builddir/config/provision.yaml + +# 本地打包需要先编译sqle,provision,dms-ui相关文件 +dms_sqle_provision_rpm: dms_sqle_provision_rpm_pre + $(DOCKER) run -v $(shell pwd):/universe/dms --user root --rm $(RPM_BUILD_IMAGE) sh -c "(mkdir -p /root/rpmbuild/SOURCES >/dev/null 2>&1);cd /root/rpmbuild/SOURCES; \ + (tar zcf ${PROJECT_NAME}.tar.gz /universe/dms --transform 's/universe/${PROJECT_NAME}-$(GIT_COMMIT)/' > /tmp/build.log 2>&1) && \ + (rpmbuild --define 'group_name $(RPM_USER_GROUP_NAME)' --define 'user_name $(RPM_USER_NAME)' --define 'commit $(GIT_COMMIT)' --define 'os_version $(OS_VERSION)' \ + --target $(RPMBUILD_TARGET) --with qa -bb /universe/dms/build/dms_sqle_provision.spec >> /tmp/build.log 2>&1) && \ + (cat ~/rpmbuild/RPMS/$(RPMBUILD_TARGET)/${PROJECT_NAME}-$(GIT_COMMIT)-qa.$(OS_VERSION).$(RPMBUILD_TARGET).rpm) || (cat /tmp/build.log && exit 1)" > $(RPM_NAME) && \ + md5sum $(RPM_NAME) > $(RPM_NAME).md5 + +upload_rpm: + curl -T $(shell pwd)/$(RPM_NAME) $(FTP_PATH) --ftp-create-dirs + curl -T $(shell pwd)/$(RPM_NAME).md5 $(FTP_PATH).md5 --ftp-create-dirs + +############################### check ################################## validation_swag: $(DOCKER) run --rm -e VERBOSE=1 --volume=$(shell pwd):/source $(DOCKER_IMAGE_GO_SWAGGER) validate /source/api/swagger.json -open_swag_server: - ./internal/apiserver/cmd/swag/swagger_${ARCH}_amd64 serve --no-open -F=swagger --port 36666 ./api/swagger.yaml -upload_rpm: - curl -T $(RPM_BUILD_PATH) ftp://$(RELEASE_FTPD_HOST)/actiontech-$(PROJECT_NAME)/$(VERSION)/$(RPM_NAME) --ftp-create-dirs -rpm: - $(DOCKER) run --rm -e VERBOSE=1 --volume=$(shell pwd):/source --volume=$(shell pwd)/build:/spec --volume=$(shell pwd):/out \ - --env=PRE_BUILDDEP="mkdir /src && tar zcf /src/$(PROJECT_NAME).tar.gz /source --exclude=/source/bin --transform 's|source|$(PROJECT_NAME)-$(VERSION)|'" \ - --env=RPM_ARGS='-bb \ - --define "user_name $(USER_NAME)" --define "group_name $(GROUP_NAME)" --define "project_name $(PROJECT_NAME)" --define "version $(VERSION)" --define "release $(RELEASE)"' \ - $(DOCKER_IMAGE_RPM) dms.spec - -download_front: - wget ftp://$(RELEASE_FTPD_HOST)/actiontech-dms-ui/$(VERSION)/dms-ui-$(VERSION).tar.gz -O ./build/dms-ui-$(VERSION).tar.gz - mkdir -p ./build/static - tar zxf ./build/dms-ui-$(VERSION).tar.gz --strip-components 4 -C ./build/static/ golangci_lint: golangci-lint run -c ./build/golangci-lint/.golangci.yml --timeout=10m # check go lint on dev golangci_lint_dev: docker run --rm -v $(shell pwd):/src golangci/golangci-lint:v1.49 bash -c "cd /src && make golangci_lint" -dlv_install: - GOOS=linux GOARCH=amd64 GOPROXY=https://goproxy.io,direct go build -gcflags "all=-N -l" -tags ${RELEASE} -mod=vendor -ldflags "-X 'main.defaultRunUser=${USER_NAME}' -X 'main.version=${VERSION}' -X 'main.gitCommitID=${GIT_LATEST_COMMIT_ID}'" -o ./bin/dms ./internal/apiserver/cmd/server/main.go \ No newline at end of file + +############################### test ################################## +dms_unit_test_prepare: + ./build/scripts/dms_run_unit_test_db_container.sh $(DMS_UNIT_TEST_MYSQL_DB_CONTAINER) + +dms_unit_test_clean: + docker rm -f $(DMS_UNIT_TEST_MYSQL_DB_CONTAINER) + +dms_test_dms: + go test -v -p 1 ./internal/dms/... + +############################### generate ################################## +gen_repo_fields: + go run ./internal/dms/cmd/gencli/gencli.go -d generate-node-repo-fields ./internal/dms/storage/model/ ./internal/dms/biz/ + +docker_gen_swag: + $(DOCKER) run -v $(shell pwd):/universe --rm $(DMS_GO_COMPILER_IMAGE) sh -c "cd /universe &&make gen_swag" + +gen_swag: check_swag_version + ./internal/apiserver/cmd/swag/swagger_${HOST_OS}_${HOST_ARCH} generate spec -m -w ./internal/apiserver/cmd/server/ -o ./api/swagger.yaml + ./internal/apiserver/cmd/swag/swagger_${HOST_OS}_${HOST_ARCH} generate spec -i ./api/swagger.yaml -o ./api/swagger.json + +check_swag_version: + @SWAG_BIN=./internal/apiserver/cmd/swag/swagger_${HOST_OS}_${HOST_ARCH}; \ + SWAG_VER=$$($$SWAG_BIN version | grep 'version:' | awk '{print $$2}'); \ + MATCHING_GO_VER="unknown"; \ + MAPPINGS="v0.33.1:1.24.0 v0.31.0:1.22 v0.30.4:1.19 v0.29.0:1.18"; \ + for m in $$MAPPINGS; do \ + v=$${m%%:*}; g=$${m#*:}; \ + if [ "$$v" = "$$SWAG_VER" ]; then MATCHING_GO_VER="$$g"; break; fi; \ + done; \ + if [ "$$MATCHING_GO_VER" = "unknown" ]; then \ + echo "Fetching Go version for $$SWAG_VER from GitHub..."; \ + MATCHING_GO_VER=$$(curl -sL --connect-timeout 2 https://raw.githubusercontent.com/go-swagger/go-swagger/$$SWAG_VER/go.mod | grep "^go " | awk '{print $$2}' 2>/dev/null); \ + if [ -z "$$MATCHING_GO_VER" ]; then MATCHING_GO_VER="unknown"; fi; \ + fi; \ + PROJECT_GO_VER=$$(grep "^go " go.mod | awk '{print $$2}'); \ + SYSTEM_GO_VER=$$(go version | awk '{print $$3}' | sed 's/go//'); \ + echo "Project go.mod Version: $$PROJECT_GO_VER"; \ + echo "Swagger Version: $$SWAG_VER (Expected Go: $$MATCHING_GO_VER)"; \ + echo "System Go Version: $$SYSTEM_GO_VER"; \ + if [ "$$MATCHING_GO_VER" != "unknown" ]; then \ + PROJECT_GO_MAJOR=$$(echo $$PROJECT_GO_VER | cut -d. -f1,2); \ + MATCH_GO_VER_MAJOR=$$(echo $$MATCHING_GO_VER | cut -d. -f1,2); \ + SYSTEM_GO_MAJOR=$$(echo $$SYSTEM_GO_VER | cut -d. -f1,2); \ + if [ "$$PROJECT_GO_MAJOR" != "$$MATCH_GO_VER_MAJOR" ]; then \ + echo "Warning: Current Swagger generator ($$SWAG_VER, Go $$MATCHING_GO_VER) does not match project's go.mod ($$PROJECT_GO_VER)."; \ + echo "Please update the Swagger generator to match the project Go version."; \ + fi; \ + if [ "$$PROJECT_GO_MAJOR" != "$$SYSTEM_GO_MAJOR" ]; then \ + echo "Warning: Your system Go version ($$SYSTEM_GO_VER) does not match project's go.mod ($$PROJECT_GO_VER)."; \ + fi; \ + fi + +open_swag_server: + ./internal/apiserver/cmd/swag/swagger_${HOST_OS}_${HOST_ARCH} serve --no-open -F=swagger --port 36666 ./api/swagger.yaml + +######################################## i18n ########################################################## +GOBIN = ${shell pwd}/bin +LOCALE_PATH = ${shell pwd}/internal/pkg/locale + +install_i18n_tool: + GOBIN=$(GOBIN) go install -v github.com/nicksnyder/go-i18n/v2/goi18n@latest + +extract_i18n: + cd ${LOCALE_PATH} && $(GOBIN)/goi18n extract -sourceLanguage zh + +start_trans_i18n: + cd ${LOCALE_PATH} && touch translate.en.toml && $(GOBIN)/goi18n merge -sourceLanguage=zh active.*.toml + +end_trans_i18n: + cd ${LOCALE_PATH} && $(GOBIN)/goi18n merge active.en.toml translate.en.toml && rm -rf translate.en.toml diff --git a/api/base/v1/base.go b/api/base/v1/base.go deleted file mode 100644 index dc1fbd33e..000000000 --- a/api/base/v1/base.go +++ /dev/null @@ -1,23 +0,0 @@ -package v1 - -// GenericResp defines the return code and msg -// swagger:response GenericResp -type GenericResp struct { - // code - Code int `json:"code"` - // message - Msg string `json:"msg"` -} - -func (r *GenericResp) SetCode(code int) { - r.Code = code -} - -func (r *GenericResp) SetMsg(msg string) { - r.Msg = msg -} - -type GenericResper interface { - SetCode(code int) - SetMsg(msg string) -} diff --git a/api/dms/service/v1/base.go b/api/dms/service/v1/base.go index f580a2f78..f1878e159 100644 --- a/api/dms/service/v1/base.go +++ b/api/dms/service/v1/base.go @@ -1,14 +1,5 @@ package v1 -// swagger:enum Stat -type Stat string - -const ( - StatOK Stat = "正常" - StatDisable Stat = "被禁用" - StatUnknown Stat = "未知" -) - type UidWithName struct { Uid string `json:"uid"` Name string `json:"name"` diff --git a/api/dms/service/v1/basic.go b/api/dms/service/v1/basic.go new file mode 100644 index 000000000..768bd6bcb --- /dev/null +++ b/api/dms/service/v1/basic.go @@ -0,0 +1,37 @@ +package v1 + +import ( + "mime/multipart" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +type ComponentNameWithVersion struct { + Name string `json:"name"` + Version string `json:"version"` +} +type BasicInfo struct { + LogoUrl string `json:"logo_url"` + Title string `json:"title"` + Components []ComponentNameWithVersion `json:"components"` +} + +// swagger:model GetBasicInfoReply +type GetBasicInfoReply struct { + Data *BasicInfo `json:"data"` + // Generic reply + base.GenericResp +} + +// swagger:response GetStaticLogoReply +type GetStaticLogoReply struct { + // swagger:file + // in: body + File []byte +} + +// swagger:model +type PersonalizationReq struct { + Title string `json:"title" form:"title"` + File *multipart.FileHeader `json:"file" form:"file"` +} diff --git a/api/dms/service/v1/business_tag.go b/api/dms/service/v1/business_tag.go new file mode 100644 index 000000000..f4cb4323f --- /dev/null +++ b/api/dms/service/v1/business_tag.go @@ -0,0 +1,47 @@ +package v1 + +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +// swagger:model BusinessTag +type BusinessTag struct { + UID string `json:"uid,omitempty"` + // 业务标签最多50个字符 + Name string `json:"name" validate:"max=50"` +} + +// swagger:model +type CreateBusinessTagReq struct { + BusinessTag *BusinessTag `json:"business_tag" validate:"required"` +} + +// swagger:model +type UpdateBusinessTagReq struct { + // swagger:ignore + BusinessTagUID string `param:"business_tag_uid" json:"business_tag_uid"` + BusinessTag *BusinessTag `json:"business_tag" validate:"required"` +} + +// swagger:parameters ListBusinessTags +type ListBusinessTagReq struct { + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` +} + +// swagger:model ListBusinessTagsReply +type ListBusinessTagsReply struct { + Data []*BusinessTag `json:"data"` + Total int64 `json:"total_nums"` + base.GenericResp +} + +// swagger:parameters DeleteBusinessTag +type DeleteBusinessTagReq struct { + // in:path + // Required: true + BusinessTagUID string `param:"business_tag_uid" json:"business_tag_uid" validate:"required"` +} diff --git a/api/dms/service/v1/cb_operation_logs.go b/api/dms/service/v1/cb_operation_logs.go new file mode 100644 index 000000000..683fbddb3 --- /dev/null +++ b/api/dms/service/v1/cb_operation_logs.go @@ -0,0 +1,119 @@ +package v1 + +import ( + "time" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:parameters ListCBOperationLogs +type ListCBOperationLogsReq struct { + CbOperationLogsReq + // the maximum count of member to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of members to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` +} + +// swagger:model ListCBOperationLogsReply +type ListCBOperationLogsReply struct { + // 执行SQL总量 + ExecSQLTotal int64 `json:"exec_sql_total"` + // 执行成功率 + ExecSuccessRate float64 `json:"exec_success_rate"` + // 审核拦截的异常SQL数量 + AuditInterceptedSQLCount int64 `json:"audit_intercepted_sql_count"` + // 执行失败的SQL + ExecFailedSQLCount int64 `json:"exec_failed_sql_count"` + // list cb operation logs reply + Data []*CBOperationLog `json:"data"` + Total int64 `json:"total_nums"` + // Generic reply + base.GenericResp +} + +type CBOperationLog struct { + UID string `json:"uid"` + OperationPerson UidWithName `json:"operation_person"` + OperationTime time.Time `json:"operation_time"` + DBService UidWithDBServiceName `json:"db_service"` + Operation Operation `json:"operation"` + SessionID string `json:"session_id"` + OperationIp string `json:"operation_ip"` + AuditResult []*AuditSQLResult `json:"audit_result"` + ExecResult string `json:"exec_result"` + ExecTimeSecond int `json:"exec_time_second"` + ResultSetRowCount int64 `json:"result_set_row_count"` + WorkflowID *string `json:"workflow_id"` +} + +// swagger:enum CbOperationType +type CbOperationType string + +const ( + CbOperationTypeSQL CbOperationType = "SQL" +) + +type Operation struct { + OperationType CbOperationType `json:"operation_type"` + OperationDetail string `json:"operation_detail"` +} + +type UidWithDBServiceName struct { + Uid string `json:"uid"` + Name string `json:"name"` +} + +// swagger:parameters ExportCBOperationLogs +type ExportCBOperationLogsReq struct { + CbOperationLogsReq +} + +// swagger:response ExportCBOperationLogsReply +type ExportCBOperationLogsReply struct { + // swagger:file + // in: body + File []byte +} + +type CbOperationLogsReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // in:query + FilterOperationPersonUID string `json:"filter_operation_person_uid" query:"filter_operation_person_uid"` + // in:query + FilterOperationTimeFrom string `json:"filter_operation_time_from" query:"filter_operation_time_from"` + // in:query + FilterOperationTimeTo string `json:"filter_operation_time_to" query:"filter_operation_time_to"` + // in:query + FilterDBServiceUID string `json:"filter_db_service_uid" query:"filter_db_service_uid"` + // in:query + FilterExecResult string `json:"filter_exec_result" query:"filter_exec_result"` + // filter fuzzy key word for operation_detail/operation_ip + // in:query + FuzzyKeyword string `json:"fuzzy_keyword" query:"fuzzy_keyword"` +} + +// swagger:parameters GetCBOperationLogTips +type GetCBOperationLogTipsReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:model GetCBOperationLogTipsReply +type GetCBOperationLogTipsReply struct { + // Generic reply + base.GenericResp + Data *CBOperationLogTips `json:"data"` +} + +type CBOperationLogTips struct { + ExecResult []string `json:"exec_result"` +} diff --git a/api/dms/service/v1/cloudbeaver.go b/api/dms/service/v1/cloudbeaver.go index 7f56edf3a..a48c213c2 100644 --- a/api/dms/service/v1/cloudbeaver.go +++ b/api/dms/service/v1/cloudbeaver.go @@ -1,13 +1,15 @@ package v1 -import base "github.com/actiontech/dms/api/base/v1" +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" // swagger:model GetSQLQueryConfigurationReply type GetSQLQueryConfigurationReply struct { - Payload struct { + Data struct { EnableSQLQuery bool `json:"enable_sql_query"` SQLQueryRootURI string `json:"sql_query_root_uri"` - } `json:"payload"` + EnableOdcQuery bool `json:"enable_odc_query"` + OdcQueryRootURI string `json:"odc_query_root_uri"` + } `json:"data"` // Generic reply base.GenericResp } diff --git a/api/dms/service/v1/company_notice.go b/api/dms/service/v1/company_notice.go new file mode 100644 index 000000000..4575e7dad --- /dev/null +++ b/api/dms/service/v1/company_notice.go @@ -0,0 +1,50 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + "time" +) + +// swagger:parameters GetCompanyNotice +type GetCompanyNoticeReq struct { + // When true, return the latest notice record regardless of the display time window (e.g. expired or not yet started); intended for admin edit forms. + // in: query + IncludeLatestOutsidePeriod bool `query:"include_latest_outside_period" json:"include_latest_outside_period"` +} + +// A companynotice +type CompanyNotice struct { + // companynotice info + NoticeStr string `json:"notice_str"` + // companynotice creator name + CreateUserName string `json:"create_user_name"` + // current user has been read + ReadByCurrentUser bool `json:"read_by_current_user"` + // notice show start time + StartTime *time.Time `json:"start_time,omitempty"` + // notice expire time + ExpireTime *time.Time `json:"expire_time,omitempty"` +} + +// swagger:model GetCompanyNoticeReply +type GetCompanyNoticeReply struct { + Data CompanyNotice `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:model +type UpdateCompanyNoticeReq struct { + UpdateCompanyNotice UpdateCompanyNotice `json:"company_notice" validate:"required"` +} + +// A companynotice +type UpdateCompanyNotice struct { + // companynotice info + NoticeStr *string `json:"notice_str" validate:"required"` + // notice show start time + StartTime *time.Time `json:"start_time" validate:"required"` + // notice show end time + EndTime *time.Time `json:"end_time" validate:"required"` +} diff --git a/api/dms/service/v1/configuration.go b/api/dms/service/v1/configuration.go index b8a595a04..fd5aa09cd 100644 --- a/api/dms/service/v1/configuration.go +++ b/api/dms/service/v1/configuration.go @@ -1,54 +1,92 @@ package v1 -import base "github.com/actiontech/dms/api/base/v1" +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +// swagger:model GetLoginTipsReply +type GetLoginTipsReply struct { + Data LoginTipsResData `json:"data"` + + // Generic reply + base.GenericResp +} + +type LoginTipsResData struct { + LoginButtonText string `json:"login_button_text"` + DisableUserPwdLogin bool `json:"disable_user_pwd_login"` +} + +// swagger:model +type UpdateLoginConfigurationReq struct { + LoginConfiguration LoginConfiguration `json:"login" validate:"required"` +} + +type LoginConfiguration struct { + LoginButtonText *string `json:"login_button_text"` + DisableUserPwdLogin *bool `json:"disable_user_pwd_login"` +} type GetOauth2ConfigurationResData struct { - EnableOauth2 bool `json:"enable_oauth2"` - ClientID string `json:"client_id"` - ClientHost string `json:"client_host"` - ServerAuthUrl string `json:"server_auth_url"` - ServerTokenUrl string `json:"server_token_url"` - ServerUserIdUrl string `json:"server_user_id_url"` - Scopes []string `json:"scopes"` - AccessTokenTag string `json:"access_token_tag"` - UserIdTag string `json:"user_id_tag"` - LoginTip string `json:"login_tip"` + EnableOauth2 bool `json:"enable_oauth2"` + SkipCheckState bool `json:"skip_check_state"` + EnableManuallyBind bool `json:"enable_manually_bind"` + AutoBindSameNameUser bool `json:"auto_bind_same_name_user"` + AutoCreateUser bool `json:"auto_create_user"` + ClientID string `json:"client_id"` + ClientHost string `json:"client_host"` + ServerAuthUrl string `json:"server_auth_url"` + ServerTokenUrl string `json:"server_token_url"` + ServerUserIdUrl string `json:"server_user_id_url"` + ServerLogoutUrl string `json:"server_logout_url"` + Scopes []string `json:"scopes"` + AccessTokenTag string `json:"access_token_tag"` + UserIdTag string `json:"user_id_tag"` + UserEmailTag string `json:"user_email_tag"` + UserWeChatTag string `json:"user_wechat_tag"` + LoginPermExpr string `json:"login_perm_expr"` // GJSON查询表达式 eg:`resource_access.sqle.roles.#(=="login")` 即判断查询的json文档的 resource_access.sqle.roles 中是否存在login元素 + LoginTip string `json:"login_tip"` + BackChannelLogoutUri string `json:"back_channel_logout_uri"` // sqle实现OIDC后端通道注销接口的地址 } // swagger:model GetOauth2ConfigurationResDataReply type GetOauth2ConfigurationReply struct { - Payload struct { - Data GetOauth2ConfigurationResData `json:"data"` - } `json:"payload"` + Data GetOauth2ConfigurationResData `json:"data"` + // Generic reply base.GenericResp } -// swagger:parameters UpdateOauth2Configuration +// swagger:model type Oauth2ConfigurationReq struct { - // update oauth2 configuration - // in:body Oauth2Configuration Oauth2Configuration `json:"oauth2" validate:"required"` } type Oauth2Configuration struct { - EnableOauth2 *bool `json:"enable_oauth2"` - ClientID *string `json:"client_id"` - ClientKey *string `json:"client_key"` - ClientHost *string `json:"client_host"` - ServerAuthUrl *string `json:"server_auth_url"` - ServerTokenUrl *string `json:"server_token_url"` - ServerUserIdUrl *string `json:"server_user_id_url"` - Scopes *[]string `json:"scopes"` - AccessTokenTag *string `json:"access_token_tag"` - UserIdTag *string `json:"user_id_tag"` - LoginTip *string `json:"login_tip"` + EnableOauth2 *bool `json:"enable_oauth2"` + SkipCheckState *bool `json:"skip_check_state"` + EnableManuallyBind *bool `json:"enable_manually_bind"` + AutoBindSameNameUser *bool `json:"auto_bind_same_name_user"` + AutoCreateUser *bool `json:"auto_create_user"` + AutoCreateUserPWD *string `json:"auto_create_user_pwd"` + ClientID *string `json:"client_id"` + ClientKey *string `json:"client_key"` + ClientHost *string `json:"client_host"` + ServerAuthUrl *string `json:"server_auth_url"` + ServerTokenUrl *string `json:"server_token_url"` + ServerUserIdUrl *string `json:"server_user_id_url"` + ServerLogoutUrl *string `json:"server_logout_url"` + Scopes *[]string `json:"scopes"` + AccessTokenTag *string `json:"access_token_tag"` + UserIdTag *string `json:"user_id_tag"` + UserEmailTag *string `json:"user_email_tag"` + UserWeChatTag *string `json:"user_wechat_tag"` + LoginPermExpr *string `json:"login_perm_expr"` + // Maximum: 28 + LoginTip *string `json:"login_tip" validate:"max=28"` } // swagger:model GetOauth2TipsReply type GetOauth2TipsReply struct { - Payload struct { - Data GetOauth2TipsResData `json:"data"` - } `json:"payload"` + Data GetOauth2TipsResData `json:"data"` + // Generic reply base.GenericResp } @@ -58,18 +96,18 @@ type GetOauth2TipsResData struct { LoginTip string `json:"login_tip"` } -// swagger:parameters BindOauth2User +// swagger:model type BindOauth2UserReq struct { - UserName string `json:"user_name" form:"user_name" validate:"required"` - Pwd string `json:"pwd" form:"pwd" validate:"required"` - Oauth2Token string `json:"oauth2_token" form:"oauth2_token" validate:"required"` + UserName string `json:"user_name" form:"user_name" validate:"required"` + Pwd string `json:"pwd" form:"pwd" validate:"required"` + Oauth2Token string `json:"oauth2_token" form:"oauth2_token" validate:"required"` + RefreshToken string `json:"refresh_token" form:"refresh_token"` } // swagger:model BindOauth2UserReply type BindOauth2UserReply struct { - Payload struct { - Data BindOauth2UserResData `json:"data"` - } `json:"payload"` + Data BindOauth2UserResData `json:"data"` + // Generic reply base.GenericResp } @@ -80,15 +118,14 @@ type BindOauth2UserResData struct { // swagger:parameters Oauth2Callback type Oauth2CallbackReq struct { - State string `json:"state" query:"state" validate:"required"` + State string `json:"state" query:"state"` Code string `json:"code" query:"code" validate:"required"` } // swagger:model GetLDAPConfigurationResDataReply type GetLDAPConfigurationReply struct { - Payload struct { - Data LDAPConfigurationResData `json:"data"` - } `json:"payload"` + Data LDAPConfigurationResData `json:"data"` + // Generic reply base.GenericResp } @@ -104,30 +141,27 @@ type LDAPConfigurationResData struct { LdapUserEmailRdnKey string `json:"ldap_user_email_rdn_key"` } -// swagger:parameters UpdateLDAPConfiguration +// swagger:model type UpdateLDAPConfigurationReq struct { - // update ldap configuration - // in:body LDAPConfiguration LDAPConfiguration `json:"ldap" validate:"required"` } type LDAPConfiguration struct { EnableLdap *bool `json:"enable_ldap"` EnableSSL *bool `json:"enable_ssl"` - LdapServerHost *string `json:"ldap_server_host"` - LdapServerPort *string `json:"ldap_server_port"` - LdapConnectDn *string `json:"ldap_connect_dn"` - LdapConnectPwd *string `json:"ldap_connect_pwd"` - LdapSearchBaseDn *string `json:"ldap_search_base_dn"` - LdapUserNameRdnKey *string `json:"ldap_user_name_rdn_key"` + LdapServerHost *string `json:"ldap_server_host" validate:"omitempty,min=1"` + LdapServerPort *string `json:"ldap_server_port" validate:"omitempty,min=1"` + LdapConnectDn *string `json:"ldap_connect_dn" validate:"omitempty,min=1"` + LdapConnectPwd *string `json:"ldap_connect_pwd" validate:"omitempty,min=1"` + LdapSearchBaseDn *string `json:"ldap_search_base_dn" validate:"omitempty,min=1"` + LdapUserNameRdnKey *string `json:"ldap_user_name_rdn_key" validate:"omitempty,min=1"` LdapUserEmailRdnKey *string `json:"ldap_user_email_rdn_key"` } // swagger:model GetSMTPConfigurationReply type GetSMTPConfigurationReply struct { - Payload struct { - Data SMTPConfigurationResData `json:"data"` - } `json:"payload"` + Data SMTPConfigurationResData `json:"data"` + // Generic reply base.GenericResp } @@ -140,10 +174,8 @@ type SMTPConfigurationResData struct { IsSkipVerify bool `json:"is_skip_verify"` } -// swagger:parameters UpdateSMTPConfiguration +// swagger:model type UpdateSMTPConfigurationReq struct { - // update smtp configuration - // in:body UpdateSMTPConfiguration UpdateSMTPConfiguration `json:"smtp_configuration" validate:"required"` } @@ -156,10 +188,8 @@ type UpdateSMTPConfiguration struct { IsSkipVerify *bool `json:"is_skip_verify" form:"is_skip_verify" description:"是否启用邮件通知"` } -// swagger:parameters TestSMTPConfiguration +// swagger:model type TestSMTPConfigurationReq struct { - // test smtp configuration - // in:body TestSMTPConfiguration TestSMTPConfiguration `json:"test_smtp_configuration" validate:"required,email"` } @@ -169,9 +199,8 @@ type TestSMTPConfiguration struct { // swagger:model TestSMTPConfigurationReply type TestSMTPConfigurationReply struct { - Payload struct { - Data TestSMTPConfigurationResData `json:"data"` - } `json:"payload"` + Data TestSMTPConfigurationResData `json:"data"` + // Generic reply base.GenericResp } @@ -183,9 +212,8 @@ type TestSMTPConfigurationResData struct { // swagger:model GetWeChatConfigurationReply type GetWeChatConfigurationReply struct { - Payload struct { - Data WeChatConfigurationResData `json:"data"` - } `json:"payload"` + Data WeChatConfigurationResData `json:"data"` + // Generic reply base.GenericResp } @@ -198,10 +226,8 @@ type WeChatConfigurationResData struct { ProxyIP string `json:"proxy_ip"` } -// swagger:parameters UpdateWeChatConfiguration +// swagger:model type UpdateWeChatConfigurationReq struct { - // update wechat configuration - // in:body UpdateWeChatConfiguration UpdateWeChatConfiguration `json:"update_wechat_configuration"` } @@ -214,10 +240,8 @@ type UpdateWeChatConfiguration struct { ProxyIP *string `json:"proxy_ip" from:"proxy_ip" description:"企业微信代理服务器IP"` } -// swagger:parameters TestWeChatConfiguration +// swagger:model type TestWeChatConfigurationReq struct { - // test wechat configuration - // in:body TestWeChatConfiguration TestWeChatConfiguration `json:"test_wechat_configuration"` } @@ -227,9 +251,8 @@ type TestWeChatConfiguration struct { // swagger:model TestWeChatConfigurationReply type TestWeChatConfigurationReply struct { - Payload struct { - Data TestWeChatConfigurationResData `json:"data"` - } `json:"payload"` + Data TestWeChatConfigurationResData `json:"data"` + // Generic reply base.GenericResp } @@ -241,9 +264,8 @@ type TestWeChatConfigurationResData struct { // swagger:model GetFeishuConfigurationReply type GetFeishuConfigurationReply struct { - Payload struct { - Data FeishuConfigurationResData `json:"data"` - } `json:"payload"` + Data FeishuConfigurationResData `json:"data"` + // Generic reply base.GenericResp } @@ -253,10 +275,8 @@ type FeishuConfigurationResData struct { IsFeishuNotificationEnabled bool `json:"is_feishu_notification_enabled"` } -// swagger:parameters UpdateFeishuConfiguration +// swagger:model type UpdateFeishuConfigurationReq struct { - // update feishu configuration - // in:body UpdateFeishuConfiguration UpdateFeishuConfiguration `json:"update_feishu_configuration"` } @@ -266,10 +286,94 @@ type UpdateFeishuConfiguration struct { IsFeishuNotificationEnabled *bool `json:"is_feishu_notification_enabled" from:"is_feishu_notification_enabled" description:"是否启用飞书推送"` } -// swagger:parameters TestFeishuConfiguration +// swagger:model +type UpdateSmsConfigurationReq struct { + UpdateSmsConfiguration UpdateSmsConfiguration `json:"update_sms_configuration"` +} + +// swagger:model +type TestSmsConfigurationReq struct { + TestSmsConfiguration TestSmsConfiguration `json:"test_sms_configuration"` +} + +type TestSmsConfiguration struct { + RecipientPhone string `json:"recipient_phone" validate:"required"` +} + +// swagger:model TestSmsConfigurationReply +type TestSmsConfigurationReply struct { + Data TestSmsConfigurationResData `json:"data"` + + // Generic reply + base.GenericResp +} + +type TestSmsConfigurationResData struct { + IsSmsSendNormal bool `json:"is_smtp_send_normal"` + SendErrorMessage string `json:"send_error_message,omitempty"` +} + +// swagger:model +type VerifySmsCodeReq struct { + Code string `json:"code" validate:"required"` + Username string `json:"username" validate:"required"` +} + +// swagger:model +type SendSmsCodeReq struct { + Username string `json:"username" validate:"required"` +} + +type UpdateSmsConfiguration struct { + EnableSms *bool `json:"enable_sms" form:"enable_sms"` + Url *string `json:"url" form:"url"` + SmsType *string `json:"sms_type" form:"sms_type" enums:"ali,tencent,webhook"` + Configuration *map[string]string `json:"configuration" form:"configuration"` +} + +// swagger:model GetSmsConfigurationReply +type GetSmsConfigurationReply struct { + Data GetSmsConfigurationReplyItem `json:"data"` + + // Generic reply + base.GenericResp +} + +type GetSmsConfigurationReplyItem struct { + Enable bool `json:"enable" description:"是否启用"` + Url string `json:"url" description:"服务地址"` + SmsType string `json:"sms_type" description:"短信服务类型"` + Configuration map[string]string `json:"configuration" description:"配置详情"` +} + +// swagger:model SendSmsCodeReply +type SendSmsCodeReply struct { + Data SendSmsCodeReplyData `json:"data"` + + // Generic reply + base.GenericResp +} + +type SendSmsCodeReplyData struct { + IsSmsCodeSentNormally bool `json:"is_sms_code_sent_normally"` + SendErrorMessage string `json:"send_error_message,omitempty"` +} + +// swagger:model VerifySmsCodeReply +type VerifySmsCodeReply struct { + Data VerifySmsCodeReplyData `json:"data"` + + // Generic reply + base.GenericResp +} + +type VerifySmsCodeReplyData struct { + IsVerifyNormally bool `json:"is_verify_sent_normally"` + VerifyErrorMessage string `json:"verify_error_message,omitempty"` +} + +// swagger:model type TestFeishuConfigurationReq struct { - // test feishu configuration - // in:body TestFeishuConfiguration TestFeishuConfiguration `json:"test_feishu_configuration" validate:"required"` } @@ -288,9 +392,8 @@ type TestFeishuConfiguration struct { // swagger:model TestFeishuConfigurationReply type TestFeishuConfigurationReply struct { - Payload struct { - Data TestFeishuConfigurationResData `json:"data"` - } `json:"payload"` + Data TestFeishuConfigurationResData `json:"data"` + // Generic reply base.GenericResp } @@ -300,11 +403,19 @@ type TestFeishuConfigurationResData struct { ErrorMessage string `json:"error_message,omitempty"` } +type GetWebHookConfigurationReplyItem struct { + Enable bool `json:"enable" description:"是否启用"` + // minlength(3) maxlength(100) + MaxRetryTimes int `json:"max_retry_times" description:"最大重试次数"` + RetryIntervalSeconds int `json:"retry_interval_seconds" description:"请求重试间隔"` + Token string `json:"token" description:"token 令牌"` + URL string `json:"url" description:"回调API URL"` +} + // swagger:model GetWebHookConfigurationReply type GetWebHookConfigurationReply struct { - Payload struct { - Data WebHookConfigurationData `json:"data"` - } `json:"payload"` + Data GetWebHookConfigurationReplyItem `json:"data"` + // Generic reply base.GenericResp } @@ -318,18 +429,15 @@ type WebHookConfigurationData struct { URL *string `json:"url" description:"回调API URL"` } -// swagger:parameters UpdateWebHookConfiguration +// swagger:model type UpdateWebHookConfigurationReq struct { - // test webhook configuration - // in:body UpdateWebHookConfiguration WebHookConfigurationData `json:"webhook_config"` } // swagger:model TestWebHookConfigurationReply type TestWebHookConfigurationReply struct { - Payload struct { - Data TestWebHookConfigurationResData `json:"data"` - } `json:"payload"` + Data TestWebHookConfigurationResData `json:"data"` + // Generic reply base.GenericResp } diff --git a/api/dms/service/v1/data_export_task.go b/api/dms/service/v1/data_export_task.go new file mode 100644 index 000000000..37b8eb5ae --- /dev/null +++ b/api/dms/service/v1/data_export_task.go @@ -0,0 +1,174 @@ +package v1 + +import ( + "time" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:model +type AddDataExportTaskReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DataExportTasks []DataExportTask `json:"data_export_tasks"` +} + +type DataExportTask struct { + // DB Service uid + // Required: true + DBServiceUid string `json:"db_service_uid" validate:"required"` + // DB Service name + // Required: false + DatabaseName string `json:"database_name"` + // The exported SQL statement executed. it's necessary when ExportType is SQL + // SELECT * FROM DMS_test LIMIT 20; + ExportSQL string `json:"export_sql"` +} + +// swagger:model AddDataExportTaskReply +type AddDataExportTaskReply struct { + // add data export workflow reply + Data struct { + // data export task UIDs + Uids []string `json:"data_export_task_uids"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:parameters BatchGetDataExportTask +type BatchGetDataExportTaskReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // Required: true + // in: query + TaskUids string `query:"data_export_task_uids" json:"data_export_task_uids" validate:"required"` +} + +// swagger:model BatchGetDataExportTaskReply +type BatchGetDataExportTaskReply struct { + Data []*GetDataExportTask `json:"data"` + + // Generic reply + base.GenericResp +} + +type TaskDBInfo struct { + UidWithName + DBType string `json:"db_type"` + DatabaseName string `json:"database_name"` +} + +// swagger:enum DataExportTaskStatus +type DataExportTaskStatus string + +// 导出任务状态常量 +const ( + StatusInit DataExportTaskStatus = "init" + StatusExporting DataExportTaskStatus = "exporting" + StatusFinish DataExportTaskStatus = "finish" + StatusFailed DataExportTaskStatus = "failed" + StatusFileDeleted DataExportTaskStatus = "file_deleted" +) + +type GetDataExportTask struct { + TaskUid string `json:"task_uid"` + DBInfo TaskDBInfo `json:"db_info"` + Status DataExportTaskStatus `json:"status"` + ExportStartTime *time.Time `json:"export_start_time,omitempty"` + ExportEndTime *time.Time `json:"export_end_time,omitempty"` + FileName string `json:"file_name"` // 导出文件名 + AuditResult AuditTaskResult `json:"audit_result"` + ExportType string `json:"export_type"` // Export Type example: SQL Meta + ExportFileType string `json:"export_file_type"` // Export Content example: CSV SQL EXCEL + +} + +// SQL审核结果 +type AuditTaskResult struct { + AuditLevel string `json:"audit_level" enums:"normal,notice,warn,error,"` + Score int32 `json:"score"` + PassRate float64 `json:"pass_rate"` +} + +// swagger:parameters ListDataExportTaskSQLs +type ListDataExportTaskSQLsReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // Required: true + // in:path + DataExportTaskUid string `param:"data_export_task_uid" json:"data_export_task_uid" validate:"required"` + // the maximum count of member to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of members to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` +} + +// swagger:model ListDataExportTaskSQLsReply +type ListDataExportTaskSQLsReply struct { + Data []*ListDataExportTaskSQL `json:"data"` + Total int64 `json:"total_nums"` + // Generic reply + base.GenericResp +} + +type ListDataExportTaskSQL struct { + ID uint `json:"uid"` + ExportSQL string `json:"sql"` + ExportResult string `json:"export_result"` // 导出结果 + ExportSQLType string `json:"export_sql_type"` + AuditLevel string `json:"audit_level"` + AuditSQLResult []AuditSQLResult `json:"audit_sql_result"` +} +type AuditSQLResult struct { + Level string `json:"level" example:"warn"` + Message string `json:"message" example:"避免使用不必要的内置函数md5()"` + ErrorInfo string `json:"error_info"` + ExecutionFailed bool `json:"execution_failed" example:"false"` + RuleName string `json:"rule_name"` + DBType string `json:"db_type"` +} + +// swagger:parameters DownloadDataExportTask +type DownloadDataExportTaskReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // Required: true + // in:path + DataExportTaskUid string `param:"data_export_task_uid" json:"data_export_task_uid" validate:"required"` +} + +// swagger:response DownloadDataExportTaskReply +type DownloadDataExportTaskReply struct { + // swagger:file + // in: body + File []byte +} + +// swagger:parameters DownloadDataExportTaskSQLs +type DownloadDataExportTaskSQLsReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // Required: true + // in:path + DataExportTaskUid string `param:"data_export_task_uid" json:"data_export_task_uid" validate:"required"` +} + +// swagger:response DownloadDataExportTaskSQLsReply +type DownloadDataExportTaskSQLsReply struct { + // swagger:file + // in: body + File []byte +} diff --git a/api/dms/service/v1/data_export_workflow.go b/api/dms/service/v1/data_export_workflow.go new file mode 100644 index 000000000..5a51d9437 --- /dev/null +++ b/api/dms/service/v1/data_export_workflow.go @@ -0,0 +1,285 @@ +package v1 + +import ( + "time" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +// swagger:model +type AddDataExportWorkflowReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DataExportWorkflow DataExportWorkflow `json:"data_export_workflow"` +} + +type DataExportWorkflow struct { + // name + // Required: true + // example: d1 + Name string `json:"name" validate:"required"` + // desc + // Required: false + // example: transaction data export + Desc string `json:"desc"` + // export task info + // Required: true + // example: [export_task_uid1,export_task_uid2] + Tasks []Task `json:"tasks" validate:"required"` +} + +// swagger:model AddDataExportWorkflowReply +type AddDataExportWorkflowReply struct { + // add data export workflow reply + Data struct { + // data export workflow UID + Uid string `json:"export_data_workflow_uid"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:parameters ListDataExportWorkflows ListAllDataExportWorkflows +type ListDataExportWorkflowsReq struct { + // project id + // Required: false + // in:path + ProjectUid string `param:"project_uid" json:"project_uid"` + // the maximum count of member to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of members to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // filter the status + // in:query + FilterByStatus DataExportWorkflowStatus `query:"filter_by_status" json:"filter_by_status"` + // filter create user id + // in:query + FilterByCreateUserUid string `json:"filter_by_create_user_uid" query:"filter_by_create_user_uid"` + // filter current assignee user id + // in:query + FilterCurrentStepAssigneeUserUid string `json:"filter_current_step_assignee_user_uid" query:"filter_current_step_assignee_user_uid"` + // filter db_service id + // in:query + FilterByDBServiceUid string `json:"filter_by_db_service_uid" query:"filter_by_db_service_uid"` + // filter create time from + // in:query + FilterCreateTimeFrom string `json:"filter_create_time_from" query:"filter_create_time_from"` + // filter create time end + // in:query + FilterCreateTimeTo string `json:"filter_create_time_to" query:"filter_create_time_to"` + // filter fuzzy key word for id/name + // in:query + FuzzyKeyword string `json:"fuzzy_keyword" query:"fuzzy_keyword"` +} + +// swagger:parameters FilterGlobalDataExportWorkflowReq +type FilterGlobalDataExportWorkflowReq struct { + // filter status list + // in:query + FilterStatusList []DataExportWorkflowStatus `json:"filter_status_list" query:"filter_status_list"` + // filter db service uid + // in:query + FilterDBServiceUid string `json:"filter_db_service_uid" query:"filter_db_service_uid"` + // filter project priority + // in:query + FilterCurrentStepAssigneeUserId string `json:"filter_current_step_assignee_user_id" query:"filter_current_step_assignee_user_id"` + // filter project uids + // in:query + FilterProjectUids []string `json:"filter_project_uids" query:"filter_project_uids"` + // filter project uid + // in:query + FilterProjectUid string `json:"filter_project_uid" query:"filter_project_uid"` + // the maximum count of member to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of members to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // filter the status + // in:query + FilterByStatus DataExportWorkflowStatus `query:"filter_by_status" json:"filter_by_status"` + // filter create user id + // in:query + FilterByCreateUserUid string `json:"filter_by_create_user_uid" query:"filter_by_create_user_uid"` + // filter current assignee user id + // in:query + FilterCurrentStepAssigneeUserUid string `json:"filter_current_step_assignee_user_uid" query:"filter_current_step_assignee_user_uid"` + // filter db_service id + // in:query + FilterByDBServiceUid string `json:"filter_by_db_service_uid" query:"filter_by_db_service_uid"` + // filter fuzzy key word for id/name + // in:query + FuzzyKeyword string `json:"fuzzy_keyword" query:"fuzzy_keyword"` +} + +// swagger:model GetGlobalDataExportWorkflowsReply +type GetGlobalDataExportWorkflowsReply struct { + Data []*GlobalDataExportWorkflow `json:"data"` + Total int64 `json:"total_nums"` + // Generic reply + base.GenericResp +} + +type GlobalDataExportWorkflow struct { + WorkflowID string `json:"workflow_uid"` // 数据导出工单ID + WorkflowName string `json:"workflow_name"` // 数据导出工单的名称 + Description string `json:"desc"` // 数据导出工单的描述 + Creater UidWithName `json:"creater"` // 数据导出工单的创建人 + CreatedAt time.Time `json:"created_at"` // 数据导出工单的创建时间 + Status DataExportWorkflowStatus `json:"status"` // 数据导出工单的状态 + + CurrentStepAssigneeUsers []UidWithName `json:"current_step_assignee_user_list"` // 工单待操作人 + DBServiceInfos []*dmsCommonV1.DBServiceUidWithNameInfo `json:"db_service_info,omitempty"` // 所属数据源信息 + ProjectInfo *dmsCommonV1.ProjectInfo `json:"project_info,omitempty"` // 所属项目信息 +} + +// swagger:model ListDataExportWorkflowsReply +type ListDataExportWorkflowsReply struct { + Data []*ListDataExportWorkflow `json:"data"` + Total int64 `json:"total_nums"` + // Generic reply + base.GenericResp +} + +type ListDataExportWorkflow struct { + ProjectUid string `json:"project_uid"` + ProjectName string `json:"project_name"` // 项目名称 + WorkflowID string `json:"workflow_uid"` // 数据导出工单ID + WorkflowName string `json:"workflow_name"` // 数据导出工单的名称 + Description string `json:"desc"` // 数据导出工单的描述 + Creater UidWithName `json:"creater"` // 数据导出工单的创建人 + CreatedAt time.Time `json:"created_at"` // 数据导出工单的创建时间 + ExportedAt time.Time `json:"exported_at"` // 执行数据导出工单的时间 + Status DataExportWorkflowStatus `json:"status"` // 数据导出工单的状态 + + CurrentStepAssigneeUsers []UidWithName `json:"current_step_assignee_user_list"` // 工单待操作人 + DBServiceInfos []*dmsCommonV1.DBServiceUidWithNameInfo `json:"db_service_info,omitempty"` // 所属数据源信息 + ProjectInfo *dmsCommonV1.ProjectInfo `json:"project_info,omitempty"` // 所属项目信息 +} + +// swagger:enum DataExportWorkflowStatus +type DataExportWorkflowStatus string + +const ( + DataExportWorkflowStatusWaitForApprove DataExportWorkflowStatus = "wait_for_approve" + DataExportWorkflowStatusWaitForExport DataExportWorkflowStatus = "wait_for_export" + DataExportWorkflowStatusWaitForExporting DataExportWorkflowStatus = "exporting" + DataExportWorkflowStatusRejected DataExportWorkflowStatus = "rejected" + DataExportWorkflowStatusCancel DataExportWorkflowStatus = "cancel" + DataExportWorkflowStatusFailed DataExportWorkflowStatus = "failed" + DataExportWorkflowStatusFinish DataExportWorkflowStatus = "finish" +) + +// swagger:parameters GetDataExportWorkflow +type GetDataExportWorkflowReq struct { + // Required: true + // in:path + DataExportWorkflowUid string `param:"data_export_workflow_uid" json:"data_export_workflow_uid" validate:"required"` + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:model GetDataExportWorkflowReply +type GetDataExportWorkflowReply struct { + Data *GetDataExportWorkflow `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:enum WorkflowStepStatus +type WorkflowStepStatus string + +const ( + WorkflowStepStatusWaitForExporting WorkflowStepStatus = "init" + WorkflowStepStatusRejected WorkflowStepStatus = "rejected" + WorkflowStepStatusFinish WorkflowStepStatus = "finish" +) + +type GetDataExportWorkflow struct { + Name string `json:"workflow_name"` + WorkflowID string `json:"workflow_uid"` + Desc string `json:"desc,omitempty"` + CreateUser UidWithName `json:"create_user"` + CreateTime *time.Time `json:"create_time"` + WorkflowRecord WorkflowRecord `json:"workflow_record"` + WorkflowRecordHistory []WorkflowRecord `json:"workflow_record_history"` +} + +type WorkflowRecord struct { + Tasks []*Task `json:"tasks"` + CurrentStepNumber uint `json:"current_step_number,omitempty"` + Status DataExportWorkflowStatus `json:"status"` + Steps []*WorkflowStep `json:"workflow_step_list,omitempty"` +} + +type Task struct { + Uid string `json:"task_uid"` +} + +type WorkflowStep struct { + Number uint64 `json:"number"` + Type string `json:"type"` + Desc string `json:"desc,omitempty"` + Users []UidWithName `json:"assignee_user_list,omitempty"` + OperationUser UidWithName `json:"operation_user,omitempty"` + OperationTime *time.Time `json:"operation_time,omitempty"` + State WorkflowStepStatus `json:"state,omitempty" ` + Reason string `json:"reason,omitempty"` +} + +// swagger:parameters ApproveDataExportWorkflow +type ApproveDataExportWorkflowReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // Required: true + // in:path + DataExportWorkflowUid string `param:"data_export_workflow_uid" json:"data_export_workflow_uid" validate:"required"` +} + +// swagger:parameters ExportDataExportWorkflow +type ExportDataExportWorkflowReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // Required: true + // in:path + DataExportWorkflowUid string `param:"data_export_workflow_uid" json:"data_export_workflow_uid" validate:"required"` +} + +type RejectDataExportWorkflowPayload struct { + // Required: true + Reason string `json:"reason" validate:"required"` +} + +// swagger:model +type RejectDataExportWorkflowReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // swagger:ignore + DataExportWorkflowUid string `param:"data_export_workflow_uid" json:"data_export_workflow_uid" validate:"required"` + Payload RejectDataExportWorkflowPayload `json:"payload" validate:"required"` +} + +type CancelDataExportWorkflowPayload struct { + // Required: true + DataExportWorkflowUids []string `json:"data_export_workflow_uids" validate:"required"` +} + +// swagger:model +type CancelDataExportWorkflowReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + Payload CancelDataExportWorkflowPayload `json:"payload" validate:"required"` +} diff --git a/api/dms/service/v1/db_service.go b/api/dms/service/v1/db_service.go index 60c3cfb47..73bb5d03c 100644 --- a/api/dms/service/v1/db_service.go +++ b/api/dms/service/v1/db_service.go @@ -1,32 +1,15 @@ package v1 import ( + "bytes" "fmt" - base "github.com/actiontech/dms/api/base/v1" - + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" "github.com/go-openapi/strfmt" -) -// swagger:enum DBType -type DBType string - -const ( - DBTypeMySQL DBType = "MySQL" - DBTypeOceanBaseMySQL DBType = "OceanBaseMySQL" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" ) -func ParseDBType(s string) (DBType, error) { - switch s { - case string(DBTypeMySQL): - return DBTypeMySQL, nil - case string(DBTypeOceanBaseMySQL): - return DBTypeOceanBaseMySQL, nil - default: - return "", fmt.Errorf("invalid db type: %s", s) - } -} - // A db service type DBService struct { // Service name @@ -34,7 +17,7 @@ type DBService struct { Name string `json:"name" validate:"required"` // Service DB type // Required: true - DBType DBType `json:"db_type" validate:"required"` + DBType string `json:"db_type" validate:"required"` // DB Service Host // Required: true Host string `json:"host" validate:"required,ip_addr|uri|hostname|hostname_rfc1123"` @@ -49,38 +32,32 @@ type DBService struct { Password string `json:"password" validate:"required"` // DB Service business name // Required: true + // Deprecated: the business field is replaced with the environmentTag of the v2 interface. Business string `json:"business" validate:"required"` // DB Service maintenance time // empty value means that maintenance time is unlimited // Required: true - MaintenanceTimes []*MaintenanceTime `json:"maintenance_times"` - // DB Service namespace id - // Required: true - NamespaceUID string `json:"namespace_uid" validate:"required"` + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` // DB Service Custom connection parameters // Required: false - AdditionalParams []*DBServiceAdditionalParam `json:"additional_params"` + AdditionalParams []*dmsCommonV1.AdditionalParam `json:"additional_params"` // Service description Desc string `json:"desc"` // SQLE config - SQLEConfig *SQLEConfig `json:"sqle_config"` -} - -type MaintenanceTime struct { - MaintenanceStartTime *Time `json:"maintenance_start_time"` - MaintenanceStopTime *Time `json:"maintenance_stop_time"` -} - -type Time struct { - Hour int `json:"hour"` - Minute int `json:"minute"` + SQLEConfig *dmsCommonV1.SQLEConfig `json:"sqle_config"` + // backup switch + // Required: false + EnableBackup bool `json:"enable_backup"` + // backup switch + // Required: false + BackupMaxRows *uint64 `json:"backup_max_rows,omitempty"` } -// swagger:parameters AddDBService +// swagger:model AddDBServiceReq type AddDBServiceReq struct { - // Add new db service - // in:body - DBService *DBService `json:"db_service" validate:"required"` + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DBService *DBService `json:"db_service" validate:"required"` } func (u *AddDBServiceReq) String() string { @@ -93,10 +70,10 @@ func (u *AddDBServiceReq) String() string { // swagger:model AddDBServiceReply type AddDBServiceReply struct { // Add db service reply - Payload struct { + Data struct { // db service UID Uid string `json:"uid"` - } `json:"payload"` + } `json:"data"` // Generic reply base.GenericResp @@ -106,52 +83,61 @@ func (u *AddDBServiceReply) String() string { if u == nil { return "AddDBServiceReply{nil}" } - return fmt.Sprintf("AddDBServiceReply{Uid:%s}", u.Payload.Uid) + return fmt.Sprintf("AddDBServiceReply{Uid:%s}", u.Data.Uid) } -// swagger:parameters CheckDBServiceIsConnectable +// swagger:model type CheckDBServiceIsConnectableReq struct { - // check db_service is connectable - // in:body - DBService struct { - // DB Service type - // Required: true - // example: MySQL - DBType string `json:"db_type" validate:"required"` - // DB Service admin user - // Required: true - // example: root - User string `json:"user" validate:"required"` - // DB Service admin password - // Required: true - // example: 123456 - Password string `json:"password" validate:"required"` - // DB Service host - // Required: true - // example: 127.0.0.1 - Host string `json:"host" validate:"required,ip_addr|uri|hostname|hostname_rfc1123"` - // DB Service port - // Required: true - // example: 3306 - Port string `json:"port" validate:"required"` - // DB Service Custom connection parameters - // Required: false - AdditionalParams []*DBServiceAdditionalParam `json:"additional_params"` - } `json:"db_service"` + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DBService dmsCommonV1.CheckDbConnectable `json:"db_service"` +} + +type CheckDBServiceIsConnectableReplyItem struct { + IsConnectable bool `json:"is_connectable"` + Component string `json:"component"` + ConnectErrorMessage string `json:"connect_error_message"` } // swagger:model CheckDBServiceIsConnectableReply type CheckDBServiceIsConnectableReply struct { - Payload struct { - IsConnectable bool `json:"is_connectable"` - ConnectErrorMessage string `json:"connect_error_message,omitempty"` - } `json:"payload"` + Data []CheckDBServiceIsConnectableReplyItem `json:"data"` base.GenericResp } +// swagger:model +type CheckDBServicesIsConnectableReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DBServices []DbServiceConnections `json:"db_services"` +} + +// swagger:model CheckDBServicesIsConnectableReply +type CheckDBServicesIsConnectableReply struct { + Data []DBServiceIsConnectableReply `json:"data"` + base.GenericResp +} + +type DBServiceIsConnectableReply struct { + DBServiceUid string `param:"db_service_uid" json:"db_service_uid"` + ConnectionStatus dmsCommonV1.LastConnectionTestStatus `json:"connection_status"` + TestConnectionTime strfmt.DateTime `json:"test_connection_time"` + ConnectErrorMessage string `json:"connect_error_message"` +} + +// swagger:model +type CheckDBServiceIsConnectableByIdReq struct { + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DBServiceUid string `param:"db_service_uid" json:"db_service_uid" validate:"required"` +} + // swagger:parameters DelDBService type DelDBServiceReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` // db service uid // in:path DBServiceUid string `param:"db_service_uid" json:"db_service_uid" validate:"required"` @@ -164,8 +150,197 @@ func (u *DelDBServiceReq) String() string { return fmt.Sprintf("DelDBServiceReq{Uid:%s}", u.DBServiceUid) } -// swagger:parameters ListDBServices -type ListDBServiceReq struct { +// swagger:model +type UpdateDBServiceReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // swagger:ignore + DBServiceUid string `param:"db_service_uid" json:"db_service_uid" validate:"required"` + DBService *UpdateDBService `json:"db_service" validate:"required"` +} + +func (u *UpdateDBServiceReq) String() string { + if u == nil { + return "UpdateDBServiceReq{nil}" + } + if u.DBService == nil { + return "UpdateDBServiceReq{DBService:nil}" + } + return fmt.Sprintf("UpdateDBServiceReq{Uid:%s}", u.DBServiceUid) +} + +// update db service +type UpdateDBService struct { + // Service DB type + // Required: true + DBType string `json:"db_type" validate:"required"` + // DB Service Host + // Required: true + Host string `json:"host" validate:"required,ip_addr|uri|hostname|hostname_rfc1123"` + // DB Service port + // Required: true + Port string `json:"port" validate:"required"` + // DB Service admin user + // Required: true + User string `json:"user" validate:"required"` + // DB Service admin password + Password *string `json:"password"` + // DB Service business name + // Required: true + // Deprecated: the business field is replaced with the environmentTag of the v2 interface. + Business string `json:"business" validate:"required"` + // DB Service maintenance time + // Required: true + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` + // DB Service Custom connection parameters + // Required: false + AdditionalParams []*dmsCommonV1.AdditionalParam `json:"additional_params"` + // Service description + Desc *string `json:"desc"` + // SQLE config + SQLEConfig *dmsCommonV1.SQLEConfig `json:"sqle_config"` + // backup switch + // Required: false + EnableBackup bool `json:"enable_backup"` + // backup switch + // Required: false + BackupMaxRows *uint64 `json:"backup_max_rows,omitempty"` +} + +// swagger:model UpdateDBServiceReply +type UpdateDBServiceReply struct { + // update db service reply + Data struct { + // db service UID + Uid string `json:"uid"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +func (u *UpdateDBServiceReply) String() string { + if u == nil { + return "UpdateDBServiceReply{nil}" + } + return fmt.Sprintf("UpdateDBServiceReply{Uid:%s}", u.Data.Uid) +} + +type DatabaseDriverAdditionalParam struct { + Name string `json:"name"` + Value string `json:"value"` + Description string `json:"description" example:"参数项中文名"` + Type string `json:"type" example:"int"` +} + +type DatabaseDriverOption struct { + DBType string `json:"db_type"` + LogoPath string `json:"logo_path"` + Params []*DatabaseDriverAdditionalParam `json:"params"` +} + +// swagger:model ListDBServiceDriverOptionReply +type ListDBServiceDriverOptionReply struct { + // List db service reply + Data []*DatabaseDriverOption `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:parameters ListDBServiceTips +type ListDBServiceTipsReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // Required: false + // in:query + FilterDBType string `json:"filter_db_type" query:"filter_db_type"` + // Required: false + // enum: ["save_audit_plan","create_workflow","create_export_task"] + // in:query + FunctionalModule string `json:"functional_module" query:"functional_module" validate:"omitempty,oneof=save_audit_plan create_workflow create_export_task"` +} + +type ListDBServiceTipItem struct { + Id string `json:"id"` + Name string `json:"name"` + Type string `json:"db_type"` + Host string `json:"host"` + Port string `json:"port"` +} + +// swagger:model ListDBServiceTipsReply +type ListDBServiceTipsReply struct { + // List db service reply + Data []*ListDBServiceTipItem `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:parameters ImportDBServicesOfOneProjectCheck +type ImportDBServicesOfOneProjectCheckReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // DBServices file. + // + // in: formData + // + // swagger:file + DBServicesFile *bytes.Buffer `json:"db_services_file"` +} + +type ImportDBService struct { + // db service name + Name string `json:"name"` + // db service DB type + DBType string `json:"db_type"` + // db service host + Host string `json:"host"` + // db service port + Port string `json:"port"` + // db service admin user + User string `json:"user"` + // db service admin encrypted password + Password string `json:"password"` + // the db service business name + // Deprecated: the business field is replaced with the environmentTag of the v2 interface. + Business string `json:"business"` + // DB Service maintenance time + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` + // DB desc + Desc string `json:"desc"` + // DB source + Source string `json:"source"` + // DB project uid + ProjectUID string `json:"project_uid"` + // sqle config + SQLEConfig *dmsCommonV1.SQLEConfig `json:"sqle_config"` + // DB Service Custom connection parameters + AdditionalParams []*dmsCommonV1.AdditionalParam `json:"additional_params"` +} + +// swagger:model +type ImportDBServicesOfOneProjectReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DBServices []ImportDBService `json:"db_services" validate:"required"` +} + +// swagger:model ImportDBServicesCheckReply +type ImportDBServicesCheckReply struct { + // db services + Data []*ImportDBService `json:"data"` + // Generic reply + base.GenericResp +} + +// swagger:parameters ListGlobalDBServices +type ListGlobalDBServicesReq struct { // the maximum count of db service to be returned // in:query // Required: true @@ -175,184 +350,127 @@ type ListDBServiceReq struct { PageIndex uint32 `query:"page_index" json:"page_index"` // Multiple of ["name"], default is ["name"] // in:query - OrderBy DBServiceOrderByField `query:"order_by" json:"order_by"` + OrderBy dmsCommonV1.DBServiceOrderByField `query:"order_by" json:"order_by"` + // the db service connection + // enum: ["connect_success","connect_failed"] + // in:query + FilterLastConnectionTestStatus *string `query:"filter_last_connection_test_status" json:"filter_last_connection_test_status" validate:"omitempty,oneof=connect_success connect_failed"` + // TODO This parameter is deprecated and will be removed soon. // the db service business name // in:query FilterByBusiness string `query:"filter_by_business" json:"filter_by_business"` + // filter db services by environment tag + // in:query + FilterByEnvironmentTag string `query:"filter_by_environment_tag" json:"filter_by_environment_tag"` // the db service host // in:query FilterByHost string `query:"filter_by_host" json:"filter_by_host"` // the db service uid + // in:query FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` + // the db service name + // in:query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` // the db service port // in:query FilterByPort string `query:"filter_by_port" json:"filter_by_port"` // the db service db type // in:query - // Multiple of ["MySQL","OceanBaseMySQL"], default is [""] FilterByDBType string `query:"filter_by_db_type" json:"filter_by_db_type"` - // filter by db service namespace uid - // only the sys user can use an empty namespace value, which means lookup from all namespaces + // the db service project id + // in:query + FilterByProjectUid string `query:"filter_by_project_uid" json:"filter_by_project_uid"` + // is masking // in:query - FilterByNamespaceUid string `query:"filter_by_namespace_uid" json:"filter_by_namespace_uid"` + FilterByIsEnableMasking *bool `query:"filter_by_is_enable_masking" json:"filter_by_is_enable_masking"` + // the db service fuzzy keyword + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` } -// swagger:enum DBServiceOrderByField -type DBServiceOrderByField string +// swagger:model ListGlobalDBServicesReply +type ListGlobalDBServicesReply struct { + // List global db service reply + Data []*ListGlobalDBService `json:"data"` + Total int64 `json:"total_nums"` -const ( - DBServiceOrderByName DBServiceOrderByField = "name" -) + // Generic reply + base.GenericResp +} -// A dms db Service -type ListDBService struct { +type ListGlobalDBService struct { // db service uid DBServiceUid string `json:"uid"` // db service name Name string `json:"name"` - // Multiple of ["MySQL"], default is ["MySQL"] // db service DB type - DBType DBType `json:"db_type"` + DBType string `json:"db_type"` // db service host Host string `json:"host"` // db service port Port string `json:"port"` - // db service admin user - User string `json:"user"` - // db service admin encrypted password - Password string `json:"password"` + // TODO This parameter is deprecated and will be removed soon. // the db service business name - Business string `json:"business"` + // Deprecated: the business field is replaced with the environmentTag of the v2 interface. + Business string `json:"business"` // DB Service maintenance time - MaintenanceTimes []*MaintenanceTime `json:"maintenance_times"` + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` // DB desc Desc string `json:"desc"` // DB source Source string `json:"source"` - // DB namespace uid - NamespaceUID string `json:"namespace_uid"` - // sqle config - SQLEConfig *SQLEConfig `json:"sqle_config"` - // auth config - AuthConfig *AuthSyncConfig `json:"auth_config"` -} - -type DBServiceAdditionalParam struct { - Name string `json:"name"` - Value string `json:"value"` -} -type SQLEConfig struct { - // DB Service rule template name - RuleTemplateName string `json:"rule_template_name"` - // DB Service rule template id - RuleTemplateID string `json:"rule_template_id"` - // DB Service SQL query config - SQLQueryConfig *SQLQueryConfig `json:"sql_query_config"` + // DB project uid + ProjectUID string `json:"project_uid"` + // db service project_name + ProjectName string `json:"project_name"` + // is enable audit + IsEnableAudit bool `json:"is_enable_audit"` + // is enable masking + IsEnableMasking bool `json:"is_enable_masking"` + // db service unfinished workflow num + UnfinishedWorkflowNum int64 `json:"unfinished_workflow_num"` + // backup switch + EnableBackup bool `json:"enable_backup"` + // backup switch + // Required: false + BackupMaxRows uint64 `json:"backup_max_rows"` + // DB connection test time + LastConnectionTestTime strfmt.DateTime `json:"last_connection_test_time"` + // DB connect test status + LastConnectionTestStatus dmsCommonV1.LastConnectionTestStatus `json:"last_connection_test_status"` + // DB connect test error message + LastConnectionTestErrorMessage string `json:"last_connection_test_error_message,omitempty"` } -// swagger:enum SQLAllowQueryAuditLevel -type SQLAllowQueryAuditLevel string +// swagger:enum FunctionSupportType +type FunctionSupportType string const ( - AuditLevelNormal SQLAllowQueryAuditLevel = "normal" - AuditLevelNotice SQLAllowQueryAuditLevel = "notice" - AuditLevelWarn SQLAllowQueryAuditLevel = "warn" - AuditLevelError SQLAllowQueryAuditLevel = "error" + // FunctionSupportTypeDataMasking 数据脱敏功能 + FunctionSupportTypeDataMasking FunctionSupportType = "data_masking" ) -type SQLQueryConfig struct { - MaxPreQueryRows int `json:"max_pre_query_rows" example:"100"` - QueryTimeoutSecond int `json:"query_timeout_second" example:"10"` - AuditEnabled bool `json:"audit_enabled" example:"false"` - AllowQueryWhenLessThanAuditLevel SQLAllowQueryAuditLevel `json:"allow_query_when_less_than_audit_level" enums:"normal,notice,warn,error" valid:"omitempty,oneof=normal notice warn error " example:"error"` -} - -type AuthSyncConfig struct { - // last sync data result - LastSyncDataResult string `json:"last_sync_data_result"` - // last sync data time - LastSyncDataTime strfmt.DateTime `json:"last_sync_data_time"` -} - -// swagger:model ListDBServiceReply -type ListDBServiceReply struct { - // List db service reply - Payload struct { - DBServices []*ListDBService `json:"db_services"` - Total int64 `json:"total"` - } `json:"payload"` - - // Generic reply - base.GenericResp +// swagger:parameters ListGlobalDBServicesTips +type ListGlobalDBServicesTipsReq struct { + // function support filter, when specified, returns the db types supported by the function + // in: query + // enum: data_masking + // Example: data_masking + FunctionSupport FunctionSupportType `query:"function_support" json:"function_support" validate:"omitempty,oneof=data_masking"` } -// swagger:parameters UpdateDBService -type UpdateDBServiceReq struct { - // db_service_uid - // Required: true - // in:path - DBServiceUid string `param:"db_service_uid" json:"db_service_uid" validate:"required"` - // Update a DB service - // in:body - DBService *UpdateDBService `json:"db_service" validate:"required"` -} - -func (u *UpdateDBServiceReq) String() string { - if u == nil { - return "UpdateDBServiceReq{nil}" - } - if u.DBService == nil { - return "UpdateDBServiceReq{DBService:nil}" - } - return fmt.Sprintf("UpdateDBServiceReq{Uid:%s}", u.DBServiceUid) -} - -// update db service -type UpdateDBService struct { - // Service DB type - // Required: true - DBType DBType `json:"db_type" validate:"required"` - // DB Service Host - // Required: true - Host string `json:"host" validate:"required,ip_addr|uri|hostname|hostname_rfc1123"` - // DB Service port - // Required: true - Port string `json:"port" validate:"required"` - // DB Service admin user - // Required: true - User string `json:"user" validate:"required"` - // DB Service admin password - Password *string `json:"password"` - // DB Service business name - // Required: true - Business string `json:"business" validate:"required"` - // DB Service maintenance time - // Required: true - MaintenanceTimes []*MaintenanceTime `json:"maintenance_times"` - // DB Service Custom connection parameters - // Required: false - AdditionalParams []*DBServiceAdditionalParam `json:"additional_params"` - // Service description - Desc *string `json:"desc"` - // SQLE config - SQLEConfig *SQLEConfig `json:"sqle_config"` -} - -// swagger:model UpdateDBServiceReply -type UpdateDBServiceReply struct { - // update db service reply - Payload struct { - // db service UID - Uid string `json:"uid"` - } `json:"payload"` +// swagger:model ListGlobalDBServicesTipsReply +type ListGlobalDBServicesTipsReply struct { + // List global db service tips reply + Data *ListGlobalDBServiceTips `json:"data"` // Generic reply base.GenericResp } -func (u *UpdateDBServiceReply) String() string { - if u == nil { - return "UpdateDBServiceReply{nil}" - } - return fmt.Sprintf("UpdateDBServiceReply{Uid:%s}", u.Payload.Uid) +type ListGlobalDBServiceTips struct { + // DBType 数据库类型列表 + // 当请求参数 function_support 为空时,返回所有数据库类型 + // 当请求参数 function_support 有效时,仅返回支持该功能的数据库类型 + DBType []string `json:"db_type"` } diff --git a/api/dms/service/v1/db_service_sync_task.go b/api/dms/service/v1/db_service_sync_task.go new file mode 100644 index 000000000..6df48bf73 --- /dev/null +++ b/api/dms/service/v1/db_service_sync_task.go @@ -0,0 +1,123 @@ +package v1 + +import ( + "time" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + pkgParams "github.com/actiontech/dms/pkg/params" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +// swagger:model ListDBServiceSyncTasksReply +type ListDBServiceSyncTasksReply struct { + Data []*ListDBServiceSyncTask `json:"data"` + + // Generic reply + base.GenericResp +} + +type ListDBServiceSyncTask struct { + DBServiceSyncTask + UID string `json:"uid"` + + // last sync error message + LastSyncErr string `json:"last_sync_err"` + LastSyncSuccessTime *time.Time `json:"last_sync_success_time"` +} + +type GetDBServiceSyncTaskReq struct { + // swagger:ignore + DBServiceSyncTaskUid string `param:"db_service_sync_task_uid" json:"db_service_sync_task_uid" validate:"required"` +} + +// swagger:model GetDBServiceSyncTaskReply +type GetDBServiceSyncTaskReply struct { + Data *GetDBServiceSyncTask `json:"data"` + + // Generic reply + base.GenericResp +} + +type GetDBServiceSyncTask struct { + DBServiceSyncTask + UID string `json:"uid"` +} + + +type DBServiceSyncTask struct { + // name + // Required: true + // example: dmp + Name string `json:"name" validate:"required"` + // source + // Required: true + // example: actiontech-dmp + Source string `json:"source" validate:"required"` + // addr + // Required: true + // example: http://10.186.62.56:10000 + URL string `json:"url" validate:"required"` + // database type + // Required: true + // example: MySQL + DbType string `json:"db_type" validate:"required"` + // cron expression + // Required: true + // example: 0 0 * * * + CronExpress string `json:"cron_express" validate:"required"` + // additional params + // Required: false + AdditionalParam pkgParams.Params `json:"additional_params"` + // SQLE config + SQLEConfig *dmsCommonV1.SQLEConfig `json:"sqle_config"` +} + +// swagger:model AddDBServiceSyncTaskReq +type AddDBServiceSyncTaskReq struct { + DBServiceSyncTask DBServiceSyncTask `json:"db_service_sync_task"` +} + +// swagger:model AddDBServiceSyncTaskReply +type AddDBServiceSyncTaskReply struct { + // add database source service reply + Data struct { + // db service UID + Uid string `json:"uid"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:model UpdateDBServiceSyncTaskReq +type UpdateDBServiceSyncTaskReq struct { + // swagger:ignore + DBServiceSyncTaskUid string `param:"db_service_sync_task_uid" json:"db_service_sync_task_uid" validate:"required"` + DBServiceSyncTask DBServiceSyncTask `json:"db_service_sync_task" validate:"required"` +} + +type DeleteDBServiceSyncTaskReq struct { + // swagger:ignore + DBServiceSyncTaskUid string `param:"db_service_sync_task_uid" json:"db_service_sync_task_uid" validate:"required"` +} + +// swagger:model ListDBServiceSyncTaskTipsReply +type ListDBServiceSyncTaskTipsReply struct { + Data []DBServiceSyncTaskTip `json:"data"` + + // Generic reply + base.GenericResp +} + +type DBServiceSyncTaskTip struct { + Type pkgConst.DBServiceSourceName `json:"service_source_name"` + Desc string `json:"description"` + DBType []pkgConst.DBType `json:"db_type"` // 使用constant.DBType + Params pkgParams.Params `json:"params,omitempty"` +} + +type SyncDBServicesReq struct { + // swagger:ignore + DBServiceSyncTaskUid string `param:"db_service_sync_task_uid" json:"db_service_sync_task_uid" validate:"required"` +} diff --git a/api/dms/service/v1/environment_tag.go b/api/dms/service/v1/environment_tag.go new file mode 100644 index 000000000..3e64e8671 --- /dev/null +++ b/api/dms/service/v1/environment_tag.go @@ -0,0 +1,52 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +// swagger:model +type CreateEnvironmentTagReq struct { + // swagger:ignore + ProjectUID string `param:"project_uid" json:"project_uid" validate:"required"` + Name string `json:"environment_name" validate:"required,min=1,max=50"` +} + +// swagger:model +type UpdateEnvironmentTagReq struct { + // swagger:ignore + EnvironmentTagUID string `param:"environment_tag_uid" json:"environment_tag_uid" validate:"required"` + // swagger:ignore + ProjectUID string `param:"project_uid" json:"project_uid" validate:"required"` + + Name string `json:"environment_name" validate:"required,min=1,max=50"` +} + +// swagger:parameters ListEnvironmentTags +type ListEnvironmentTagReq struct { + // in:path + // Required: true + ProjectUID string `param:"project_uid" json:"project_uid" validate:"required"` + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` +} + +// swagger:model ListEnvironmentTagsReply +type ListEnvironmentTagsReply struct { + Data []*dmsCommonV1.EnvironmentTag `json:"data"` + Total int64 `json:"total_nums"` + base.GenericResp +} + +// swagger:parameters DeleteEnvironmentTag +type DeleteEnvironmentTagReq struct { + // in:path + // Required: true + EnvironmentTagUID string `param:"environment_tag_uid" json:"environment_tag_uid" validate:"required"` + // in:path + // Required: true + ProjectUID string `param:"project_uid" json:"project_uid" validate:"required"` +} diff --git a/api/dms/service/v1/gateway.go b/api/dms/service/v1/gateway.go new file mode 100644 index 000000000..67912f523 --- /dev/null +++ b/api/dms/service/v1/gateway.go @@ -0,0 +1,90 @@ +package v1 + +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +// swagger:model +type AddGatewayReq struct { + AddGateway *Gateway `json:"add_gateway" validate:"required"` +} + +// swagger:model AddGatewayReply +type AddGatewayReply struct { + base.GenericResp +} + +// swagger:parameters DeleteGateway +type DeleteGatewayReq struct { + // in:path + // Required: true + DeleteGatewayID string `param:"gateway_id" json:"gateway_id" validate:"required"` +} + +// swagger:model DeleteGatewayReply +type DeleteGatewayReply struct { + base.GenericResp +} + +// swagger:model +type UpdateGatewayReq struct { + // swagger:ignore + UpdateGatewayID string `param:"gateway_id" json:"gateway_id" validate:"required"` + UpdateGateway UpdateGateway `json:"update_gateway" validate:"required"` +} + +type UpdateGateway struct { + GatewayName string `json:"gateway_name" validate:"required"` + GatewayDesc string `json:"gateway_desc"` + GatewayAddress string `json:"gateway_address" binding:"required"` +} + +// swagger:model UpdateGatewayReply +type UpdateGatewayReply struct { + base.GenericResp +} + +// swagger:parameters GetGateway +type GetGatewayReq struct { + // in:path + // Required: true + GetGatewayID string `param:"gateway_id" json:"gateway_id" validate:"required"` +} + +type Gateway struct { + GatewayID string `json:"gateway_id" validate:"required"` + GatewayName string `json:"gateway_name" validate:"required"` + GatewayDesc string `json:"gateway_desc" ` + GatewayAddress string `json:"gateway_address" binding:"required"` +} + +// swagger:model GetGatewayReply +type GetGatewayReply struct { + Gateways *Gateway `json:"data"` + base.GenericResp +} + +// swagger:parameters ListGateways +type ListGatewaysReq struct { + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` +} + +// swagger:model ListGatewaysReply +type ListGatewaysReply struct { + Total int64 `json:"total"` + Gateways []*Gateway `json:"data"` + base.GenericResp +} + +// swagger:model GetGatewayTipsReply +type GetGatewayTipsReply struct { + base.GenericResp + GatewayTips []*UidWithName `json:"data"` +} + +// swagger:model +type SyncGatewayReq struct { + Gateways []*Gateway `json:"gateways" validate:"required"` +} diff --git a/api/dms/service/v1/license.go b/api/dms/service/v1/license.go new file mode 100644 index 000000000..a7323f943 --- /dev/null +++ b/api/dms/service/v1/license.go @@ -0,0 +1,76 @@ +package v1 + +import ( + "bytes" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:model GetLicenseReply +type GetLicenseReply struct { + // Generic reply + base.GenericResp + Content string `json:"content"` + License []LicenseItem `json:"license"` +} + +type LicenseItem struct { + Description string `json:"description"` + Name string `json:"name"` + Limit string `json:"limit"` +} + +// swagger:model CheckLicenseReply +type CheckLicenseReply struct { + // Generic CheckLicenseReply + base.GenericResp + Content string `json:"content"` + License []LicenseItem `json:"license"` +} + +// swagger:parameters SetLicense +type SetLicenseReq struct { + // license file. + // + // in: formData + // + // swagger:file + LicenseFile *bytes.Buffer `json:"license_file"` +} + +// swagger:parameters CheckLicense +type CheckLicenseReq struct { + // license file. + // + // in: formData + // + // swagger:file + LicenseFile *bytes.Buffer `json:"license_file"` +} + +// swagger:response GetLicenseInfoReply +type GetLicenseInfoReply struct { + // swagger:file + // in: body + File []byte +} + +type LicenseUsageItem struct { + ResourceType string `json:"resource_type"` + ResourceTypeDesc string `json:"resource_type_desc"` + Used uint `json:"used"` + Limit uint `json:"limit"` + IsLimited bool `json:"is_limited"` +} + +type LicenseUsage struct { + UsersUsage LicenseUsageItem `json:"users_usage"` + DbServicesUsage []LicenseUsageItem `json:"db_services_usage"` +} + +// swagger:model GetLicenseUsageReply +type GetLicenseUsageReply struct { + // Generic reply + base.GenericResp + Data *LicenseUsage `json:"data"` +} diff --git a/api/dms/service/v1/masking.go b/api/dms/service/v1/masking.go new file mode 100644 index 000000000..2b93a4dda --- /dev/null +++ b/api/dms/service/v1/masking.go @@ -0,0 +1,846 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:parameters ListMaskingRules +type ListMaskingRulesReq struct { +} + +// swagger:model ListMaskingRulesData +type ListMaskingRulesData struct { + // masking type + // Example: "MASK_DIGIT" + MaskingType string `json:"masking_type"` + // description + // Example: "mask digits" + Description string `json:"description"` + // effect description for users + // Example: "保留开头2位和结尾2位,中间字符替换为*" + Effect string `json:"effect"` + // effect example before masking + // Example: "13812345678" + EffectExampleBefore string `json:"effect_example_before"` + // effect example after masking + // Example: "138******78" + EffectExampleAfter string `json:"effect_example_after"` + // masking rule id + // Example: 1 + Id int `json:"id"` +} + +// swagger:model ListMaskingRulesReply +type ListMaskingRulesReply struct { + // list masking rule reply + Data []ListMaskingRulesData `json:"data"` + + base.GenericResp +} + +// swagger:parameters ListMaskingTemplates +type ListMaskingTemplatesReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // the maximum count of masking templates to be returned, default is 20 + // in: query + PageSize uint32 `query:"page_size" json:"page_size"` + // the offset of masking templates to be returned, default is 0 + // in: query + PageIndex uint32 `query:"page_index" json:"page_index"` +} + +// swagger:model ListMaskingTemplatesData +type ListMaskingTemplatesData struct { + // masking template id + // Example: 1 + Id int `json:"id"` + // masking template name + // Example: "Standard Template" + Name string `json:"name"` + // count of rules in the template + // Example: 5 + RuleCount int `json:"rule_count"` + // preview of rule name in the template, up to 3 items + RuleNames []string `json:"rule_names"` +} + +// swagger:model ListMaskingTemplatesReply +type ListMaskingTemplatesReply struct { + // list masking templates reply + Data []ListMaskingTemplatesData `json:"data"` + // total count of masking templates + // Example: 100 + Total int64 `json:"total_nums"` + + base.GenericResp +} + +// swagger:model AddMaskingTemplateReq +type AddMaskingTemplateReq struct { + // project uid + // in: path + // swagger:ignore + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // masking template + // Required: true + MaskingTemplate *AddMaskingTemplate `json:"masking_template" validate:"required"` +} + +// swagger:model AddMaskingTemplate +type AddMaskingTemplate struct { + // masking template name + // Required: true + // Example: "New Template" + Name string `json:"name" validate:"required"` + // masking rule id list + // Required: true + // MinLength: 1 + // Example: [1, 2, 3] + RuleIDs []int `json:"rule_ids" validate:"required,min=1"` +} + +// swagger:model AddMaskingTemplateReply +type AddMaskingTemplateReply struct { + base.GenericResp +} + +// swagger:model UpdateMaskingTemplateReq +type UpdateMaskingTemplateReq struct { + // project uid + // in: path + // swagger:ignore + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // masking template id + // in: path + // swagger:ignore + // Required: true + // Example: 1 + TemplateID int `param:"template_id" json:"template_id" validate:"required"` + // masking template + // Required: true + MaskingTemplate *UpdateMaskingTemplate `json:"masking_template" validate:"required"` +} + +// swagger:model UpdateMaskingTemplate +type UpdateMaskingTemplate struct { + // masking rule id list + // Required: true + // MinLength: 1 + // Example: [1, 2] + RuleIDs []int `json:"rule_ids" validate:"required,min=1"` +} + +// swagger:model UpdateMaskingTemplateReply +type UpdateMaskingTemplateReply struct { + base.GenericResp +} + +// swagger:parameters DeleteMaskingTemplate +type DeleteMaskingTemplateReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // masking template id + // in: path + // Required: true + // Example: 1 + TemplateID int `param:"template_id" json:"template_id" validate:"required"` +} + +// swagger:model DeleteMaskingTemplateReply +type DeleteMaskingTemplateReply struct { + base.GenericResp +} + +// swagger:parameters ListSensitiveDataDiscoveryTasks +type ListSensitiveDataDiscoveryTasksReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // the maximum count of tasks to be returned, default is 20 + // in: query + // Example: 20 + PageSize uint32 `query:"page_size" json:"page_size"` + // the offset of tasks to be returned, default is 0 + // in: query + // Example: 0 + PageIndex uint32 `query:"page_index" json:"page_index"` +} + +// swagger:enum SensitiveDataDiscoveryTaskType +type SensitiveDataDiscoveryTaskType string + +const ( + SensitiveDataDiscoveryTaskTypePeriodic SensitiveDataDiscoveryTaskType = "PERIODIC" // 周期性任务 + SensitiveDataDiscoveryTaskTypeOneTime SensitiveDataDiscoveryTaskType = "ONE_TIME" // 一次性任务 +) + +// swagger:enum SensitiveDataDiscoveryTaskStatus +type SensitiveDataDiscoveryTaskStatus string + +const ( + SensitiveDataDiscoveryTaskStatusPendingChangeConfirm SensitiveDataDiscoveryTaskStatus = "PENDING_CONFIRM" + SensitiveDataDiscoveryTaskStatusNormal SensitiveDataDiscoveryTaskStatus = "NORMAL" + SensitiveDataDiscoveryTaskStatusCompleted SensitiveDataDiscoveryTaskStatus = "COMPLETED" + SensitiveDataDiscoveryTaskStatusRunning SensitiveDataDiscoveryTaskStatus = "RUNNING" + SensitiveDataDiscoveryTaskStatusFailed SensitiveDataDiscoveryTaskStatus = "FAILED" + SensitiveDataDiscoveryTaskStatusStopped SensitiveDataDiscoveryTaskStatus = "STOPPED" +) + +// swagger:model ListSensitiveDataDiscoveryTasksData +type ListSensitiveDataDiscoveryTasksData struct { + // sensitive data discovery task id + // Example: 1 + ID int `json:"id"` + // database instance id + // Example: "db_service_uid_1" + DBServiceUID string `json:"db_service_uid"` + // database instance name + // Example: "mysql-01" + DBServiceName string `json:"db_service_name"` + // database instance host + // Example: "10.10.10.10" + DBServiceHost string `json:"db_service_host"` + // database instance port + // Example: "3306" + DBServicePort string `json:"db_service_port"` + // task type + // Example: "PERIODIC" + TaskType SensitiveDataDiscoveryTaskType `json:"task_type"` + // sensitive data identification method + // Example: "BY_FIELD_NAME" + IdentificationMethod SensitiveDataIdentificationMethod `json:"identification_method"` + // execution plan + // Example: "ONE_TIME" + ExecutionPlan SensitiveDataDiscoveryTaskType `json:"execution_plan"` + // whether periodic scanning is enabled + // Example: true + IsPeriodicScanEnabled bool `json:"is_periodic_scan_enabled"` + // cron expression of execution frequency, periodic task returns cron, one-time task returns empty + // Example: "0 2 * * *" + ExecutionFrequency string `json:"execution_frequency"` + // related masking template id + // Example: 1 + MaskingTemplateID int `json:"masking_template_id"` + // related masking template name + // Example: "Standard Template" + MaskingTemplateName string `json:"masking_template_name"` + // next run time, periodic task returns RFC3339 time, one-time task returns null + // Format: date-time (RFC3339) + // Example: "2024-01-15T10:30:00Z" + NextExecutionAt *string `json:"next_execution_at"` + // task status + // Example: "NORMAL" + Status SensitiveDataDiscoveryTaskStatus `json:"status"` +} + +// swagger:model ListSensitiveDataDiscoveryTasksReply +type ListSensitiveDataDiscoveryTasksReply struct { + // sensitive data discovery tasks list reply + Data []ListSensitiveDataDiscoveryTasksData `json:"data"` + // total count of sensitive data discovery tasks + // Example: 100 + Total int64 `json:"total_nums"` + + base.GenericResp +} + +// swagger:enum SensitiveDataIdentificationMethod +type SensitiveDataIdentificationMethod string + +const ( + SensitiveDataIdentificationMethodByFieldName SensitiveDataIdentificationMethod = "BY_FIELD_NAME" + SensitiveDataIdentificationMethodBySampleData SensitiveDataIdentificationMethod = "BY_SAMPLE_DATA" +) + +// swagger:model AddSensitiveDataDiscoveryTaskReq +type AddSensitiveDataDiscoveryTaskReq struct { + // project uid + // in: path + // swagger:ignore + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // sensitive data discovery task + // Required: true + Task *AddSensitiveDataDiscoveryTask `json:"task" validate:"required"` +} + +// swagger:enum ConfidenceLevel +type ConfidenceLevel string + +const ( + ConfidenceHigh ConfidenceLevel = "HIGH" + ConfidenceMedium ConfidenceLevel = "MEDIUM" + ConfidenceLow ConfidenceLevel = "LOW" +) + +// swagger:model AddSensitiveDataDiscoveryTask +type AddSensitiveDataDiscoveryTask struct { + // database instance id + // Required: true + // Example: "1" + DBServiceUID string `json:"db_service_uid" validate:"required"` + // masking template id + // Required: true + // Example: 1 + MaskingTemplateID int `json:"masking_template_id"` + // sensitive data identification method + // Required: true + // Example: "BY_FIELD_NAME" + IdentificationMethod SensitiveDataIdentificationMethod `json:"identification_method" validate:"required,oneof=BY_FIELD_NAME BY_SAMPLE_DATA"` + // execution plan + // Required: true + // Example: "ONE_TIME" + ExecutionPlan SensitiveDataDiscoveryTaskType `json:"execution_plan" validate:"required,oneof=PERIODIC ONE_TIME"` + // whether periodic scanning is enabled, default is true + // Example: true + IsPeriodicScanEnabled *bool `json:"is_periodic_scan_enabled"` + // cron expression, required when execution_plan is PERIODIC + // Example: "0 0 * * *" + CronExpression string `json:"cron_expression"` +} + +// swagger:model SensitiveFieldScanResult +type SensitiveFieldScanResult struct { + // scan information for the field + // Example: "matched by field name 'email'" + ScanInfo string `json:"scan_info"` + // confidence level + // Example: "High" + Confidence ConfidenceLevel `json:"confidence"` + // recommended masking rule id + // Example: 1 + RecommendedMaskingRuleID int `json:"recommended_masking_rule_id"` + // recommended masking rule name + // Example: "Email Masking" + RecommendedMaskingRuleName string `json:"recommended_masking_rule_name"` +} + +// swagger:model SuspectedSensitiveFieldsTree +type SuspectedSensitiveFieldsTree struct { + // database_name -> database node + Databases map[string]SuspectedSensitiveDatabaseNode `json:"databases"` +} + +// swagger:model SuspectedSensitiveDatabaseNode +type SuspectedSensitiveDatabaseNode struct { + // table_name -> table node + Tables map[string]SuspectedSensitiveTableNode `json:"tables"` +} + +// swagger:model SuspectedSensitiveTableNode +type SuspectedSensitiveTableNode struct { + // field_name -> scan result + Fields map[string]SensitiveFieldScanResult `json:"fields"` +} + +// swagger:model AddSensitiveDataDiscoveryTaskData +type AddSensitiveDataDiscoveryTaskData struct { + // suspected sensitive fields tree + SuspectedSensitiveFieldsTree SuspectedSensitiveFieldsTree `json:"suspected_sensitive_fields_tree"` +} + +// swagger:model AddSensitiveDataDiscoveryTaskReply +type AddSensitiveDataDiscoveryTaskReply struct { + // add sensitive data discovery task reply + Data AddSensitiveDataDiscoveryTaskData `json:"data"` + + base.GenericResp +} + +// swagger:enum SensitiveDataDiscoveryTaskAction +type SensitiveDataDiscoveryTaskAction string + +const ( + SensitiveDataDiscoveryTaskActionEnable SensitiveDataDiscoveryTaskAction = "ENABLE" + SensitiveDataDiscoveryTaskActionTerminate SensitiveDataDiscoveryTaskAction = "TERMINATE" + SensitiveDataDiscoveryTaskActionUpdate SensitiveDataDiscoveryTaskAction = "UPDATE" +) + +// swagger:model UpdateSensitiveDataDiscoveryTaskReq +type UpdateSensitiveDataDiscoveryTaskReq struct { + // project uid + // in: path + // swagger:ignore + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // sensitive data discovery task id + // in: path + // swagger:ignore + // Required: true + // Example: 1 + TaskID int `param:"task_id" json:"task_id" validate:"required"` + // action type: ENABLE(启用周期扫描), TERMINATE(终止周期扫描), UPDATE(更新配置) + // Required: true + // Example: "ENABLE" + Action SensitiveDataDiscoveryTaskAction `json:"action" validate:"required,oneof=ENABLE TERMINATE UPDATE"` + // task update data, required when action is UPDATE + Task *UpdateSensitiveDataDiscoveryTask `json:"task"` +} + +// swagger:model UpdateSensitiveDataDiscoveryTask +type UpdateSensitiveDataDiscoveryTask struct { + // masking template id + // Example: 1 + MaskingTemplateID int `json:"masking_template_id"` + // sensitive data identification method + // Example: "BY_FIELD_NAME" + IdentificationMethod SensitiveDataIdentificationMethod `json:"identification_method" validate:"oneof=BY_FIELD_NAME BY_SAMPLE_DATA"` + // execution plan + // Example: "PERIODIC" + ExecutionPlan SensitiveDataDiscoveryTaskType `json:"execution_plan" validate:"oneof=PERIODIC ONE_TIME"` + // cron expression, only used when execution_plan is PERIODIC + // Example: "0 0 * * *" + CronExpression string `json:"cron_expression"` +} + +// swagger:model UpdateSensitiveDataDiscoveryTaskData +type UpdateSensitiveDataDiscoveryTaskData struct { + // suspected sensitive fields tree + SuspectedSensitiveFieldsTree SuspectedSensitiveFieldsTree `json:"suspected_sensitive_fields_tree"` +} + +// swagger:model UpdateSensitiveDataDiscoveryTaskReply +type UpdateSensitiveDataDiscoveryTaskReply struct { + // update sensitive data discovery task reply + Data UpdateSensitiveDataDiscoveryTaskData `json:"data"` + + base.GenericResp +} + +// swagger:parameters DeleteSensitiveDataDiscoveryTask +type DeleteSensitiveDataDiscoveryTaskReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // sensitive data discovery task id + // in: path + // Required: true + // Example: 1 + TaskID int `param:"task_id" json:"task_id" validate:"required"` +} + +// swagger:model DeleteSensitiveDataDiscoveryTaskReply +type DeleteSensitiveDataDiscoveryTaskReply struct { + base.GenericResp +} + +// swagger:parameters ListSensitiveDataDiscoveryTaskHistories +type ListSensitiveDataDiscoveryTaskHistoriesReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // sensitive data discovery task id + // in: path + // Required: true + // Example: 1 + TaskID int `param:"task_id" json:"task_id" validate:"required"` + // the maximum count of histories to be returned, default is 20 + // in: query + // Example: 20 + PageSize uint32 `query:"page_size" json:"page_size"` + // the offset of histories to be returned, default is 0 + // in: query + // Example: 0 + PageIndex uint32 `query:"page_index" json:"page_index"` +} + +// swagger:model ListSensitiveDataDiscoveryTaskHistoriesData +type ListSensitiveDataDiscoveryTaskHistoriesData struct { + // execution time in RFC3339 format + // Format: date-time (RFC3339) + // Example: "2024-01-15T10:30:00Z" + ExecutedAt string `json:"executed_at"` + // execution status + // Example: "NORMAL" + Status SensitiveDataDiscoveryTaskStatus `json:"status"` + // newly discovered sensitive field count + // Example: 10 + NewSensitiveFieldCount int `json:"new_sensitive_field_count"` + // remark + // Example: "scan completed successfully" + Remark string `json:"remark"` +} + +// swagger:model ListSensitiveDataDiscoveryTaskHistoriesReply +type ListSensitiveDataDiscoveryTaskHistoriesReply struct { + // sensitive data discovery task histories reply + Data []ListSensitiveDataDiscoveryTaskHistoriesData `json:"data"` + // total count of sensitive data discovery task histories + // Example: 100 + Total int64 `json:"total_nums"` + + base.GenericResp +} + +// swagger:model ConfigureMaskingRulesReq +type ConfigureMaskingRulesReq struct { + // project uid + // in: path + // swagger:ignore + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // masking rule configurations for batch create or update + // Required: true + // MinLength: 1 + MaskingRuleConfigs []MaskingRuleConfig `json:"masking_rule_configs" validate:"required,min=1"` +} + +// swagger:model MaskingRuleConfig +type MaskingRuleConfig struct { + // data source id + // Required: true + // Example: "1" + DBServiceUID string `json:"db_service_uid" validate:"required"` + // schema name + // Required: true + // Example: "db1" + SchemaName string `json:"schema_name" validate:"required"` + // table name + // Required: true + // Example: "users" + TableName string `json:"table_name" validate:"required"` + // column name + // Required: true + // Example: "email" + ColumnName string `json:"column_name" validate:"required"` + // masking rule id + // Required: true + // Example: 1 + MaskingRuleID int `json:"masking_rule_id" validate:"required"` + // whether to enable masking for this column + // Required: true + // Example: true + IsMaskingEnabled bool `json:"is_masking_enabled" validate:"required"` +} + +// swagger:model ConfigureMaskingRulesReply +type ConfigureMaskingRulesReply struct { + base.GenericResp +} + +// swagger:enum MaskingConfigStatus +type MaskingConfigStatus string + +const ( + MaskingConfigStatusConfigured MaskingConfigStatus = "CONFIGURED" + MaskingConfigStatusPendingConfirm MaskingConfigStatus = "PENDING_CONFIRM" + MaskingConfigStatusSystemConfirmed MaskingConfigStatus = "SYSTEM_CONFIRMED" +) + +// swagger:parameters GetMaskingOverviewTree +type GetMaskingOverviewTreeReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // data source id + // in: query + // Required: true + // Example: "1" + DBServiceUID string `query:"db_service_uid" json:"db_service_uid" validate:"required"` + // fuzzy search keywords for column name + // in: query + // Example: "user" + Keywords string `query:"keywords" json:"keywords"` + // masking config status filters + // in: query + MaskingConfigStatus MaskingConfigStatus `query:"masking_config_statuses" json:"masking_config_statuses"` +} + +// swagger:model MaskingOverviewDashboard +type MaskingOverviewDashboard struct { + // total count of tables that contain sensitive data + // Example: 50 + TotalSensitiveTables int `json:"total_sensitive_tables"` + // total count of columns with configured masking + // Example: 120 + ConfiguredMaskingColumns int `json:"configured_masking_columns"` + // total count of columns pending masking confirmation + // Example: 5 + PendingConfirmMaskingColumns int `json:"pending_confirm_masking_columns"` +} + +// swagger:model MaskingOverviewTableData +type MaskingOverviewTableData struct { + // table id + // Example: 1 + TableID int `json:"table_id"` + // configured masking column count for this table + // Example: 3 + ConfiguredMaskingColumns int `json:"configured_masking_columns"` + // pending masking confirmation column count for this table + // Example: 1 + PendingConfirmMaskingColumns int `json:"pending_confirm_masking_columns"` +} + +// swagger:model MaskingOverviewDatabaseNode +type MaskingOverviewDatabaseNode struct { + // table_name -> table overview data + Tables map[string]MaskingOverviewTableData `json:"tables"` +} + +// swagger:model GetMaskingOverviewTreeData +type GetMaskingOverviewTreeData struct { + // dashboard summary for the selected data source + Dashboard MaskingOverviewDashboard `json:"dashboard"` + // database_name -> database node + Databases map[string]MaskingOverviewDatabaseNode `json:"databases"` +} + +// swagger:model GetMaskingOverviewTreeReply +type GetMaskingOverviewTreeReply struct { + // masking overview tree reply + Data GetMaskingOverviewTreeData `json:"data"` + + base.GenericResp +} + +// swagger:parameters GetTableColumnMaskingDetails +type GetTableColumnMaskingDetailsReq struct { + // project uid + // + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // table id from masking overview tree + // in: path + // Required: true + // Example: 1 + TableID int `param:"table_id" json:"table_id" validate:"required"` + // fuzzy search keywords for column name + // in: query + // Example: "phone" + Keywords string `query:"keywords" json:"keywords"` +} + +// swagger:model TableColumnMaskingDetail +type TableColumnMaskingDetail struct { + // column name + // Example: "email" + ColumnName string `json:"column_name"` + // current masking rule id, null if no masking rule is applied + // + // Example: 1 + MaskingRuleID *int `json:"masking_rule_id"` + // current masking rule name, null if no masking rule is applied + // + // Example: "Email Masking" + MaskingRuleName *string `json:"masking_rule_name"` + // confidence level of masking recommendation,null if no masking rule is applied + // + // Example: 2 + Confidence *ConfidenceLevel `json:"confidence"` + // current masking config status + Status MaskingConfigStatus `json:"status"` +} + +// swagger:model GetTableColumnMaskingDetailsReply +type GetTableColumnMaskingDetailsReply struct { + // table column masking details reply + Data []TableColumnMaskingDetail `json:"data"` + + base.GenericResp +} + +// swagger:parameters ListPendingApprovalRequests +type ListPendingApprovalRequestsReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // the maximum count of requests to be returned, default is 20 + // in: query + // Example: 20 + PageSize uint32 `query:"page_size" json:"page_size"` + // the offset of requests to be returned, default is 0 + // in: query + // Example: 0 + PageIndex uint32 `query:"page_index" json:"page_index"` +} + +// swagger:model PendingApprovalRequestData +type PendingApprovalRequestData struct { + // approval request id + // Example: 1 + ID int `json:"id"` + // applicant name + // Example: "admin" + ApplicantName string `json:"applicant_name"` + // application time in RFC3339 format + // Format: date-time (RFC3339) + // Example: "2024-01-15T10:30:00Z" + AppliedAt string `json:"applied_at"` + // application reason + // Example: "data analysis" + Reason string `json:"reason"` + // data scope + // Example: "database 'db1', table 'users'" + DataScope string `json:"data_scope"` +} + +// swagger:model ListPendingApprovalRequestsReply +type ListPendingApprovalRequestsReply struct { + // pending approval requests reply + Data []PendingApprovalRequestData `json:"data"` + // total count of pending approval requests + // Example: 100 + Total int64 `json:"total_nums"` + + base.GenericResp +} + +// swagger:enum ApprovalAction +type ApprovalAction string + +const ( + ApprovalActionApprove ApprovalAction = "APPROVE" + ApprovalActionReject ApprovalAction = "REJECT" +) + +// swagger:model ProcessApprovalRequestReq +type ProcessApprovalRequestReq struct { + // project uid + // in: path + // swagger:ignore + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // approval request id + // in: path + // swagger:ignore + // Required: true + // Example: 1 + RequestID int `param:"request_id" json:"request_id" validate:"required"` + // process action + // Required: true + // Example: "APPROVE" + Action ApprovalAction `json:"action" validate:"required"` + // reject reason, required when action is REJECT + // Example: "insufficient reason" + RejectReason string `json:"reject_reason"` + // approval remark, optional when action is APPROVE + // Example: "approved for one-time access" + ApproveRemark string `json:"approve_remark"` +} + +// swagger:model ProcessApprovalRequestReply +type ProcessApprovalRequestReply struct { + base.GenericResp +} + +// swagger:parameters GetPlaintextAccessRequestDetail +type GetPlaintextAccessRequestDetailReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // approval request id + // in: path + // Required: true + // Example: 1 + RequestID int `param:"request_id" json:"request_id" validate:"required"` +} + +// swagger:model MaskingPreviewData +type MaskingPreviewData struct { + // preview columns + // Example: ["id", "name", "email"] + Columns []string `json:"columns"` + // preview rows + // Example: [["1", "John", "j***@example.com"], ["2", "Alice", "a***@example.com"]] + Rows [][]string `json:"rows"` +} + +// swagger:model GetPlaintextAccessRequestDetailReply +type GetPlaintextAccessRequestDetailReply struct { + // plaintext access request detail reply + Data struct { + // query sql statement + // Example: "SELECT * FROM users" + QuerySQL string `json:"query_sql"` + // masking result preview + MaskingPreview MaskingPreviewData `json:"masking_preview"` + // application reason + // Example: "troubleshooting" + Reason string `json:"reason"` + } `json:"data"` + + base.GenericResp +} + +// swagger:parameters ListCreatableDBServicesForMaskingTask +// 用于获取可以创建敏感数据扫描任务的数据源列表 +type ListCreatableDBServicesForMaskingTaskReq struct { + // project uid + // in: path + // Required: true + // Example: "project_uid" + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // the maximum count of db services to be returned, default is 100 + // in: query + // Example: 100 + PageSize uint32 `query:"page_size" json:"page_size"` + // the offset of db services to be returned, default is 0 + // in: query + // Example: 0 + PageIndex uint32 `query:"page_index" json:"page_index"` + // fuzzy search keywords for db service name + // in: query + // Example: "mysql" + Keywords string `query:"keywords" json:"keywords"` +} + +// swagger:model ListCreatableDBServicesForMaskingTaskData +// 可创建扫描任务的数据源数据 +type ListCreatableDBServicesForMaskingTaskData struct { + // database instance uid + // Example: "db_service_uid_1" + DBServiceUID string `json:"db_service_uid"` + // database instance name + // Example: "mysql-01" + DBServiceName string `json:"db_service_name"` + // database type + // Example: "MySQL" + DBType string `json:"db_type"` + // database instance host + // Example: "10.10.10.10" + DBServiceHost string `json:"db_service_host"` + // database instance port + // Example: "3306" + DBServicePort string `json:"db_service_port"` +} + +// swagger:model ListCreatableDBServicesForMaskingTaskReply +type ListCreatableDBServicesForMaskingTaskReply struct { + // list of db services that can create masking discovery task + Data []ListCreatableDBServicesForMaskingTaskData `json:"data"` + // total count of db services + // Example: 10 + Total int64 `json:"total_nums"` + + base.GenericResp +} diff --git a/api/dms/service/v1/member.go b/api/dms/service/v1/member.go index 9e6ca72ea..ade6ca40a 100644 --- a/api/dms/service/v1/member.go +++ b/api/dms/service/v1/member.go @@ -3,7 +3,7 @@ package v1 import ( "fmt" - base "github.com/actiontech/dms/api/base/v1" + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" ) // A member @@ -11,13 +11,12 @@ type Member struct { // member user uid // Required: true UserUid string `json:"user_uid" validate:"required"` - // Whether the member has namespace admin permission - IsNamespaceAdmin bool `json:"is_namespace_admin"` - // namespace uid - // Required: true - NamespaceUid string `json:"namespace_uid"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` // member role with op ranges RoleWithOpRanges []MemberRoleWithOpRange `json:"role_with_op_ranges"` + // member project manage permissions + ProjectManagePermissions []string `json:"project_manage_permissions"` } type MemberRoleWithOpRange struct { @@ -29,10 +28,10 @@ type MemberRoleWithOpRange struct { RangeUIDs []string `json:"range_uids" validate:"required"` } -// swagger:parameters AddMember +// swagger:model type AddMemberReq struct { - // Add new member - // in:body + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` Member *Member `json:"member" validate:"required"` } @@ -46,10 +45,10 @@ func (u *AddMemberReq) String() string { // swagger:model AddMemberReply type AddMemberReply struct { // Add member reply - Payload struct { + Data struct { // member UID Uid string `json:"uid"` - } `json:"payload"` + } `json:"data"` // Generic reply base.GenericResp @@ -59,7 +58,7 @@ func (u *AddMemberReply) String() string { if u == nil { return "AddMemberReply{nil}" } - return fmt.Sprintf("AddMemberReply{Uid:%s}", u.Payload.Uid) + return fmt.Sprintf("AddMemberReply{Uid:%s}", u.Data.Uid) } // swagger:parameters ListMembers @@ -77,10 +76,10 @@ type ListMemberReq struct { // filter the member user uid // in:query FilterByUserUid string `query:"filter_by_user_uid" json:"filter_by_user_uid"` - // the member namespace uid - // in:query + // project id // Required: true - NamespaceUid string `query:"namespace_uid" json:"namespace_uid" validate:"required"` + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` } // swagger:enum MemberOrderByField @@ -97,6 +96,10 @@ type ListMemberRoleWithOpRange struct { OpRangeType OpRangeType `json:"op_range_type" validate:"required"` // op range uids RangeUIDs []UidWithName `json:"range_uids" validate:"required"` + // member op permissions + OpPermissions []UidWithName `json:"op_permissions"` + // member group + MemberGroup *ProjectMemberGroup `json:"member_group"` } // A dms member @@ -105,19 +108,99 @@ type ListMember struct { MemberUid string `json:"uid"` // member user User UidWithName `json:"user"` - // Whether the member has namespace admin permission - IsNamespaceAdmin bool `json:"is_namespace_admin"` + // Whether the member is a group member + IsGroupMember bool `json:"is_group_member"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` + // current project admin info + CurrentProjectAdmin CurrentProjectAdmin `json:"current_project_admin"` // member op permission RoleWithOpRanges []ListMemberRoleWithOpRange `json:"role_with_op_ranges"` + // current project permission + CurrentProjectOpPermissions []ProjectOpPermission `json:"current_project_op_permissions"` + // current project manage permissions + CurrentProjectManagePermissions []ProjectManagePermission `json:"current_project_manage_permissions"` + // member platform roles + PlatformRoles []UidWithName `json:"platform_roles"` + // member projects + Projects []string `json:"projects"` +} + +type CurrentProjectAdmin struct { + IsAdmin bool `json:"is_admin"` + MemberGroups []string `json:"member_groups"` +} + +type ProjectManagePermission struct { + Uid string `json:"uid"` + Name string `json:"name"` + MemberGroup string `json:"member_group"` +} + +type ProjectOpPermission struct { + DataSource string `json:"data_source"` + Roles []ProjectRole `json:"roles"` +} + +type ProjectRole struct { + Uid string `json:"uid"` + Name string `json:"name"` + OpPermissions []UidWithName `json:"op_permissions"` + MemberGroup *ProjectMemberGroup `json:"member_group"` +} + +type ProjectMemberGroup struct { + Uid string `json:"uid"` + Name string `json:"name"` + Users []UidWithName `json:"users"` + OpPermissions []UidWithName `json:"op_permissions"` } // swagger:model ListMemberReply type ListMemberReply struct { // List member reply - Payload struct { - Members []*ListMember `json:"members"` - Total int64 `json:"total"` - } `json:"payload"` + Data []*ListMember `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +// swagger:parameters ListMemberTips +type ListMemberTipsReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:parameters ListMemberGroupTips +type ListMemberGroupTipsReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:model ListMemberGroupTipsReply +type ListMemberGroupTipsReply struct { + // List member group tip reply + Data []UidWithName `json:"data"` + + // Generic reply + base.GenericResp +} + + +type ListMemberTipsItem struct { + UserId string `json:"user_id"` + UserName string `json:"user_name"` +} + +// swagger:model ListMemberTipsReply +type ListMemberTipsReply struct { + // List member tip reply + Data []ListMemberTipsItem `json:"data"` // Generic reply base.GenericResp @@ -125,6 +208,10 @@ type ListMemberReply struct { // swagger:parameters DelMember type DelMemberReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` // member uid // in:path MemberUid string `param:"member_uid" json:"member_uid" validate:"required"` @@ -138,20 +225,20 @@ func (u *DelMemberReq) String() string { } type UpdateMember struct { - // Whether the member has namespace admin permission - IsNamespaceAdmin bool `json:"is_namespace_admin"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` // member role with op ranges RoleWithOpRanges []MemberRoleWithOpRange `json:"role_with_op_ranges"` + // member project manage permissions + ProjectManagePermissions []string `json:"project_manage_permissions"` } -// swagger:parameters UpdateMember +// swagger:model type UpdateMemberReq struct { - // Member uid - // Required: true - // in:path + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // swagger:ignore MemberUid string `param:"member_uid" json:"member_uid" validate:"required"` - // Update a member - // in:body Member *UpdateMember `json:"member" validate:"required"` } diff --git a/api/dms/service/v1/member_group.go b/api/dms/service/v1/member_group.go new file mode 100644 index 000000000..e260cd124 --- /dev/null +++ b/api/dms/service/v1/member_group.go @@ -0,0 +1,158 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:enum MemberGroupOrderByField +type MemberGroupOrderByField string + +const ( + MemberGroupOrderByName MemberGroupOrderByField = "name" +) + +// swagger:parameters ListMemberGroups +type ListMemberGroupsReq struct { + // the maximum count of member to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of members to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy MemberGroupOrderByField `query:"order_by" json:"order_by"` + // filter the user group name + // in:query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +type ListMemberGroup struct { + Name string `json:"name"` + // member uid + Uid string `json:"uid"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` + // member user + Users []UidWithName `json:"users"` + // member op permission + RoleWithOpRanges []ListMemberRoleWithOpRange `json:"role_with_op_ranges"` + // current project permission + CurrentProjectOpPermissions []ProjectOpPermission `json:"current_project_op_permissions"` + // member project manage permissions + CurrentProjectManagePermissions []UidWithName `json:"current_project_manage_permissions"` +} + +// swagger:model ListMemberGroupsReply +type ListMemberGroupsReply struct { + // List member reply + Data []*ListMemberGroup `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +type GetMemberGroup struct { + Name string `json:"name"` + // member group uid + Uid string `json:"uid"` + // member user + Users []UidWithName `json:"users"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` + // member op permission + RoleWithOpRanges []ListMemberRoleWithOpRange `json:"role_with_op_ranges"` +} + +// swagger:parameters GetMemberGroup +type GetMemberGroupReq struct { + // Member group id + // Required: true + // in:path + MemberGroupUid string `param:"member_group_uid" json:"member_group_uid" validate:"required"` + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:model GetMemberGroupReply +type GetMemberGroupReply struct { + // List member reply + Data *GetMemberGroup `json:"data"` + + // Generic reply + base.GenericResp +} + +type MemberGroup struct { + // member group name + // Required: true + Name string `json:"name" validate:"required"` + // member user uid + // Required: true + UserUids []string `json:"user_uids" validate:"required"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` + // member role with op ranges + RoleWithOpRanges []MemberRoleWithOpRange `json:"role_with_op_ranges"` + // member project manage permissions + ProjectManagePermissions []string `json:"project_manage_permissions"` +} + +// swagger:model +type AddMemberGroupReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + MemberGroup MemberGroup `json:"member_group" validate:"required"` +} + +// swagger:model AddMemberGroupReply +type AddMemberGroupReply struct { + // Add member group reply + Data struct { + // member group ID + Id string `json:"id"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +type UpdateMemberGroup struct { + // member user uid + // Required: true + UserUids []string `json:"user_uids" validate:"required"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` + // member role with op ranges + RoleWithOpRanges []MemberRoleWithOpRange `json:"role_with_op_ranges"` + // member project manage permissions + ProjectManagePermissions []string `json:"project_manage_permissions"` +} + +// swagger:model +type UpdateMemberGroupReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // swagger:ignore + MemberGroupUid string `param:"member_group_uid" json:"member_group_uid" validate:"required"` + MemberGroup *UpdateMemberGroup `json:"member_group" validate:"required"` +} + +// swagger:parameters DeleteMemberGroup +type DeleteMemberGroupReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // member group id + // in:path + MemberGroupUid string `param:"member_group_uid" json:"member_group_uid" validate:"required"` +} diff --git a/api/dms/service/v1/namespace.go b/api/dms/service/v1/namespace.go deleted file mode 100644 index c60fff077..000000000 --- a/api/dms/service/v1/namespace.go +++ /dev/null @@ -1,104 +0,0 @@ -package v1 - -import ( - "fmt" - - base "github.com/actiontech/dms/api/base/v1" -) - -// A Namespace -type Namespace struct { - // namespace name - Name string `json:"name"` - // namespace desc - Desc string `json:"desc"` -} - -// swagger:parameters AddNamespace -type AddNamespaceReq struct { - // Add new Namespace - // in:body - Namespace *Namespace `json:"namespace" validate:"required"` -} - -func (u *AddNamespaceReq) String() string { - if u == nil { - return "AddNamespaceReq{nil}" - } - return fmt.Sprintf("AddNamespaceReq{NamespaceName:%s}", u.Namespace.Name) -} - -// swagger:model AddNamespaceReply -type AddNamespaceReply struct { - // Add Namespace reply - Payload struct { - // Namespace UID - Uid string `json:"uid"` - } `json:"payload"` - - // Generic reply - base.GenericResp -} - -func (u *AddNamespaceReply) String() string { - if u == nil { - return "AddNamespaceReply{nil}" - } - return fmt.Sprintf("AddNamespaceReply{Uid:%s}", u.Payload.Uid) -} - -// swagger:parameters DelNamespace -type DelNamespaceReq struct { - // namespace uid - // in:path - NamespaceUid string `param:"namespace_uid" json:"namespace_uid" validate:"required"` -} - -func (u *DelNamespaceReq) String() string { - if u == nil { - return "DelNamespaceReq{nil}" - } - return fmt.Sprintf("DelNamespaceReq{Uid:%s}", u.NamespaceUid) -} - -type UpdateNamespace struct { - // Namespace desc - Desc *string `json:"desc"` -} - -// swagger:parameters UpdateNamespace -type UpdateNamespaceReq struct { - // Namespace uid - // Required: true - // in:path - NamespaceUid string `param:"namespace_uid" json:"namespace_uid" validate:"required"` - // Update a namespace - // in:body - Namespace *UpdateNamespace `json:"namespace" validate:"required"` -} - -func (u *UpdateNamespaceReq) String() string { - if u == nil { - return "UpdateNamespaceReq{nil}" - } - if u.Namespace == nil { - return "UpdateNamespaceReq{Namespace:nil}" - } - return fmt.Sprintf("UpdateNamespaceReq{Uid:%s}", u.NamespaceUid) -} - -// swagger:parameters ArchiveNamespace -type ArchiveNamespaceReq struct { - // Namespace uid - // Required: true - // in:path - NamespaceUid string `param:"namespace_uid" json:"namespace_uid" validate:"required"` -} - -// swagger:parameters UnarchiveNamespace -type UnarchiveNamespaceReq struct { - // Namespace uid - // Required: true - // in:path - NamespaceUid string `param:"namespace_uid" json:"namespace_uid" validate:"required"` -} diff --git a/api/dms/service/v1/op_permission.go b/api/dms/service/v1/op_permission.go index 4cf76c6d1..30b032c0f 100644 --- a/api/dms/service/v1/op_permission.go +++ b/api/dms/service/v1/op_permission.go @@ -3,7 +3,7 @@ package v1 import ( "fmt" - base "github.com/actiontech/dms/api/base/v1" + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" ) // swagger:enum OpRangeType @@ -13,9 +13,9 @@ const ( OpRangeTypeUnknown OpRangeType = "unknown" // 全局权限: 该权限只能被用户使用 OpRangeTypeGlobal OpRangeType = "global" - // 空间权限: 该权限只能被成员使用 - OpRangeTypeNamespace OpRangeType = "namespace" - // 空间内的数据源权限: 该权限只能被成员使用 + // 项目权限: 该权限只能被成员使用 + OpRangeTypeProject OpRangeType = "project" + // 项目内的数据源权限: 该权限只能被成员使用 OpRangeTypeDBService OpRangeType = "db_service" ) @@ -23,8 +23,8 @@ func ParseOpRangeType(typ string) (OpRangeType, error) { switch typ { case string(OpRangeTypeDBService): return OpRangeTypeDBService, nil - case string(OpRangeTypeNamespace): - return OpRangeTypeNamespace, nil + case string(OpRangeTypeProject): + return OpRangeTypeProject, nil case string(OpRangeTypeGlobal): return OpRangeTypeGlobal, nil default: @@ -47,6 +47,9 @@ type ListOpPermissionReq struct { // filter by op permission target // in:query FilterByTarget OpPermissionTarget `query:"filter_by_target" json:"filter_by_target" validate:"required"` + // filter by service + // in:query + Service *Service `query:"service" json:"service"` } // swagger:enum OpPermissionTarget @@ -56,6 +59,15 @@ const ( OpPermissionTargetAll OpPermissionTarget = "all" OpPermissionTargetUser OpPermissionTarget = "user" OpPermissionTargetMember OpPermissionTarget = "member" + OpPermissionTargetProject OpPermissionTarget = "project" +) + +// swagger:enum Service +type Service string + +const ( + ServiceDMS Service = "dms" + ServiceSQLE Service = "sqle" ) // swagger:enum OpPermissionOrderByField @@ -69,17 +81,17 @@ const ( type ListOpPermission struct { // op permission OpPermission UidWithName `json:"op_permission"` + Module string `json:"module"` Description string `json:"description"` RangeType OpRangeType `json:"range_type"` + Service Service `json:"service"` } // swagger:model ListOpPermissionReply type ListOpPermissionReply struct { // List op_permission reply - Payload struct { - OpPermissions []*ListOpPermission `json:"op_permissions"` - Total int64 `json:"total"` - } `json:"payload"` + Data []*ListOpPermission `json:"data"` + Total int64 `json:"total_nums"` // Generic reply base.GenericResp diff --git a/api/dms/service/v1/operation_record.go b/api/dms/service/v1/operation_record.go new file mode 100644 index 000000000..1ab6d2680 --- /dev/null +++ b/api/dms/service/v1/operation_record.go @@ -0,0 +1,100 @@ +package v1 + +import ( + "time" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" +) + +// swagger:model +type AddOperationRecordReq struct { + OperationRecord *OperationRecord `json:"operation_record" validate:"required"` +} + +// swagger:model AddOperationRecordReply +type AddOperationRecordReply struct { + base.GenericResp +} + +type OperationRecord struct { + OperationTime time.Time `json:"operation_time"` + OperationUserName string `json:"operation_user_name" validate:"required"` + OperationReqIP string `json:"operation_req_ip"` + OperationUserAgent string `json:"operation_user_agent"` + OperationTypeName string `json:"operation_type_name"` + OperationAction string `json:"operation_action"` + OperationProjectName string `json:"operation_project_name"` + OperationStatus string `json:"operation_status"` + OperationI18nContent i18nPkg.I18nStr `json:"operation_i18n_content"` +} + +// swagger:parameters GetOperationRecordList +type GetOperationRecordListReq struct { + // in:query + FilterOperateTimeFrom string `json:"filter_operate_time_from" query:"filter_operate_time_from"` + // in:query + FilterOperateTimeTo string `json:"filter_operate_time_to" query:"filter_operate_time_to"` + // in:query + FilterOperateProjectName *string `json:"filter_operate_project_name" query:"filter_operate_project_name"` + // in:query + FuzzySearchOperateUserName string `json:"fuzzy_search_operate_user_name" query:"fuzzy_search_operate_user_name"` + // in:query + FilterOperateTypeName string `json:"filter_operate_type_name" query:"filter_operate_type_name"` + // in:query + FilterOperateAction string `json:"filter_operate_action" query:"filter_operate_action"` + // in:query + // Required: true + PageIndex uint32 `json:"page_index" query:"page_index" validate:"required"` + // in:query + // Required: true + PageSize uint32 `json:"page_size" query:"page_size" validate:"required"` +} + +// swagger:model GetOperationRecordListReply +type GetOperationRecordListReply struct { + Data []OperationRecordListItem `json:"data"` + TotalNums uint64 `json:"total_nums"` + base.GenericResp +} + +type OperationRecordListItem struct { + ID uint64 `json:"id"` + OperationTime *time.Time `json:"operation_time"` + OperationUser OperationUser `json:"operation_user"` + OperationUserAgent string `json:"operation_user_agent"` + OperationTypeName string `json:"operation_type_name"` + OperationAction string `json:"operation_action"` + OperationContent string `json:"operation_content"` + ProjectName string `json:"project_name"` + // enum: ["succeeded","failed"] + Status string `json:"status"` +} + +type OperationUser struct { + UserName string `json:"user_name"` + IP string `json:"ip"` +} + +// swagger:parameters ExportOperationRecordList +type ExportOperationRecordListReq struct { + // in:query + FilterOperateTimeFrom string `json:"filter_operate_time_from" query:"filter_operate_time_from"` + // in:query + FilterOperateTimeTo string `json:"filter_operate_time_to" query:"filter_operate_time_to"` + // in:query + FilterOperateProjectName *string `json:"filter_operate_project_name" query:"filter_operate_project_name"` + // in:query + FuzzySearchOperateUserName string `json:"fuzzy_search_operate_user_name" query:"fuzzy_search_operate_user_name"` + // in:query + FilterOperateTypeName string `json:"filter_operate_type_name" query:"filter_operate_type_name"` + // in:query + FilterOperateAction string `json:"filter_operate_action" query:"filter_operate_action"` +} + +// swagger:response ExportOperationRecordListReply +type ExportOperationRecordListReply struct { + // swagger:file + // in: body + File []byte +} diff --git a/api/dms/service/v1/project.go b/api/dms/service/v1/project.go new file mode 100644 index 000000000..3c8ffa660 --- /dev/null +++ b/api/dms/service/v1/project.go @@ -0,0 +1,315 @@ +package v1 + +import ( + "bytes" + "fmt" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +// swagger:model ProjectV1 +type Project struct { + // project name + Name string `json:"name"` + // project desc + Desc string `json:"desc"` + // is fixed business + IsFixedBusiness bool `json:"is_fixed_business"` + // project business + Business []string `json:"business"` + // project priority + ProjectPriority dmsCommonV1.ProjectPriority `json:"project_priority" enums:"high,medium,low"` +} + +// swagger:model +type AddProjectReq struct { + Project *Project `json:"project" validate:"required"` +} + +func (u *AddProjectReq) String() string { + if u == nil { + return "AddProjectReq{nil}" + } + return fmt.Sprintf("AddProjectReq{ProjectName:%s}", u.Project.Name) +} + +// swagger:model AddProjectReply +type AddProjectReply struct { + // Add Project reply + Data struct { + // Project UID + Uid string `json:"uid"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +func (u *AddProjectReply) String() string { + if u == nil { + return "AddProjectReply{nil}" + } + return fmt.Sprintf("AddProjectReply{Uid:%s}", u.Data.Uid) +} + +// swagger:parameters DelProject +type DelProjectReq struct { + // project uid + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +func (u *DelProjectReq) String() string { + if u == nil { + return "DelProjectReq{nil}" + } + return fmt.Sprintf("DelProjectReq{Uid:%s}", u.ProjectUid) +} + +// swagger:model UpdateProject +type UpdateProject struct { + // Project desc + Desc *string `json:"desc"` + // is fixed business + IsFixedBusiness *bool `json:"is_fixed_business"` + // Project business + Business []BusinessForUpdate `json:"business"` + // project priority + ProjectPriority *dmsCommonV1.ProjectPriority `json:"project_priority" enums:"high,medium,low"` +} + +type BusinessForUpdate struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// swagger:model +type UpdateProjectReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + Project *UpdateProject `json:"project" validate:"required"` +} + +func (u *UpdateProjectReq) String() string { + if u == nil { + return "UpdateProjectReq{nil}" + } + if u.Project == nil { + return "UpdateProjectReq{Project:nil}" + } + return fmt.Sprintf("UpdateProjectReq{Uid:%s}", u.ProjectUid) +} + +// swagger:parameters ArchiveProject +type ArchiveProjectReq struct { + // Project uid + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:parameters UnarchiveProject +type UnarchiveProjectReq struct { + // Project uid + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` +} + +// swagger:model +type ImportProjectsReq struct { + Projects []*ImportProjects `json:"projects" validate:"required"` +} + +type ImportProjects struct { + // Project name + Name string `json:"name" validate:"required"` + // Project desc + Desc string `json:"desc"` + // business + Business []string `json:"business" validate:"required"` +} + +// swagger:parameters PreviewImportProjects +type PreviewImportProjectsRep struct { + // projects file. + // + // in: formData + // + // swagger:file + ProjectsFile *bytes.Buffer `json:"projects_file"` +} + +// swagger:model PreviewImportProjectsReply +type PreviewImportProjectsReply struct { + // Generic reply + base.GenericResp + // list preview import projects + Data []*PreviewImportProjects `json:"data"` +} + +type PreviewImportProjects struct { + // Project name + Name string `json:"name"` + // Project desc + Desc string `json:"desc"` + // business + Business []string `json:"business"` +} + +// swagger:parameters ExportProjects +type ExportProjectsReq struct { + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy dmsCommonV1.ProjectOrderByField `query:"order_by" json:"order_by"` + // filter the Project name + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // filter the Project UID + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` +} + +// swagger:response ExportProjectsReply +type ExportProjectsReply struct { + // swagger:file + // in: body + File []byte +} + +// swagger:response GetImportProjectsTemplateReply +type GetImportProjectsTemplateReply struct { + // swagger:file + // in: body + File []byte +} + +// swagger:parameters GetProjectTips +type GetProjectTipsReq struct { + // Project uid + // in:query + ProjectUid string `query:"project_uid" json:"project_uid"` +} + +// swagger:model GetProjectTipsReply +type GetProjectTipsReply struct { + // Generic reply + base.GenericResp + // project tips + Data []*ProjectTips `json:"data"` +} + +type ProjectTips struct { + IsFixedBusiness bool `json:"is_fixed_business"` + Business []string `json:"business"` +} + +// swagger:response GetImportDBServicesTemplateReply +type GetImportDBServicesTemplateReply struct { + // swagger:file + // in: body + File []byte +} + +// swagger:parameters ImportDBServicesOfProjectsCheck +type ImportDBServicesOfProjectsCheckReq struct { + // DBServices file. + // + // in: formData + // + // swagger:file + DBServicesFile *bytes.Buffer `json:"db_services_file"` +} + +// swagger:response ImportDBServicesCheckCsvReply +type ImportDBServicesCheckCsvReply struct { + // swagger:file + // in: body + File []byte +} + +// swagger:model +type ImportDBServicesOfProjectsReq struct { + DBServices []ImportDBService `json:"db_services" validate:"required"` +} + +type CheckDbsConnectable struct { + // DB Service name + // Required: true + // example: mysql_1 + Name string `json:"name" example:"mysql_1" validate:"required"` + // DB Service type + // Required: true + // example: MySQL + DBType string `json:"db_type" example:"mysql" validate:"required"` + // DB Service admin user + // Required: true + // example: root + User string `json:"user" example:"root" valid:"required"` + // DB Service host + // Required: true + // example: 127.0.0.1 + Host string `json:"host" example:"10.10.10.10" valid:"required,ip_addr|uri|hostname|hostname_rfc1123"` + // DB Service port + // Required: true + // example: 3306 + Port string `json:"port" example:"3306" valid:"required,port"` + // DB Service admin password + // Required: true + // example: 123456 + Password string `json:"password" example:"123456"` + // DB Service Custom connection parameters + // Required: false + AdditionalParams []*dmsCommonV1.AdditionalParam `json:"additional_params" from:"additional_params"` +} + +// swagger:model +type DBServiceConnectionReq struct { + DBServices []CheckDbsConnectable `json:"db_services"` +} + +// swagger:model +type DBServicesConnectionReq struct { + DBServices []DbServiceConnections `json:"db_services"` +} + +type DbServiceConnections struct { + DBServiceUid string `param:"db_service_uid" json:"db_service_uid"` +} + +// swagger:model DBServicesConnectionReqReply +type DBServicesConnectionReqReply struct { + Data []DBServiceIsConnectableReply `json:"data"` + base.GenericResp +} + +type DBServicesConnectionItem struct { + // Successful connection num + SuccessfulNum int `json:"successful_num"` + // Failed connection num + FailedNum int `json:"failed_num"` + // Failed DBServices name + FailedNames []string `json:"failed_names"` +} + +// swagger:model DBServicesConnectionReply +type DBServicesConnectionReply struct { + // Generic reply + base.GenericResp + // connection result + Data *DBServicesConnectionItem `json:"data"` +} + +// swagger:model +type CheckDBServicesPrivilegesReq struct { + DBServices []dmsCommonV1.CheckDbConnectable `json:"db_services"` +} + +// swagger:model CheckDBServicesPrivilegesReply +type CheckDBServicesPrivilegesReply struct { + base.GenericResp + Data []CheckDBServicesPrivilegesItem `json:"data"` +} + +type CheckDBServicesPrivilegesItem struct { + CheckDBServicesPrivileges []CheckDBServiceIsConnectableReplyItem +} diff --git a/api/dms/service/v1/resource_overview.go b/api/dms/service/v1/resource_overview.go new file mode 100644 index 000000000..93724487f --- /dev/null +++ b/api/dms/service/v1/resource_overview.go @@ -0,0 +1,183 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +// 资源概览接口组 API Model + +// 资源概览统计接口 +// route: /v1/dms/resource_overview/statistics +// Method: GET + +// swagger:parameters GetResourceOverviewStatisticsV1 +type ResourceOverviewStatisticsReq struct{} + +// swagger:model ResourceOverviewStatisticsResV1 +type ResourceOverviewStatisticsRes struct { + Data struct { + // 业务总数 + BusinessTotalNumber int64 `json:"business_total_number"` + // 项目总数 + ProjectTotalNumber int64 `json:"project_total_number"` + // 数据源总数 + DBServiceTotalNumber int64 `json:"db_service_total_number"` + } `json:"data"` + base.GenericResp +} + +// 资源类型分布接口 +// route: /v1/dms/resource_overview/resource_type_distribution +// Method: GET + +// swagger:parameters GetResourceOverviewResourceTypeDistributionV1 +type ResourceOverviewResourceTypeDistributionReq struct{} + +// swagger:model ResourceOverviewResourceTypeDistributionResV1 +type ResourceOverviewResourceTypeDistributionRes struct { + Data []*ResourceTypeDistributionData `json:"data"` + Total int64 `json:"total_nums"` + base.GenericResp +} + +// swagger:model ResourceTypeDistributionData +type ResourceTypeDistributionData struct { + // 资源类型 + ResourceType string `json:"resource_type"` + // 数量 + Count int64 `json:"count"` +} + +// 资源概览拓扑接口 +// route: /v1/dms/resource_overview/topology +// Method: GET + +// swagger:parameters GetResourceOverviewTopologyV1 +type ResourceOverviewTopologyReq struct { + ResourceOverviewFilter +} + +// swagger:parameters +type ResourceOverviewFilter struct { + // 根据数据源类型筛选 + // in:query + // type:string + FilterByDBType string `query:"filter_by_db_type" param:"filter_by_db_type" json:"filter_by_db_type"` + // 根据所属业务标签筛选 + // in:query + // type:string + FilterByBusinessTagUID string `query:"filter_by_business_tag_uid" param:"filter_by_business_tag_uid" json:"filter_by_business_tag_uid"` + // 根据环境属性标签筛选 + // in:query + // type:string + FilterByEnvironmentTagUID string `query:"filter_by_environment_tag_uid" param:"filter_by_environment_tag_uid" json:"filter_by_environment_tag_uid"` + // 根据所属项目筛选 + // in:query + // type:string + FilterByProjectUID string `query:"filter_by_project_uid" param:"filter_by_project_uid" json:"filter_by_project_uid"` + // 根据项目或数据源名称模糊搜索 + // in:query + // type:string + FuzzySearchResourceName string `query:"fuzzy_search_resource_name" param:"fuzzy_search_resource_name" json:"fuzzy_search_resource_name"` +} + +// swagger:enum ResourceListSortByField +type ResourceListSortByField string + +const ( + // 根据审核评分排序 + SortByFieldAuditScore ResourceListSortByField = "audit_score" + // 根据待处理工单数排序 + SortByFieldPendingWorkflowCount ResourceListSortByField = "pending_workflow_count" + // 根据高优先级SQL数排序 + SortByFieldHighPrioritySQLCount ResourceListSortByField = "high_priority_sql_count" +) + +// swagger:model ResourceOverviewTopologyResV1 +type ResourceOverviewTopologyRes struct { + // business:project = 1:n project:db_service = 1:n + Data []*Business `json:"data"` + Total int64 `json:"total_nums"` + base.GenericResp +} + +// swagger:model ResourceBusiness +type Business struct { + BusinessTag *BusinessTag `json:"business_tag"` + Project []*ResourceProject `json:"project"` +} + +// swagger:model ResourceProject +type ResourceProject struct { + ProjectUID string `json:"project_uid"` + ProjectName string `json:"project_name"` + DBService []*ResourceDBService `json:"db_service"` +} + +// swagger:model ResourceDBService +type ResourceDBService struct { + DBServiceUID string `json:"db_service_uid"` + DBServiceName string `json:"db_service_name"` +} + +// 资源详情列表接口 +// route: /v1/dms/resource_overview/resource_list +// Method: GET + +// swagger:parameters GetResourceOverviewResourceListV1 +type ResourceOverviewResourceListReq struct { + ResourceOverviewFilter + ResourceOverviewListOptions +} + +// swagger:parameters +type ResourceOverviewListOptions struct { + // in:query + // type:uint32 + PageIndex uint32 `query:"page_index" param:"page_index" json:"page_index"` + // in:query + // type:uint32 + PageSize uint32 `query:"page_size" param:"page_size" json:"page_size"` +} + +// swagger:model ResourceOverviewResourceListResV1 +type ResourceOverviewResourceListRes struct { + Data []*ResourceListData `json:"data"` + Total int64 `json:"total_nums"` + base.GenericResp +} + +// swagger:model ResourceListData +type ResourceListData struct { + // 资源UID + ResourceUID string `json:"resource_uid"` + // 资源类型 + ResourceType string `json:"resource_type"` + // 资源名称 + ResourceName string `json:"resource_name"` + // 所属业务 + BusinessTag *BusinessTag `json:"business_tag"` + // 所属项目 + Project *ResourceProject `json:"project"` + // 环境属性 + EnvironmentTag *dmsCommonV1.EnvironmentTag `json:"environment_tag"` + // 审核评分 + AuditScore float32 `json:"audit_score"` + // 待处理工单数 + PendingWorkflowCount int32 `json:"pending_workflow_count"` + // 高优先级SQL数 + HighPrioritySQLCount int32 `json:"high_priority_sql_count"` +} + +// swagger:parameters DownloadResourceOverviewList +type DownloadResourceOverviewListReq struct { + ResourceOverviewFilter +} + +// swagger:response DownloadResourceOverviewListRes +type DownloadResourceOverviewListRes struct { + // swagger:file + // in: body + File []byte +} diff --git a/api/dms/service/v1/role.go b/api/dms/service/v1/role.go index 0292214b7..dc20283b5 100644 --- a/api/dms/service/v1/role.go +++ b/api/dms/service/v1/role.go @@ -3,7 +3,8 @@ package v1 import ( "fmt" - base "github.com/actiontech/dms/api/base/v1" + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" ) // A role @@ -17,10 +18,8 @@ type Role struct { OpPermissionUids []string `json:"op_permission_uids"` } -// swagger:parameters AddRole +// swagger:model type AddRoleReq struct { - // Add new role - // in:body Role *Role `json:"role" validate:"required"` } @@ -34,10 +33,10 @@ func (u *AddRoleReq) String() string { // swagger:model AddRoleReply type AddRoleReply struct { // Add role reply - Payload struct { + Data struct { // role UID Uid string `json:"uid"` - } `json:"payload"` + } `json:"data"` // Generic reply base.GenericResp @@ -47,7 +46,7 @@ func (u *AddRoleReply) String() string { if u == nil { return "AddRoleReply{nil}" } - return fmt.Sprintf("AddRoleReply{Uid:%s}", u.Payload.Uid) + return fmt.Sprintf("AddRoleReply{Uid:%s}", u.Data.Uid) } // swagger:parameters DelRole @@ -79,6 +78,9 @@ type ListRoleReq struct { // filter the role name // in:query FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // the db service fuzzy keyword,include op_permission + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` } // swagger:enum RoleOrderByField @@ -95,20 +97,24 @@ type ListRole struct { // role name Name string `json:"name"` // role stat - Stat Stat `json:"stat"` + Stat dmsCommonV1.Stat `json:"stat"` // role desc Desc string `json:"desc"` // op permissions - OpPermissions []UidWithName `json:"op_permissions"` + OpPermissions []ListRoleOpPermission `json:"op_permissions"` +} + +type ListRoleOpPermission struct { + Uid string `json:"uid"` + Name string `json:"name"` + Module string `json:"module"` } // swagger:model ListRoleReply type ListRoleReply struct { // List role reply - Payload struct { - Roles []*ListRole `json:"roles"` - Total int64 `json:"total"` - } `json:"payload"` + Data []*ListRole `json:"data"` + Total int64 `json:"total_nums"` // Generic reply base.GenericResp @@ -123,15 +129,11 @@ type UpdateRole struct { OpPermissionUids *[]string `json:"op_permission_uids" validate:"required"` } -// swagger:parameters UpdateRole +// swagger:model type UpdateRoleReq struct { - // Role uid - // Required: true - // in:path - RoleUid string `param:"role_uid" json:"role_uid" validate:"required"` - // Update a role - // in:body - Role *UpdateRole `json:"role" validate:"required"` + // swagger:ignore + RoleUid string `param:"role_uid" json:"role_uid" validate:"required"` + Role *UpdateRole `json:"role" validate:"required"` } func (u *UpdateRoleReq) String() string { diff --git a/api/dms/service/v1/session.go b/api/dms/service/v1/session.go index 73f1a2230..975ecaad6 100644 --- a/api/dms/service/v1/session.go +++ b/api/dms/service/v1/session.go @@ -1,6 +1,6 @@ package v1 -import base "github.com/actiontech/dms/api/base/v1" +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" // Use this struct to add a new session type AddSession struct { @@ -10,24 +10,36 @@ type AddSession struct { // User password // Required: true Password string `json:"password" example:"admin" description:"password" validate:"required"` + // VerifyCode + VerifyCode *string `json:"verify_code" example:"1111" description:"verify_code"` } -// swagger:parameters AddSession +// swagger:model type AddSessionReq struct { - // Add a new session - // in:body Session *AddSession `json:"session" validate:"required"` } // swagger:model AddSessionReply type AddSessionReply struct { // Add user reply - Payload struct { - // User UID - UserUid string `json:"user_uid"` + Data struct { // Session token Token string `json:"token"` - } `json:"payload"` + // Message + Message string `json:"message"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:model DelSessionReply +type DelSessionReply struct { + // Del session reply + Data struct { + // Session token + Location string `json:"location"` + } `json:"data"` // Generic reply base.GenericResp @@ -41,12 +53,12 @@ type GetUserBySessionReq struct { // swagger:model GetUserBySessionReply type GetUserBySessionReply struct { // Get user reply - Payload struct { + Data struct { // User UID UserUid string `json:"user_uid"` // User name Name string `json:"name"` - } `json:"payload"` + } `json:"data"` // Generic reply base.GenericResp diff --git a/api/dms/service/v1/user.go b/api/dms/service/v1/user.go index ec2ce888d..eb1d5aee6 100644 --- a/api/dms/service/v1/user.go +++ b/api/dms/service/v1/user.go @@ -3,11 +3,12 @@ package v1 import ( "fmt" - base "github.com/actiontech/dms/api/base/v1" + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" ) // A user type User struct { + UID string `json:"uid"` // user name // Required: true Name string `json:"name" validate:"required"` @@ -25,12 +26,14 @@ type User struct { UserGroupUids []string `json:"user_group_uids"` // user op permission uid OpPermissionUids []string `json:"op_permission_uids"` + // 对接登录的参数 + ThirdPartyUserID string `json:"third_party_user_id"` + ThirdPartyUserInfo string `json:"third_party_user_info"` + UserAuthenticationType string `json:"user_authentication_type"` } -// swagger:parameters AddUser +// swagger:model type AddUserReq struct { - // Add new user - // in:body User *User `json:"user" validate:"required"` } @@ -44,10 +47,10 @@ func (u *AddUserReq) String() string { // swagger:model AddUserReply type AddUserReply struct { // Add user reply - Payload struct { + Data struct { // user UID Uid string `json:"uid"` - } `json:"payload"` + } `json:"data"` // Generic reply base.GenericResp @@ -57,7 +60,7 @@ func (u *AddUserReply) String() string { if u == nil { return "AddUserReply{nil}" } - return fmt.Sprintf("AddUserReply{Uid:%s}", u.Payload.Uid) + return fmt.Sprintf("AddUserReply{Uid:%s}", u.Data.Uid) } // swagger:parameters DelUser @@ -85,21 +88,25 @@ type UpdateUser struct { Phone *string `json:"phone"` // User wxid WxID *string `json:"wxid"` + // User language + Language *string `json:"language"` // User group uids - UserGroupUids *[]string `json:"user_group_uids" validate:"required"` + UserGroupUids *[]string `json:"user_group_uids"` // User operation permission uids OpPermissionUids *[]string `json:"op_permission_uids" validate:"required"` + // 对接登录的参数 + ThirdPartyUserID *string `json:"third_party_user_id"` + ThirdPartyUserInfo *string `json:"third_party_user_info"` + UserAuthenticationType *string `json:"user_authentication_type"` + // User system + System *UserSystem `json:"system"` } -// swagger:parameters UpdateUser +// swagger:model type UpdateUserReq struct { - // User uid - // Required: true - // in:path - UserUid string `param:"user_uid" json:"user_uid" validate:"required"` - // Update a user - // in:body - User *UpdateUser `json:"user" validate:"required"` + // swagger:ignore + UserUid string `param:"user_uid" json:"user_uid" validate:"required"` + User *UpdateUser `json:"user" validate:"required"` } func (u *UpdateUserReq) String() string { @@ -112,11 +119,47 @@ func (u *UpdateUserReq) String() string { return fmt.Sprintf("UpdateUserReq{Uid:%s}", u.UserUid) } +// swagger:model +type UpdateCurrentUserReq struct { + User *UpdateCurrentUser `json:"current_user" validate:"required"` +} + +func (u *UpdateCurrentUserReq) String() string { + if u == nil { + return "UpdateCurrentUserReq{nil}" + } + if u.User == nil { + return "UpdateCurrentUserReq{User:nil}" + } + return fmt.Sprintf("UpdateCurrentUserReq{Uid:%v}", u.User) +} + +type UpdateCurrentUser struct { + // User old password + OldPassword *string `json:"old_password"` + // User new password + Password *string `json:"password"` + // User email + Email *string `json:"email"` + // User phone + Phone *string `json:"phone"` + // User wxid + WxID *string `json:"wxid"` + // User language + Language *string `json:"language"` + // User two factor enabled + TwoFactorEnabled *bool `json:"two_factor_enabled"` + // User system + System *UserSystem `json:"system"` +} + type VerifyUserLoginReq struct { // user name UserName string `json:"user_name" validate:"required"` // user password Password string `json:"password" validate:"required"` + // VerifyCode + VerifyCode *string `json:"verify_code" description:"verify_code"` } func (u *VerifyUserLoginReq) String() string { @@ -126,20 +169,24 @@ func (u *VerifyUserLoginReq) String() string { return fmt.Sprintf("VerifyUserLoginReq{UserName:%s}", u.UserName) } +// swagger:model type VerifyUserLoginReply struct { - Payload struct { + base.GenericResp + Data struct { // If verify Successful, return empty string, otherwise return error message VerifyFailedMsg string `json:"verify_failed_msg"` // If verify Successful, return user uid - UserUid string `json:"user_uid"` - } `json:"payload"` + UserUid string `json:"user_uid"` + Phone string `json:"phone"` + TwoFactorEnabled bool `json:"two_factor_enabled"` + } `json:"data"` } func (u *VerifyUserLoginReply) String() string { if u == nil { return "VerifyUserLoginReply{nil}" } - return fmt.Sprintf("VerifyUserLoginReply{UserUid:%s}", u.Payload.UserUid) + return fmt.Sprintf("VerifyUserLoginReply{UserUid:%s}", u.Data.UserUid) } type AfterUserLoginReq struct { @@ -153,3 +200,11 @@ func (u *AfterUserLoginReq) String() string { } return fmt.Sprintf("AfterUserLoginReq{UserUid:%s}", u.UserUid) } + +// swagger:enum UserSystem +type UserSystem string + +const ( + UserSystemWorkbench UserSystem = "WORKBENCH" + UserSystemManagement UserSystem = "MANAGEMENT" +) diff --git a/api/dms/service/v1/user_group.go b/api/dms/service/v1/user_group.go index 822d2652a..d718ef47a 100644 --- a/api/dms/service/v1/user_group.go +++ b/api/dms/service/v1/user_group.go @@ -3,7 +3,8 @@ package v1 import ( "fmt" - base "github.com/actiontech/dms/api/base/v1" + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" ) // A user group @@ -17,10 +18,8 @@ type UserGroup struct { UserUids []string `json:"user_uids"` } -// swagger:parameters AddUserGroup +// swagger:model type AddUserGroupReq struct { - // Add new user group - // in:body UserGroup *UserGroup `json:"user_group" validate:"required"` } @@ -34,10 +33,10 @@ func (u *AddUserGroupReq) String() string { // swagger:model AddUserGroupReply type AddUserGroupReply struct { // Add user group reply - Payload struct { + Data struct { // user group UID Uid string `json:"uid"` - } `json:"payload"` + } `json:"data"` // Generic reply base.GenericResp @@ -47,7 +46,7 @@ func (u *AddUserGroupReply) String() string { if u == nil { return "AddUserGroupReply{nil}" } - return fmt.Sprintf("AddUserGroupReply{Uid:%s}", u.Payload.Uid) + return fmt.Sprintf("AddUserGroupReply{Uid:%s}", u.Data.Uid) } // swagger:parameters DelUserGroup @@ -97,7 +96,7 @@ type ListUserGroup struct { // user group description Desc string `json:"desc"` // user group stat - Stat Stat `json:"stat"` + Stat dmsCommonV1.Stat `json:"stat"` // users Users []UidWithName `json:"users"` } @@ -105,10 +104,8 @@ type ListUserGroup struct { // swagger:model ListUserGroupReply type ListUserGroupReply struct { // List user reply - Payload struct { - UserGroups []*ListUserGroup `json:"user_groups"` - Total int64 `json:"total"` - } `json:"payload"` + Data []*ListUserGroup `json:"data"` + Total int64 `json:"total_nums"` // Generic reply base.GenericResp @@ -123,15 +120,11 @@ type UpdateUserGroup struct { UserUids *[]string `json:"user_uids" validate:"required"` } -// swagger:parameters UpdateUserGroup +// swagger:model type UpdateUserGroupReq struct { - // UserGroup uid - // Required: true - // in:path - UserGroupUid string `param:"user_group_uid" json:"user_group_uid" validate:"required"` - // Update a user group - // in:body - UserGroup *UpdateUserGroup `json:"user_group" validate:"required"` + // swagger:ignore + UserGroupUid string `param:"user_group_uid" json:"user_group_uid" validate:"required"` + UserGroup *UpdateUserGroup `json:"user_group" validate:"required"` } func (u *UpdateUserGroupReq) String() string { diff --git a/api/dms/service/v2/db_service.go b/api/dms/service/v2/db_service.go new file mode 100644 index 000000000..f4d4d3442 --- /dev/null +++ b/api/dms/service/v2/db_service.go @@ -0,0 +1,280 @@ +package v2 + +import ( + "bytes" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/go-openapi/strfmt" +) + +// swagger:parameters ListGlobalDBServicesV2 +type ListGlobalDBServicesReq struct { + // the maximum count of db service to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of users to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy dmsCommonV1.DBServiceOrderByField `query:"order_by" json:"order_by"` + // the db service connection + // enum: ["connect_success","connect_failed"] + // in:query + FilterLastConnectionTestStatus *string `query:"filter_last_connection_test_status" json:"filter_last_connection_test_status" validate:"omitempty,oneof=connect_success connect_failed"` + // filter db services by environment tag + // in:query + FilterByEnvironmentTagUID string `query:"filter_by_environment_tag_uid" json:"filter_by_environment_tag_uid"` + // the db service host + // in:query + FilterByHost string `query:"filter_by_host" json:"filter_by_host"` + // the db service uid + // in:query + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` + // the db service name + // in:query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // the db service port + // in:query + FilterByPort string `query:"filter_by_port" json:"filter_by_port"` + // the db service db type + // in:query + FilterByDBType string `query:"filter_by_db_type" json:"filter_by_db_type"` + // the db service project id + // in:query + FilterByProjectUid string `query:"filter_by_project_uid" json:"filter_by_project_uid"` + // is masking + // in:query + FilterByIsEnableMasking *bool `query:"filter_by_is_enable_masking" json:"filter_by_is_enable_masking"` + // the db service fuzzy keyword + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` +} + +// swagger:model ImportDBServicesOfProjectsReqV2 +type ImportDBServicesOfProjectsReq struct { + DBServices []ImportDBService `json:"db_services" validate:"required"` +} + +// swagger:parameters ImportDBServicesOfOneProjectCheckV2 +type ImportDBServicesOfOneProjectCheckReq struct { + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // DBServices file. + // + // in: formData + // + // swagger:file + DBServicesFile *bytes.Buffer `json:"db_services_file"` +} + +// swagger:model ImportDBServicesCheckReplyV2 +type ImportDBServicesCheckReply struct { + // db services + Data []*ImportDBService `json:"data"` + // Generic reply + base.GenericResp +} + +// swagger:parameters ImportDBServicesOfProjectsCheckV2 +type ImportDBServicesOfProjectsCheckReq struct { + // DBServices file. + // + // in: formData + // + // swagger:file + DBServicesFile *bytes.Buffer `json:"db_services_file"` +} + +// swagger:model DBServiceV2 +type DBService struct { + // Service name + // Required: true + Name string `json:"name" validate:"required"` + // Service DB type + // Required: true + DBType string `json:"db_type" validate:"required"` + // DB Service Host + // Required: true + Host string `json:"host" validate:"required,ip_addr|uri|hostname|hostname_rfc1123"` + // DB Service port + // Required: true + Port string `json:"port" validate:"required"` + // DB Service admin user + // Required: true + User string `json:"user" validate:"required"` + // DB Service admin password + // Required: true + Password string `json:"password" validate:"required"` + // DB Service environment tag + // Required: true + EnvironmentTagUID string `json:"environment_tag_uid" validate:"required"` + // DB Service maintenance time + // empty value means that maintenance time is unlimited + // Required: true + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` + // DB Service Custom connection parameters + // Required: false + AdditionalParams []*dmsCommonV1.AdditionalParam `json:"additional_params"` + // Service description + Desc string `json:"desc"` + // SQLE config + SQLEConfig *dmsCommonV1.SQLEConfig `json:"sqle_config"` + // backup switch + // Required: false + EnableBackup bool `json:"enable_backup"` + // backup switch + // Required: false + BackupMaxRows *uint64 `json:"backup_max_rows,omitempty"` +} + +// swagger:model AddDBServiceReqV2 +type AddDBServiceReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DBService *DBService `json:"db_service" validate:"required"` +} + +// swagger:model UpdateDBServiceReqV2 +type UpdateDBServiceReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + // swagger:ignore + DBServiceUid string `param:"db_service_uid" json:"db_service_uid" validate:"required"` + DBService *UpdateDBService `json:"db_service" validate:"required"` +} + +// swagger:model UpdateDBServiceV2 +type UpdateDBService struct { + // Service DB type + // Required: true + DBType string `json:"db_type" validate:"required"` + // DB Service Host + // Required: true + Host string `json:"host" validate:"required,ip_addr|uri|hostname|hostname_rfc1123"` + // DB Service port + // Required: true + Port string `json:"port" validate:"required"` + // DB Service admin user + // Required: true + User string `json:"user" validate:"required"` + // DB Service admin password + Password *string `json:"password"` + // DB Service environment tag + // Required: true + EnvironmentTagUID string `json:"environment_tag_uid" validate:"required"` + // DB Service maintenance time + // Required: true + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` + // DB Service Custom connection parameters + // Required: false + AdditionalParams []*dmsCommonV1.AdditionalParam `json:"additional_params"` + // Service description + Desc *string `json:"desc"` + // SQLE config + SQLEConfig *dmsCommonV1.SQLEConfig `json:"sqle_config"` + // backup switch + // Required: false + EnableBackup bool `json:"enable_backup"` + // backup switch + // Required: false + BackupMaxRows *uint64 `json:"backup_max_rows,omitempty"` +} + +// swagger:model ImportDBServicesOfOneProjectReqV2 +type ImportDBServicesOfOneProjectReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + DBServices []ImportDBService `json:"db_services" validate:"required"` +} + +// swagger:model ImportDBServiceV2 +type ImportDBService struct { + // db service name + Name string `json:"name"` + // db service DB type + DBType string `json:"db_type"` + // db service host + Host string `json:"host"` + // db service port + Port string `json:"port"` + // db service admin user + User string `json:"user"` + // db service admin encrypted password + Password string `json:"password"` + // DB Service environment tag uid + // Required: true + EnvironmentTagName string `json:"environment_tag_name"` + // DB Service maintenance time + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` + // DB desc + Desc string `json:"desc"` + // DB source + Source string `json:"source"` + // DB project uid + ProjectUID string `json:"project_uid"` + // sqle config + SQLEConfig *dmsCommonV1.SQLEConfig `json:"sqle_config"` + // DB Service Custom connection parameters + AdditionalParams []*dmsCommonV1.AdditionalParam `json:"additional_params"` +} + +// swagger:model ListGlobalDBServicesReplyV2 +type ListGlobalDBServicesReply struct { + // List global db service reply + Data []*ListGlobalDBService `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +// swagger:model ListGlobalDBServiceV2 +type ListGlobalDBService struct { + // db service uid + DBServiceUid string `json:"uid"` + // db service name + Name string `json:"name"` + // db service DB type + DBType string `json:"db_type"` + // db service host + Host string `json:"host"` + // db service port + Port string `json:"port"` + // DB Service environment tag + // Required: true + EnvironmentTag *dmsCommonV1.EnvironmentTag `json:"environment_tag"` + // DB Service maintenance time + MaintenanceTimes []*dmsCommonV1.MaintenanceTime `json:"maintenance_times"` + // DB desc + Desc string `json:"desc"` + // DB source + Source string `json:"source"` + // DB project uid + ProjectUID string `json:"project_uid"` + // db service project_name + ProjectName string `json:"project_name"` + // is enable audit + IsEnableAudit bool `json:"is_enable_audit"` + // is enabled workflow exec + WorkflowExecEnabled bool `json:"workflow_exec_enabled"` + // is enable masking + IsEnableMasking bool `json:"is_enable_masking"` + // db service unfinished workflow num + UnfinishedWorkflowNum int64 `json:"unfinished_workflow_num"` + // backup switch + EnableBackup bool `json:"enable_backup"` + // backup switch + // Required: false + BackupMaxRows uint64 `json:"backup_max_rows"` + // DB connection test time + LastConnectionTestTime strfmt.DateTime `json:"last_connection_test_time"` + // DB connect test status + LastConnectionTestStatus dmsCommonV1.LastConnectionTestStatus `json:"last_connection_test_status"` + // DB connect test error message + LastConnectionTestErrorMessage string `json:"last_connection_test_error_message,omitempty"` +} diff --git a/api/dms/service/v2/project.go b/api/dms/service/v2/project.go new file mode 100644 index 000000000..70b885807 --- /dev/null +++ b/api/dms/service/v2/project.go @@ -0,0 +1,98 @@ +package v2 + +import ( + "bytes" + + v1 "github.com/actiontech/dms/api/dms/service/v1" + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +// swagger:model ProjectV2 +type Project struct { + // project name + Name string `json:"name"` + // project desc + Desc string `json:"desc"` + // project business tag + BusinessTag *v1.BusinessTag `json:"business_tag"` + // project priority + ProjectPriority dmsCommonV1.ProjectPriority `json:"project_priority" enums:"high,medium,low"` +} + +// swagger:model AddProjectReqV2 +type AddProjectReq struct { + Project *Project `json:"project" validate:"required"` +} + +// swagger:model AddProjectReplyV2 +type AddProjectReply struct { + // Add Project reply + Data struct { + // Project UID + Uid string `json:"uid"` + } `json:"data"` + + // Generic reply + base.GenericResp +} + +// swagger:model UpdateProjectReqV2 +type UpdateProjectReq struct { + // swagger:ignore + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` + Project *UpdateProject `json:"project" validate:"required"` +} + +// swagger:model UpdateProjectV2 +type UpdateProject struct { + // Project desc + Desc *string `json:"desc"` + // project business tag + BusinessTag *v1.BusinessTag `json:"business_tag"` + // project priority + ProjectPriority *dmsCommonV1.ProjectPriority `json:"project_priority" enums:"high,medium,low"` +} + +// swagger:model ImportProjectsReqV2 +type ImportProjectsReq struct { + Projects []*ImportProjects `json:"projects" validate:"required"` +} + +// swagger:model ImportProjectsV2 +type ImportProjects struct { + // Project name + Name string `json:"name" validate:"required"` + // Project desc + Desc string `json:"desc"` + // project business tag + BusinessTag *v1.BusinessTag `json:"business_tag"` +} + +// swagger:parameters PreviewImportProjectsV2 +type PreviewImportProjectsRep struct { + // projects file. + // + // in: formData + // + // swagger:file + ProjectsFile *bytes.Buffer `json:"projects_file"` +} + +// swagger:model PreviewImportProjectsReplyV2 +type PreviewImportProjectsReply struct { + // Generic reply + base.GenericResp + // list preview import projects + Data []*PreviewImportProjects `json:"data"` +} + +// swagger:model PreviewImportProjectsV2 +type PreviewImportProjects struct { + // Project name + Name string `json:"name"` + // Project desc + Desc string `json:"desc"` + // project business tag + BusinessTag *v1.BusinessTag `json:"business_tag"` +} diff --git a/api/doc.go b/api/doc.go new file mode 100644 index 000000000..027d932e1 --- /dev/null +++ b/api/doc.go @@ -0,0 +1,72 @@ +package api + +import ( + _ "embed" + "fmt" + "path" + "sync" + + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" + "github.com/swaggo/swag" +) + +var ( + swaggerMu = new(sync.RWMutex) + swaggerList = make(map[SwaggerType]*SwaggerDoc) + + //go:embed swagger.yaml + dmsSwagYaml []byte +) + +func init() { + RegisterSwaggerDoc(DmsSwaggerTykeKey, dmsSwagYaml) +} + +type SwaggerType string + +const ( + SqleSwaggerTypeKey SwaggerType = _const.SqleComponentName + DmsSwaggerTykeKey SwaggerType = _const.DmsComponentName +) + +type SwaggerDoc struct { + file []byte +} + +func (sd *SwaggerDoc) ReadDoc() string { + return string(sd.file) +} + +// RegisterSwaggerDoc registers a Swagger document and adds a config function +func RegisterSwaggerDoc(swaggerType SwaggerType, file []byte) { + swaggerMu.Lock() + defer swaggerMu.Unlock() + + swaggerList[swaggerType] = &SwaggerDoc{file: file} + + instanceName := swaggerType.GetUrlPath() + + swag.Register(instanceName, &SwaggerDoc{file: file}) +} + +// GetSwaggerDoc returns the Swagger document by the given type +func GetSwaggerDoc(swaggerType SwaggerType) (*SwaggerDoc, bool) { + swaggerMu.RLock() + defer swaggerMu.RUnlock() + + doc, ok := swaggerList[swaggerType] + + return doc, ok +} + +// GetAllSwaggerDocs returns all the registered Swagger documents +func GetAllSwaggerDocs() map[SwaggerType]*SwaggerDoc { + swaggerMu.RLock() + defer swaggerMu.RUnlock() + + return swaggerList +} + +func (t SwaggerType) GetUrlPath() string { + return path.Join(fmt.Sprintf("%v", t), "doc.yaml") +} diff --git a/api/swagger.json b/api/swagger.json index 9805b8a08..48ad3c5a9 100644 --- a/api/swagger.json +++ b/api/swagger.json @@ -17,10 +17,97 @@ }, "basePath": "/", "paths": { + "/v1/dms/basic_info": { + "get": { + "tags": [ + "BasicInfo" + ], + "summary": "get basic info.", + "operationId": "GetBasicInfo", + "responses": { + "200": { + "description": "GetBasicInfoReply", + "schema": { + "$ref": "#/definitions/GetBasicInfoReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/company_notice": { + "get": { + "description": "get company notice info", + "tags": [ + "CompanyNotice" + ], + "operationId": "GetCompanyNotice", + "parameters": [ + { + "type": "boolean", + "x-go-name": "IncludeLatestOutsidePeriod", + "description": "when true, return the latest notice regardless of display window (for admin edit)", + "name": "include_latest_outside_period", + "in": "query" + } + ], + "responses": { + "200": { + "description": "GetCompanyNoticeReply", + "schema": { + "$ref": "#/definitions/GetCompanyNoticeReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "patch": { + "description": "update company notice info", + "tags": [ + "CompanyNotice" + ], + "operationId": "UpdateCompanyNotice", + "parameters": [ + { + "description": "Update a companynotice", + "name": "company_notice", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateCompanyNoticeReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, "/v1/dms/configurations/feishu": { "get": { "tags": [ - "dms" + "Configuration" ], "summary": "get feishu configuration.", "operationId": "GetFeishuConfiguration", @@ -41,17 +128,18 @@ }, "patch": { "tags": [ - "dms" + "Configuration" ], "summary": "update feishu configuration.", "operationId": "UpdateFeishuConfiguration", "parameters": [ { - "x-go-name": "UpdateFeishuConfiguration", "description": "update feishu configuration", "name": "update_feishu_configuration", "in": "body", - "schema": {} + "schema": { + "$ref": "#/definitions/UpdateFeishuConfigurationReq" + } } ], "responses": { @@ -73,17 +161,19 @@ "/v1/dms/configurations/feishu/test": { "post": { "tags": [ - "dms" + "Configuration" ], "summary": "test feishu configuration.", "operationId": "TestFeishuConfiguration", "parameters": [ { - "x-go-name": "TestFeishuConfiguration", "description": "test feishu configuration", "name": "test_feishu_configuration", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/TestFeishuConfigurationReq" + } } ], "responses": { @@ -105,7 +195,7 @@ "/v1/dms/configurations/ldap": { "get": { "tags": [ - "dms" + "Configuration" ], "summary": "Get ldap configuration.", "operationId": "GetLDAPConfiguration", @@ -126,17 +216,19 @@ }, "patch": { "tags": [ - "dms" + "Configuration" ], "summary": "Update ldap configuration.", "operationId": "UpdateLDAPConfiguration", "parameters": [ { - "x-go-name": "LDAPConfiguration", "description": "update ldap configuration", "name": "ldap", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/UpdateLDAPConfigurationReq" + } } ], "responses": { @@ -155,18 +247,18 @@ } } }, - "/v1/dms/configurations/oauth2": { + "/v1/dms/configurations/license": { "get": { "tags": [ - "dms" + "Configuration" ], - "summary": "Get Oauth2 configuration.", - "operationId": "GetOauth2Configuration", + "summary": "get license.", + "operationId": "GetLicense", "responses": { "200": { - "description": "GetOauth2ConfigurationResDataReply", + "description": "GetLicenseReply", "schema": { - "$ref": "#/definitions/GetOauth2ConfigurationResDataReply" + "$ref": "#/definitions/GetLicenseReply" } }, "default": { @@ -177,19 +269,22 @@ } } }, - "patch": { + "post": { + "consumes": [ + "multipart/form-data" + ], "tags": [ - "dms" + "Configuration" ], - "summary": "Update Oauth2 configuration..", - "operationId": "UpdateOauth2Configuration", + "summary": "import license.", + "operationId": "SetLicense", "parameters": [ { - "x-go-name": "Oauth2Configuration", - "description": "update oauth2 configuration", - "name": "oauth2", - "in": "body", - "schema": {} + "type": "file", + "x-go-name": "LicenseFile", + "description": "license file.", + "name": "license_file", + "in": "formData" } ], "responses": { @@ -208,18 +303,30 @@ } } }, - "/v1/dms/configurations/smtp": { - "get": { + "/v1/dms/configurations/license/check": { + "post": { + "consumes": [ + "multipart/form-data" + ], "tags": [ - "dms" + "Configuration" + ], + "summary": "notify message.", + "operationId": "CheckLicense", + "parameters": [ + { + "type": "file", + "x-go-name": "LicenseFile", + "description": "license file.", + "name": "license_file", + "in": "formData" + } ], - "summary": "get smtp configuration.", - "operationId": "GetSMTPConfiguration", "responses": { "200": { - "description": "GetSMTPConfigurationReply", + "description": "CheckLicenseReply", "schema": { - "$ref": "#/definitions/GetSMTPConfigurationReply" + "$ref": "#/definitions/CheckLicenseReply" } }, "default": { @@ -229,28 +336,41 @@ } } } - }, - "patch": { + } + }, + "/v1/dms/configurations/license/info": { + "get": { "tags": [ - "dms" - ], - "summary": "Get smtp configuration.", - "operationId": "UpdateSMTPConfiguration", - "parameters": [ - { - "x-go-name": "UpdateSMTPConfiguration", - "description": "update smtp configuration", - "name": "smtp_configuration", - "in": "body", - "schema": {} - } + "Configuration" ], + "summary": "get generate license info.", + "operationId": "GetLicenseInfo", "responses": { "200": { + "$ref": "#/responses/GetLicenseInfoReply" + }, + "default": { "description": "GenericResp", "schema": { "$ref": "#/definitions/GenericResp" } + } + } + } + }, + "/v1/dms/configurations/license/usage": { + "get": { + "tags": [ + "Configuration" + ], + "summary": "get license usage.", + "operationId": "GetLicenseUsage", + "responses": { + "200": { + "description": "GetLicenseUsageReply", + "schema": { + "$ref": "#/definitions/GetLicenseUsageReply" + } }, "default": { "description": "GenericResp", @@ -261,27 +381,29 @@ } } }, - "/v1/dms/configurations/smtp/test": { - "post": { + "/v1/dms/configurations/login": { + "patch": { "tags": [ - "dms" + "Configuration" ], - "summary": "test smtp configuration.", - "operationId": "TestSMTPConfiguration", + "summary": "Update login configuration.", + "operationId": "UpdateLoginConfiguration", "parameters": [ { - "x-go-name": "TestSMTPConfiguration", - "description": "test smtp configuration", - "name": "test_smtp_configuration", + "description": "update login configuration", + "name": "login", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/UpdateLoginConfigurationReq" + } } ], "responses": { "200": { - "description": "TestSMTPConfigurationReply", + "description": "GenericResp", "schema": { - "$ref": "#/definitions/TestSMTPConfigurationReply" + "$ref": "#/definitions/GenericResp" } }, "default": { @@ -293,18 +415,18 @@ } } }, - "/v1/dms/configurations/sql_query": { + "/v1/dms/configurations/login/tips": { "get": { "tags": [ - "cloudbeaver" + "Configuration" ], - "summary": "get sql_query configuration.", - "operationId": "GetSQLQueryConfiguration", + "summary": "get login configuration.", + "operationId": "GetLoginTips", "responses": { "200": { - "description": "GetSQLQueryConfigurationReply", + "description": "GetLoginTipsReply", "schema": { - "$ref": "#/definitions/GetSQLQueryConfigurationReply" + "$ref": "#/definitions/GetLoginTipsReply" } }, "default": { @@ -316,18 +438,18 @@ } } }, - "/v1/dms/configurations/webhook": { + "/v1/dms/configurations/oauth2": { "get": { "tags": [ - "dms" + "Configuration" ], - "summary": "get webhook configuration.", - "operationId": "GetWebHookConfiguration", + "summary": "Get Oauth2 configuration.", + "operationId": "GetOauth2Configuration", "responses": { "200": { - "description": "GetWebHookConfigurationReply", + "description": "GetOauth2ConfigurationResDataReply", "schema": { - "$ref": "#/definitions/GetWebHookConfigurationReply" + "$ref": "#/definitions/GetOauth2ConfigurationResDataReply" } }, "default": { @@ -340,17 +462,19 @@ }, "patch": { "tags": [ - "dms" + "Configuration" ], - "summary": "update webhook configuration.", - "operationId": "UpdateWebHookConfiguration", + "summary": "Update Oauth2 configuration..", + "operationId": "UpdateOauth2Configuration", "parameters": [ { - "x-go-name": "UpdateWebHookConfiguration", - "description": "test webhook configuration", - "name": "webhook_config", + "description": "update oauth2 configuration", + "name": "oauth2", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/Oauth2ConfigurationReq" + } } ], "responses": { @@ -369,18 +493,18 @@ } } }, - "/v1/dms/configurations/webhook/test": { - "post": { + "/v1/dms/configurations/sms": { + "get": { "tags": [ - "dms" + "Configuration" ], - "summary": "test webhook configuration.", - "operationId": "TestWebHookConfiguration", + "summary": "get sms configuration.", + "operationId": "GetSmsConfiguration", "responses": { "200": { - "description": "TestWebHookConfigurationReply", + "description": "GetSmsConfigurationReply", "schema": { - "$ref": "#/definitions/TestWebHookConfigurationReply" + "$ref": "#/definitions/GetSmsConfigurationReply" } }, "default": { @@ -390,20 +514,29 @@ } } } - } - }, - "/v1/dms/configurations/wechat": { - "get": { + }, + "patch": { "tags": [ - "dms" + "Configuration" + ], + "summary": "update sms configuration.", + "operationId": "UpdateSmsConfiguration", + "parameters": [ + { + "description": "update sms configuration", + "name": "update_sms_configuration", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateSmsConfigurationReq" + } + } ], - "summary": "get wechat configuration.", - "operationId": "GetWeChatConfiguration", "responses": { "200": { - "description": "GetWeChatConfigurationReply", + "description": "GenericResp", "schema": { - "$ref": "#/definitions/GetWeChatConfigurationReply" + "$ref": "#/definitions/GenericResp" } }, "default": { @@ -413,27 +546,31 @@ } } } - }, - "patch": { + } + }, + "/v1/dms/configurations/sms/send_code": { + "post": { "tags": [ - "dms" + "SMS" ], - "summary": "update wechat configuration.", - "operationId": "UpdateWeChatConfiguration", + "summary": "send sms code.", + "operationId": "SendSmsCode", "parameters": [ { - "x-go-name": "UpdateWeChatConfiguration", - "description": "update wechat configuration", - "name": "update_wechat_configuration", + "description": "user name", + "name": "username", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/SendSmsCodeReq" + } } ], "responses": { "200": { - "description": "GenericResp", + "description": "SendSmsCodeReply", "schema": { - "$ref": "#/definitions/GenericResp" + "$ref": "#/definitions/SendSmsCodeReply" } }, "default": { @@ -445,27 +582,29 @@ } } }, - "/v1/dms/configurations/wechat/test": { + "/v1/dms/configurations/sms/test": { "post": { "tags": [ - "dms" + "Configuration" ], - "summary": "test wechat configuration.", - "operationId": "TestWeChatConfiguration", + "summary": "test smtp configuration.", + "operationId": "TestSmsConfiguration", "parameters": [ { - "x-go-name": "TestWeChatConfiguration", - "description": "test wechat configuration", - "name": "test_wechat_configuration", + "description": "test sms configuration", + "name": "test_sms_configuration", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/TestSmsConfigurationReq" + } } ], "responses": { "200": { - "description": "TestWeChatConfigurationReply", + "description": "TestSmsConfigurationReply", "schema": { - "$ref": "#/definitions/TestWeChatConfigurationReply" + "$ref": "#/definitions/TestSmsConfigurationReply" } }, "default": { @@ -477,85 +616,61 @@ } } }, - "/v1/dms/db_services": { - "get": { + "/v1/dms/configurations/sms/verify_code": { + "post": { "tags": [ - "dms" + "SMS" ], - "summary": "List db service.", - "operationId": "ListDBServices", + "summary": "verify sms code.", + "operationId": "VerifySmsCode", "parameters": [ { - "type": "integer", - "format": "uint32", - "x-go-name": "PageSize", - "description": "the maximum count of db service to be returned", - "name": "page_size", - "in": "query", - "required": true - }, - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageIndex", - "description": "the offset of users to be returned, default is 0", - "name": "page_index", - "in": "query" - }, - { - "x-go-name": "OrderBy", - "description": "Multiple of [\"name\"], default is [\"name\"]", - "name": "order_by", - "in": "query" + "description": "verify sms code", + "name": "code", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/VerifySmsCodeReq" + } }, { - "type": "string", - "x-go-name": "FilterByBusiness", - "description": "the db service business name", - "name": "filter_by_business", - "in": "query" + "description": "user name", + "name": "username", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/VerifySmsCodeReq" + } + } + ], + "responses": { + "200": { + "description": "VerifySmsCodeReply", + "schema": { + "$ref": "#/definitions/VerifySmsCodeReply" + } }, - { - "type": "string", - "x-go-name": "FilterByHost", - "description": "the db service host", - "name": "filter_by_host", - "in": "query" - }, - { - "type": "string", - "x-go-name": "FilterByUID", - "description": "the db service uid", - "name": "filter_by_uid", - "in": "query" - }, - { - "type": "string", - "x-go-name": "FilterByPort", - "description": "the db service port", - "name": "filter_by_port", - "in": "query" - }, - { - "type": "string", - "x-go-name": "FilterByDBType", - "description": "the db service db type", - "name": "filter_by_db_type", - "in": "query" - }, - { - "type": "string", - "x-go-name": "FilterByNamespaceUid", - "description": "filter by db service namespace uid\nonly the sys user can use an empty namespace value, which means lookup from all namespaces", - "name": "filter_by_namespace_uid", - "in": "query" + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } } + } + } + }, + "/v1/dms/configurations/smtp": { + "get": { + "tags": [ + "Configuration" ], + "summary": "get smtp configuration.", + "operationId": "GetSMTPConfiguration", "responses": { "200": { - "description": "ListDBServiceReply", + "description": "GetSMTPConfigurationReply", "schema": { - "$ref": "#/definitions/ListDBServiceReply" + "$ref": "#/definitions/GetSMTPConfigurationReply" } }, "default": { @@ -566,26 +681,28 @@ } } }, - "post": { + "patch": { "tags": [ - "dms" + "Configuration" ], - "summary": "Add DB Service.", - "operationId": "AddDBService", + "summary": "Update smtp configuration.", + "operationId": "UpdateSMTPConfiguration", "parameters": [ { - "x-go-name": "DBService", - "description": "Add new db service", - "name": "db_service", + "description": "update smtp configuration", + "name": "smtp_configuration", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/UpdateSMTPConfigurationReq" + } } ], "responses": { "200": { - "description": "AddDBServiceReply", + "description": "GenericResp", "schema": { - "$ref": "#/definitions/AddDBServiceReply" + "$ref": "#/definitions/GenericResp" } }, "default": { @@ -597,27 +714,29 @@ } } }, - "/v1/dms/db_services/connect": { + "/v1/dms/configurations/smtp/test": { "post": { "tags": [ - "dms" + "Configuration" ], - "summary": "check if the db_service is connectable.", - "operationId": "CheckDBServiceIsConnectable", + "summary": "test smtp configuration.", + "operationId": "TestSMTPConfiguration", "parameters": [ { - "x-go-name": "DBService", - "description": "check db_service is connectable", - "name": "db_service", + "description": "test smtp configuration", + "name": "test_smtp_configuration", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/TestSMTPConfigurationReq" + } } ], "responses": { "200": { - "description": "CheckDBServiceIsConnectableReply", + "description": "TestSMTPConfigurationReply", "schema": { - "$ref": "#/definitions/CheckDBServiceIsConnectableReply" + "$ref": "#/definitions/TestSMTPConfigurationReply" } }, "default": { @@ -629,35 +748,41 @@ } } }, - "/v1/dms/db_services/{db_service_uid}": { - "put": { + "/v1/dms/configurations/sql_query": { + "get": { "tags": [ - "dms" + "CloudBeaver" ], - "summary": "update a DB Service.", - "operationId": "UpdateDBService", - "parameters": [ - { - "type": "string", - "x-go-name": "DBServiceUid", - "description": "db_service_uid", - "name": "db_service_uid", - "in": "path", - "required": true + "summary": "get sql_query configuration.", + "operationId": "GetSQLQueryConfiguration", + "responses": { + "200": { + "description": "GetSQLQueryConfigurationReply", + "schema": { + "$ref": "#/definitions/GetSQLQueryConfigurationReply" + } }, - { - "x-go-name": "DBService", - "description": "Update a DB service", - "name": "db_service", - "in": "body", - "schema": {} + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } } + } + } + }, + "/v1/dms/configurations/system_variables": { + "get": { + "description": "获取系统变量配置", + "tags": [ + "Configuration" ], + "operationId": "GetSystemVariables", "responses": { "200": { - "description": "GenericResp", + "description": "GetSystemVariablesReply", "schema": { - "$ref": "#/definitions/GenericResp" + "$ref": "#/definitions/GetSystemVariablesReply" } }, "default": { @@ -668,20 +793,21 @@ } } }, - "delete": { + "patch": { + "description": "更新系统变量配置", "tags": [ - "dms" + "Configuration" ], - "summary": "Delete a DB Service.", - "operationId": "DelDBService", + "operationId": "UpdateSystemVariables", "parameters": [ { - "type": "string", - "x-go-name": "DBServiceUid", - "description": "db service uid", - "name": "db_service_uid", - "in": "path", - "required": true + "description": "更新系统变量配置", + "name": "system_variables", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateSystemVariablesReqV1" + } } ], "responses": { @@ -700,58 +826,18 @@ } } }, - "/v1/dms/members": { + "/v1/dms/configurations/webhook": { "get": { "tags": [ - "dms" - ], - "summary": "List member, for front page.", - "operationId": "ListMembers", - "parameters": [ - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageSize", - "description": "the maximum count of member to be returned", - "name": "page_size", - "in": "query", - "required": true - }, - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageIndex", - "description": "the offset of members to be returned, default is 0", - "name": "page_index", - "in": "query" - }, - { - "x-go-name": "OrderBy", - "description": "Multiple of [\"name\"], default is [\"name\"]", - "name": "order_by", - "in": "query" - }, - { - "type": "string", - "x-go-name": "FilterByUserUid", - "description": "filter the member user uid", - "name": "filter_by_user_uid", - "in": "query" - }, - { - "type": "string", - "x-go-name": "NamespaceUid", - "description": "the member namespace uid", - "name": "namespace_uid", - "in": "query", - "required": true - } + "Configuration" ], + "summary": "get webhook configuration.", + "operationId": "GetWebHookConfiguration", "responses": { "200": { - "description": "ListMemberReply", + "description": "GetWebHookConfigurationReply", "schema": { - "$ref": "#/definitions/ListMemberReply" + "$ref": "#/definitions/GetWebHookConfigurationReply" } }, "default": { @@ -762,26 +848,27 @@ } } }, - "post": { + "patch": { "tags": [ - "dms" + "Configuration" ], - "summary": "Add member.", - "operationId": "AddMember", + "summary": "update webhook configuration.", + "operationId": "UpdateWebHookConfiguration", "parameters": [ { - "x-go-name": "Member", - "description": "Add new member", - "name": "member", + "description": "webhook configuration", + "name": "webhook_config", "in": "body", - "schema": {} + "schema": { + "$ref": "#/definitions/UpdateWebHookConfigurationReq" + } } ], "responses": { "200": { - "description": "AddMemberReply", + "description": "GenericResp", "schema": { - "$ref": "#/definitions/AddMemberReply" + "$ref": "#/definitions/GenericResp" } }, "default": { @@ -793,44 +880,41 @@ } } }, - "/v1/dms/members/internal": { - "get": { + "/v1/dms/configurations/webhook/test": { + "post": { "tags": [ - "dms" + "Configuration" ], - "summary": "List members, for internal backend service.", - "operationId": "ListMembersForInternal", - "parameters": [ - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageSize", - "description": "the maximum count of member to be returned", - "name": "page_size", - "in": "query", - "required": true - }, - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageIndex", - "description": "the offset of members to be returned, default is 0", - "name": "page_index", - "in": "query" + "summary": "test webhook configuration.", + "operationId": "TestWebHookConfiguration", + "responses": { + "200": { + "description": "TestWebHookConfigurationReply", + "schema": { + "$ref": "#/definitions/TestWebHookConfigurationReply" + } }, - { - "type": "string", - "x-go-name": "NamespaceUid", - "description": "the member namespace uid", - "name": "namespace_uid", - "in": "query" + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } } + } + } + }, + "/v1/dms/configurations/wechat": { + "get": { + "tags": [ + "Configuration" ], + "summary": "get wechat configuration.", + "operationId": "GetWeChatConfiguration", "responses": { "200": { - "description": "ListMembersForInternalReply", + "description": "GetWeChatConfigurationReply", "schema": { - "$ref": "#/definitions/ListMembersForInternalReply" + "$ref": "#/definitions/GetWeChatConfigurationReply" } }, "default": { @@ -840,30 +924,21 @@ } } } - } - }, - "/v1/dms/members/{member_uid}": { - "put": { + }, + "patch": { "tags": [ - "dms" + "Configuration" ], - "summary": "Update a member.", - "operationId": "UpdateMember", + "summary": "update wechat configuration.", + "operationId": "UpdateWeChatConfiguration", "parameters": [ { - "type": "string", - "x-go-name": "MemberUid", - "description": "Member uid", - "name": "member_uid", - "in": "path", - "required": true - }, - { - "x-go-name": "Member", - "description": "Update a member", - "name": "member", + "description": "update wechat configuration", + "name": "update_wechat_configuration", "in": "body", - "schema": {} + "schema": { + "$ref": "#/definitions/UpdateWeChatConfigurationReq" + } } ], "responses": { @@ -880,28 +955,30 @@ } } } - }, - "delete": { + } + }, + "/v1/dms/configurations/wechat/test": { + "post": { "tags": [ - "dms" + "Configuration" ], - "summary": "Delete a member.", - "operationId": "DelMember", + "summary": "test wechat configuration.", + "operationId": "TestWeChatConfiguration", "parameters": [ { - "type": "string", - "x-go-name": "MemberUid", - "description": "member uid", - "name": "member_uid", - "in": "path", - "required": true + "description": "test wechat configuration", + "name": "test_wechat_configuration", + "in": "body", + "schema": { + "$ref": "#/definitions/TestWeChatConfigurationReq" + } } ], "responses": { "200": { - "description": "GenericResp", + "description": "TestWeChatConfigurationReply", "schema": { - "$ref": "#/definitions/GenericResp" + "$ref": "#/definitions/TestWeChatConfigurationReply" } }, "default": { @@ -913,57 +990,41 @@ } } }, - "/v1/dms/namespaces": { + "/v1/dms/dashboard/data_export_workflows": { "get": { "tags": [ - "dms" + "DataExportWorkflows" ], - "summary": "List namespaces.", - "operationId": "ListNamespaces", - "parameters": [ - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageSize", - "description": "the maximum count of namespace to be returned", - "name": "page_size", - "in": "query", - "required": true - }, - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageIndex", - "description": "the offset of namespaces to be returned, default is 0", - "name": "page_index", - "in": "query" - }, - { - "x-go-name": "OrderBy", - "description": "Multiple of [\"name\"], default is [\"name\"]", - "name": "order_by", - "in": "query" - }, - { - "type": "string", - "x-go-name": "FilterByName", - "description": "filter the namespace name", - "name": "filter_by_name", - "in": "query" + "summary": "Get global data export workflows.", + "operationId": "GetGlobalDataExportWorkflows", + "responses": { + "200": { + "description": "GetGlobalDataExportWorkflowsReply", + "schema": { + "$ref": "#/definitions/GetGlobalDataExportWorkflowsReply" + } }, - { - "type": "string", - "x-go-name": "FilterByUID", - "description": "filter the namespace UID", - "name": "filter_by_uid", - "in": "query" + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } } + } + } + }, + "/v1/dms/db_service_sync_tasks": { + "get": { + "tags": [ + "DBServiceSyncTask" ], + "summary": "List database synchronization tasks.", + "operationId": "ListDBServiceSyncTasks", "responses": { "200": { - "description": "ListNamespaceReply", + "description": "ListDBServiceSyncTasksReply", "schema": { - "$ref": "#/definitions/ListNamespaceReply" + "$ref": "#/definitions/ListDBServiceSyncTasksReply" } }, "default": { @@ -976,24 +1037,26 @@ }, "post": { "tags": [ - "dms" + "DBServiceSyncTask" ], - "summary": "Add namespaces.", - "operationId": "AddNamespace", + "summary": "Add database synchronization task.", + "operationId": "AddDBServiceSyncTask", "parameters": [ { - "x-go-name": "Namespace", - "description": "Add new Namespace", - "name": "namespace", + "description": "Add new db service sync task", + "name": "db_service_sync_task", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/AddDBServiceSyncTaskReq" + } } ], "responses": { "200": { - "description": "AddNamespaceReply", + "description": "AddDBServiceReply", "schema": { - "$ref": "#/definitions/AddNamespaceReply" + "$ref": "#/definitions/AddDBServiceReply" } }, "default": { @@ -1005,35 +1068,50 @@ } } }, - "/v1/dms/namespaces/{namespace_uid}": { - "put": { + "/v1/dms/db_service_sync_tasks/tips": { + "get": { + "tags": [ + "DBServiceSyncTask" + ], + "summary": "List database synchronization task tips.", + "operationId": "ListDBServiceSyncTaskTips", + "responses": { + "200": { + "description": "ListDBServiceSyncTaskTipsReply", + "schema": { + "$ref": "#/definitions/ListDBServiceSyncTaskTipsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/db_service_sync_tasks/{db_service_sync_task_uid}": { + "get": { "tags": [ - "dms" + "DBServiceSyncTask" ], - "summary": "update a Namespace.", - "operationId": "UpdateNamespace", + "summary": "Get database synchronization task.", + "operationId": "GetDBServiceSyncTask", "parameters": [ { "type": "string", - "x-go-name": "NamespaceUid", - "description": "Namespace uid", - "name": "namespace_uid", + "description": "db service sync task uid", + "name": "db_service_sync_task_uid", "in": "path", "required": true - }, - { - "x-go-name": "Namespace", - "description": "Update a namespace", - "name": "namespace", - "in": "body", - "schema": {} } ], "responses": { "200": { - "description": "GenericResp", + "description": "GetDBServiceSyncTaskReply", "schema": { - "$ref": "#/definitions/GenericResp" + "$ref": "#/definitions/GetDBServiceSyncTaskReply" } }, "default": { @@ -1044,20 +1122,28 @@ } } }, - "delete": { - "description": "Delete a Namespace", + "put": { "tags": [ - "dms" + "DBServiceSyncTask" ], - "operationId": "DelNamespace", + "summary": "update database synchronization task.", + "operationId": "UpdateDBServiceSyncTask", "parameters": [ { "type": "string", - "x-go-name": "NamespaceUid", - "description": "namespace uid", - "name": "namespace_uid", + "description": "db service sync task uid", + "name": "db_service_sync_task_uid", "in": "path", "required": true + }, + { + "description": "update db service sync task", + "name": "db_service_sync_task", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateDBServiceSyncTaskReq" + } } ], "responses": { @@ -1074,21 +1160,18 @@ } } } - } - }, - "/v1/dms/namespaces/{namespace_uid}/archive": { - "put": { + }, + "delete": { "tags": [ - "dms" + "DBServiceSyncTask" ], - "summary": "Archive a Namespace.", - "operationId": "ArchiveNamespace", + "summary": "Delete database synchronization task.", + "operationId": "DeleteDBServiceSyncTask", "parameters": [ { "type": "string", - "x-go-name": "NamespaceUid", - "description": "Namespace uid", - "name": "namespace_uid", + "description": "db service sync task uid", + "name": "db_service_sync_task_uid", "in": "path", "required": true } @@ -1109,19 +1192,18 @@ } } }, - "/v1/dms/namespaces/{namespace_uid}/unarchive": { - "put": { + "/v1/dms/db_service_sync_tasks/{db_service_sync_task_uid}/sync": { + "post": { "tags": [ - "dms" + "DBServiceSyncTask" ], - "summary": "Unarchive a Namespace.", - "operationId": "UnarchiveNamespace", + "summary": "Sync db service.", + "operationId": "SyncDBServices", "parameters": [ { "type": "string", - "x-go-name": "NamespaceUid", - "description": "Namespace uid", - "name": "namespace_uid", + "description": "db service sync task uid", + "name": "db_service_sync_task_uid", "in": "path", "required": true } @@ -1142,27 +1224,130 @@ } } }, - "/v1/dms/notifications": { - "post": { + "/v1/dms/db_services": { + "get": { + "description": "list global DBServices", "tags": [ - "dms" + "DBService" ], - "summary": "notify message.", - "operationId": "Notification", + "operationId": "ListGlobalDBServices", + "deprecated": true, "parameters": [ { - "x-go-name": "Notification", - "description": "notification", - "name": "notification", - "in": "body", - "schema": {} + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of db service to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of users to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name DBServiceOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname DBServiceOrderByName", + "name": "order_by", + "in": "query" + }, + { + "enum": [ + "connect_success", + "connect_failed" + ], + "type": "string", + "x-go-name": "FilterLastConnectionTestStatus", + "description": "the db service connection", + "name": "filter_last_connection_test_status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByBusiness", + "description": "TODO This parameter is deprecated and will be removed soon.\nthe db service business name", + "name": "filter_by_business", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByEnvironmentTag", + "description": "filter db services by environment tag", + "name": "filter_by_environment_tag", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByHost", + "description": "the db service host", + "name": "filter_by_host", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUID", + "description": "the db service uid", + "name": "filter_by_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "the db service name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByPort", + "description": "the db service port", + "name": "filter_by_port", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDBType", + "description": "the db service db type", + "name": "filter_by_db_type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByProjectUid", + "description": "the db service project id", + "name": "filter_by_project_uid", + "in": "query" + }, + { + "type": "boolean", + "x-go-name": "FilterByIsEnableMasking", + "description": "is masking", + "name": "filter_by_is_enable_masking", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "the db service fuzzy keyword", + "name": "fuzzy_keyword", + "in": "query" } ], "responses": { "200": { - "description": "NotificationReply", + "description": "ListGlobalDBServicesReply", "schema": { - "$ref": "#/definitions/NotificationReply" + "$ref": "#/definitions/ListGlobalDBServicesReply" } }, "default": { @@ -1174,18 +1359,18 @@ } } }, - "/v1/dms/oauth2/tips": { + "/v1/dms/db_services/driver_options": { "get": { "tags": [ - "dms" + "DBService" ], - "summary": "Get Oauth2 Tips.", - "operationId": "GetOauth2Tips", + "summary": "List db service driver option.", + "operationId": "ListDBServiceDriverOption", "responses": { "200": { - "description": "GetOauth2TipsReply", + "description": "ListDBServiceDriverOptionReply", "schema": { - "$ref": "#/definitions/GetOauth2TipsReply" + "$ref": "#/definitions/ListDBServiceDriverOptionReply" } }, "default": { @@ -1197,38 +1382,32 @@ } } }, - "/v1/dms/oauth2/user/bind": { - "post": { + "/v1/dms/db_services/tips": { + "get": { + "description": "list global DBServices tips", "tags": [ - "dms" + "DBService" ], - "summary": "Bind Oauth2 User.", - "operationId": "BindOauth2User", + "operationId": "ListGlobalDBServicesTips", "parameters": [ { + "enum": [ + "data_masking" + ], "type": "string", - "x-go-name": "UserName", - "name": "user_name", - "in": "query" - }, - { - "type": "string", - "x-go-name": "Pwd", - "name": "pwd", - "in": "query" - }, - { - "type": "string", - "x-go-name": "Oauth2Token", - "name": "oauth2_token", + "example": "data_masking", + "x-go-enum-desc": "data_masking FunctionSupportTypeDataMasking FunctionSupportTypeDataMasking 数据脱敏功能", + "x-go-name": "FunctionSupport", + "description": "function support filter, when specified, returns the db types supported by the function\ndata_masking FunctionSupportTypeDataMasking FunctionSupportTypeDataMasking 数据脱敏功能", + "name": "function_support", "in": "query" } ], "responses": { "200": { - "description": "BindOauth2UserReply", + "description": "ListGlobalDBServicesTipsReply", "schema": { - "$ref": "#/definitions/BindOauth2UserReply" + "$ref": "#/definitions/ListGlobalDBServicesTipsReply" } }, "default": { @@ -1240,49 +1419,35 @@ } } }, - "/v1/dms/op_permissions": { + "/v1/dms/gateways": { "get": { "tags": [ - "dms" + "Gateway" ], - "summary": "List op permission.", - "operationId": "ListOpPermissions", + "summary": "List gateways.", + "operationId": "ListGateways", "parameters": [ - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageSize", - "description": "the maximum count of op permission to be returned", - "name": "page_size", - "in": "query", - "required": true - }, { "type": "integer", "format": "uint32", "x-go-name": "PageIndex", - "description": "the offset of op permissions to be returned, default is 0", "name": "page_index", "in": "query" }, { - "x-go-name": "OrderBy", - "description": "Order by the specified field", - "name": "order_by", - "in": "query" - }, - { - "x-go-name": "FilterByTarget", - "description": "filter by op permission target", - "name": "filter_by_target", - "in": "query" + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { - "description": "ListOpPermissionReply", + "description": "ListGatewaysReply", "schema": { - "$ref": "#/definitions/ListOpPermissionReply" + "$ref": "#/definitions/ListGatewaysReply" } }, "default": { @@ -1292,22 +1457,22 @@ } } } - } - }, - "/v1/dms/plugin": { + }, "post": { "tags": [ - "dms" + "Gateway" ], - "summary": "Register dms plugin.", - "operationId": "RegisterDMSPlugin", + "summary": "Add gateways.", + "operationId": "AddGateway", "parameters": [ { - "x-go-name": "Plugin", - "description": "Register dms plugin", - "name": "plugin", + "description": "add gateway", + "name": "add_gateway", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/AddGatewayReq" + } } ], "responses": { @@ -1326,27 +1491,18 @@ } } }, - "/v1/dms/proxy": { - "post": { + "/v1/dms/gateways/tips": { + "get": { "tags": [ - "dms" - ], - "summary": "Register dms proxy target.", - "operationId": "RegisterDMSProxyTarget", - "parameters": [ - { - "x-go-name": "DMSProxyTarget", - "description": "register dms proxy", - "name": "dms_proxy_target", - "in": "body", - "schema": {} - } + "Gateway" ], + "summary": "Get gateway tips.", + "operationId": "GetGatewayTips", "responses": { "200": { - "description": "GenericResp", + "description": "GetGatewayTipsReply", "schema": { - "$ref": "#/definitions/GenericResp" + "$ref": "#/definitions/GetGatewayTipsReply" } }, "default": { @@ -1358,50 +1514,27 @@ } } }, - "/v1/dms/roles": { + "/v1/dms/gateways/{gateway_id}": { "get": { "tags": [ - "dms" + "Gateway" ], - "summary": "List roles.", - "operationId": "ListRoles", + "summary": "Get gateways.", + "operationId": "GetGateway", "parameters": [ - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageSize", - "description": "the maximum count of role to be returned", - "name": "page_size", - "in": "query", - "required": true - }, - { - "type": "integer", - "format": "uint32", - "x-go-name": "PageIndex", - "description": "the offset of roles to be returned, default is 0", - "name": "page_index", - "in": "query" - }, - { - "x-go-name": "OrderBy", - "description": "Multiple of [\"name\"], default is [\"name\"]", - "name": "order_by", - "in": "query" - }, { "type": "string", - "x-go-name": "FilterByName", - "description": "filter the role name", - "name": "filter_by_name", - "in": "query" + "x-go-name": "GetGatewayID", + "name": "gateway_id", + "in": "path", + "required": true } ], "responses": { "200": { - "description": "ListRoleReply", + "description": "GetGatewayReply", "schema": { - "$ref": "#/definitions/ListRoleReply" + "$ref": "#/definitions/GetGatewayReply" } }, "default": { @@ -1412,26 +1545,35 @@ } } }, - "post": { + "put": { "tags": [ - "dms" + "Gateway" ], - "summary": "Add role.", - "operationId": "AddRole", + "summary": "update gateways.", + "operationId": "UpdateGateway", "parameters": [ { - "x-go-name": "Role", - "description": "Add new role", - "name": "role", + "type": "string", + "description": "gateway id", + "name": "gateway_id", + "in": "path", + "required": true + }, + { + "description": "update gateway", + "name": "update_gateway", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/UpdateGatewayReq" + } } ], "responses": { "200": { - "description": "AddRoleReply", + "description": "GenericResp", "schema": { - "$ref": "#/definitions/AddRoleReply" + "$ref": "#/definitions/GenericResp" } }, "default": { @@ -1441,30 +1583,20 @@ } } } - } - }, - "/v1/dms/roles/{role_uid}": { - "put": { + }, + "delete": { "tags": [ - "dms" + "Gateway" ], - "summary": "Update a role.", - "operationId": "UpdateRole", + "summary": "Delete gateways.", + "operationId": "DeleteGateway", "parameters": [ { "type": "string", - "x-go-name": "RoleUid", - "description": "Role uid", - "name": "role_uid", + "x-go-name": "DeleteGatewayID", + "name": "gateway_id", "in": "path", "required": true - }, - { - "x-go-name": "Role", - "description": "Update a role", - "name": "role", - "in": "body", - "schema": {} } ], "responses": { @@ -1481,32 +1613,24 @@ } } } - }, - "delete": { + } + }, + "/v1/dms/masking/rules": { + "get": { "tags": [ - "dms" - ], - "summary": "Delete a role.", - "operationId": "DelRole", - "parameters": [ - { - "type": "string", - "x-go-name": "RoleUid", - "description": "role uid", - "name": "role_uid", - "in": "path", - "required": true - } + "Masking" ], + "summary": "List masking rules.", + "operationId": "ListMaskingRules", "responses": { "200": { - "description": "GenericResp", + "description": "List masking rules successfully", "schema": { - "$ref": "#/definitions/GenericResp" + "$ref": "#/definitions/ListMaskingRulesReply" } }, "default": { - "description": "GenericResp", + "description": "Generic error response", "schema": { "$ref": "#/definitions/GenericResp" } @@ -1514,27 +1638,29 @@ } } }, - "/v1/dms/sessions": { + "/v1/dms/notifications": { "post": { "tags": [ - "dms" + "Notification" ], - "summary": "Add a session.", - "operationId": "AddSession", + "summary": "notify message.", + "operationId": "Notification", "parameters": [ { - "x-go-name": "Session", - "description": "Add a new session", - "name": "session", + "x-go-name": "Notification", + "description": "notification", + "name": "notification", "in": "body", - "schema": {} + "schema": { + "$ref": "#/definitions/Notification" + } } ], "responses": { "200": { - "description": "AddSessionReply", + "description": "NotificationReply", "schema": { - "$ref": "#/definitions/AddSessionReply" + "$ref": "#/definitions/NotificationReply" } }, "default": { @@ -1546,26 +1672,60 @@ } } }, - "/v1/dms/sessions/user": { + "/v1/dms/oauth2/link": { "get": { "tags": [ - "dms" + "OAuth2" ], - "summary": "Get current user.", - "operationId": "GetUserBySession", + "summary": "Oauth2 Link or Callback.", + "operationId": "Oauth2LinkOrCallback" + } + }, + "/v1/dms/oauth2/tips": { + "get": { + "tags": [ + "OAuth2" + ], + "summary": "Get Oauth2 Tips.", + "operationId": "GetOauth2Tips", + "responses": { + "200": { + "description": "GetOauth2TipsReply", + "schema": { + "$ref": "#/definitions/GetOauth2TipsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/oauth2/user/bind": { + "post": { + "tags": [ + "OAuth2" + ], + "summary": "Bind Oauth2 User.", + "operationId": "BindOauth2User", "parameters": [ { - "type": "string", - "x-go-name": "UserUid", - "name": "user_uid", - "in": "query" + "name": "BindOauth2UserReq", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/BindOauth2UserReq" + } } ], "responses": { "200": { - "description": "GetUserBySessionReply", + "description": "BindOauth2UserReply", "schema": { - "$ref": "#/definitions/GetUserBySessionReply" + "$ref": "#/definitions/BindOauth2UserReply" } }, "default": { @@ -1577,19 +1737,19 @@ } } }, - "/v1/dms/user_groups": { + "/v1/dms/op_permissions": { "get": { "tags": [ - "dms" + "OpPermission" ], - "summary": "List user groups.", - "operationId": "ListUserGroups", + "summary": "List op permission.", + "operationId": "ListOpPermissions", "parameters": [ { "type": "integer", "format": "uint32", "x-go-name": "PageSize", - "description": "the maximum count of user to be returned", + "description": "the maximum count of op permission to be returned", "name": "page_size", "in": "query", "required": true @@ -1598,29 +1758,53 @@ "type": "integer", "format": "uint32", "x-go-name": "PageIndex", - "description": "the offset of user groups to be returned, default is 0", + "description": "the offset of op permissions to be returned, default is 0", "name": "page_index", "in": "query" }, { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name OpPermissionOrderByName", "x-go-name": "OrderBy", - "description": "Multiple of [\"name\"], default is [\"name\"]", + "description": "Order by the specified field\nname OpPermissionOrderByName", "name": "order_by", "in": "query" }, { + "enum": [ + "all", + "user", + "member", + "project" + ], "type": "string", - "x-go-name": "FilterByName", - "description": "filter the user group name", - "name": "filter_by_name", + "x-go-enum-desc": "all OpPermissionTargetAll\nuser OpPermissionTargetUser\nmember OpPermissionTargetMember\nproject OpPermissionTargetProject", + "x-go-name": "FilterByTarget", + "description": "filter by op permission target\nall OpPermissionTargetAll\nuser OpPermissionTargetUser\nmember OpPermissionTargetMember\nproject OpPermissionTargetProject", + "name": "filter_by_target", + "in": "query" + }, + { + "enum": [ + "dms", + "sqle" + ], + "type": "string", + "x-go-enum-desc": "dms ServiceDMS\nsqle ServiceSQLE", + "x-go-name": "Service", + "description": "filter by service\ndms ServiceDMS\nsqle ServiceSQLE", + "name": "service", "in": "query" } ], "responses": { "200": { - "description": "ListUserGroupReply", + "description": "ListOpPermissionReply", "schema": { - "$ref": "#/definitions/ListUserGroupReply" + "$ref": "#/definitions/ListOpPermissionReply" } }, "default": { @@ -1630,27 +1814,74 @@ } } } - }, - "post": { + } + }, + "/v1/dms/operation_records": { + "get": { "tags": [ - "dms" + "OperationRecord" ], - "summary": "Add user group.", - "operationId": "AddUserGroup", + "summary": "Get operation record list.", + "operationId": "GetOperationRecordList", "parameters": [ { - "x-go-name": "UserGroup", - "description": "Add new user group", - "name": "user_group", - "in": "body", - "schema": {} + "type": "string", + "x-go-name": "FilterOperateTimeFrom", + "name": "filter_operate_time_from", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateTimeTo", + "name": "filter_operate_time_to", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateProjectName", + "name": "filter_operate_project_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzySearchOperateUserName", + "name": "fuzzy_search_operate_user_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateTypeName", + "name": "filter_operate_type_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateAction", + "name": "filter_operate_action", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "name": "page_index", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "name": "page_size", + "in": "query", + "required": true } ], "responses": { "200": { - "description": "AddUserGroupReply", + "description": "GetOperationRecordListReply", "schema": { - "$ref": "#/definitions/AddUserGroupReply" + "$ref": "#/definitions/GetOperationRecordListReply" } }, "default": { @@ -1660,38 +1891,91 @@ } } } - } - }, - "/v1/dms/user_groups/{user_group_uid}": { - "put": { + }, + "post": { "tags": [ - "dms" + "OperationRecord" ], - "summary": "Update a user group.", - "operationId": "UpdateUserGroup", + "summary": "Add operation record.", + "operationId": "AddOperationRecord", "parameters": [ { - "type": "string", - "x-go-name": "UserGroupUid", - "description": "UserGroup uid", - "name": "user_group_uid", - "in": "path", - "required": true - }, - { - "x-go-name": "UserGroup", - "description": "Update a user group", - "name": "user_group", + "description": "Add new operation record", + "name": "operation_record", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/AddOperationRecordReq" + } } ], "responses": { "200": { + "description": "AddOperationRecordReply", + "schema": { + "$ref": "#/definitions/AddOperationRecordReply" + } + }, + "default": { "description": "GenericResp", "schema": { "$ref": "#/definitions/GenericResp" } + } + } + } + }, + "/v1/dms/operation_records/exports": { + "get": { + "tags": [ + "OperationRecord" + ], + "summary": "Export operation record list.", + "operationId": "ExportOperationRecordList", + "parameters": [ + { + "type": "string", + "x-go-name": "FilterOperateTimeFrom", + "name": "filter_operate_time_from", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateTimeTo", + "name": "filter_operate_time_to", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateProjectName", + "name": "filter_operate_project_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzySearchOperateUserName", + "name": "fuzzy_search_operate_user_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateTypeName", + "name": "filter_operate_type_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperateAction", + "name": "filter_operate_action", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ExportOperationRecordListReply", + "schema": { + "type": "file" + } }, "default": { "description": "GenericResp", @@ -1700,21 +1984,27 @@ } } } - }, - "delete": { + } + }, + "/v1/dms/personalization": { + "post": { "tags": [ - "dms" + "BasicInfo" ], - "summary": "Delete a user group.", - "operationId": "DelUserGroup", + "summary": "personalize [title, logo].", + "operationId": "Personalization", "parameters": [ { "type": "string", - "x-go-name": "UserGroupUid", - "description": "user group uid", - "name": "user_group_uid", - "in": "path", - "required": true + "description": "title", + "name": "title", + "in": "formData" + }, + { + "type": "file", + "description": "file upload", + "name": "file", + "in": "formData" } ], "responses": { @@ -1733,19 +2023,77 @@ } } }, - "/v1/dms/users": { + "/v1/dms/personalization/logo": { "get": { + "description": "get logo", + "produces": [ + "application/octet-stream" + ], "tags": [ - "dms" + "BasicInfo" ], - "summary": "List users.", - "operationId": "ListUsers", + "operationId": "GetStaticLogo", + "responses": { + "200": { + "$ref": "#/responses/GetStaticLogoReply" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/plugins": { + "post": { + "tags": [ + "DMSPlugin" + ], + "summary": "Register dms plugin.", + "operationId": "RegisterDMSPlugin", + "parameters": [ + { + "description": "Register dms plugin", + "name": "plugin", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/RegisterDMSPluginReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects": { + "get": { + "tags": [ + "Project" + ], + "summary": "List projects.", + "operationId": "ListProjects", + "deprecated": true, "parameters": [ { "type": "integer", "format": "uint32", "x-go-name": "PageSize", - "description": "the maximum count of user to be returned", + "description": "the maximum count of Project to be returned", "name": "page_size", "in": "query", "required": true @@ -1754,43 +2102,72 @@ "type": "integer", "format": "uint32", "x-go-name": "PageIndex", - "description": "the offset of users to be returned, default is 0", + "description": "the offset of Projects to be returned, default is 0", "name": "page_index", "in": "query" }, { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name ProjectOrderByName", "x-go-name": "OrderBy", - "description": "Multiple of [\"name\"], default is [\"name\"]", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname ProjectOrderByName", "name": "order_by", "in": "query" }, { "type": "string", "x-go-name": "FilterByName", - "description": "filter the user name", + "description": "filter the Project name", "name": "filter_by_name", "in": "query" }, { "type": "string", - "x-go-name": "FilterByUids", - "description": "filter the user uids", - "name": "filter_by_uids", + "x-go-name": "FilterByUID", + "description": "filter the Project UID", + "name": "filter_by_uid", "in": "query" }, { - "type": "boolean", - "x-go-name": "FilterDeletedUser", - "description": "filter deleted user to be return ,default is false", - "name": "filter_del_user", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "FilterByProjectUids", + "description": "filter project by project id list, using in condition", + "name": "filter_by_project_uids", + "in": "query" + }, + { + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "type": "string", + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "FilterByProjectPriority", + "description": "filter project by project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "name": "filter_by_project_priority", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDesc", + "description": "filter the Project By Project description", + "name": "filter_by_desc", "in": "query" } ], "responses": { "200": { - "description": "ListUserReply", + "description": "ListProjectReply", "schema": { - "$ref": "#/definitions/ListUserReply" + "$ref": "#/definitions/ListProjectReply" } }, "default": { @@ -1803,24 +2180,27 @@ }, "post": { "tags": [ - "dms" + "Project" ], - "summary": "Add user.", - "operationId": "AddUser", + "summary": "Add project.", + "operationId": "AddProject", + "deprecated": true, "parameters": [ { - "x-go-name": "User", - "description": "Add new user", - "name": "user", + "description": "Add new Project", + "name": "project", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/AddProjectReq" + } } ], "responses": { "200": { - "description": "AddUserReply", + "description": "AddProjectReply", "schema": { - "$ref": "#/definitions/AddUserReply" + "$ref": "#/definitions/AddProjectReply" } }, "default": { @@ -1832,28 +2212,41 @@ } } }, - "/v1/dms/users/{user_uid}": { + "/v1/dms/projects/business_tags": { "get": { "tags": [ - "dms" + "Project" ], - "summary": "Get user info, This API is used by other component such as sqle\u0026auth to get user info.", - "operationId": "GetUser", + "summary": "List business tags.", + "operationId": "ListBusinessTags", "parameters": [ { - "type": "string", - "x-go-name": "UserUid", - "description": "user uid", - "name": "user_uid", - "in": "path", + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "name": "page_index", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "name": "page_size", + "in": "query", "required": true + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "name": "fuzzy_keyword", + "in": "query" } ], "responses": { "200": { - "description": "GetUserReply", + "description": "ListBusinessTagsReply", "schema": { - "$ref": "#/definitions/GetUserReply" + "$ref": "#/definitions/ListBusinessTagsReply" } }, "default": { @@ -1864,27 +2257,21 @@ } } }, - "put": { + "post": { "tags": [ - "dms" + "Project" ], - "summary": "Update a user.", - "operationId": "UpdateUser", + "summary": "Create a new business tag.", + "operationId": "CreateBusinessTag", "parameters": [ { - "type": "string", - "x-go-name": "UserUid", - "description": "User uid", - "name": "user_uid", - "in": "path", - "required": true - }, - { - "x-go-name": "User", - "description": "Update a user", - "name": "user", + "description": "business tag to be created", + "name": "business_tag", "in": "body", - "schema": {} + "required": true, + "schema": { + "$ref": "#/definitions/CreateBusinessTagReq" + } } ], "responses": { @@ -1901,21 +2288,31 @@ } } } - }, - "delete": { + } + }, + "/v1/dms/projects/business_tags/{business_tag_uid}": { + "put": { "tags": [ - "dms" + "Project" ], - "summary": "Delete a user.", - "operationId": "DelUser", + "summary": "Update an existing business tag.", + "operationId": "UpdateBusinessTag", "parameters": [ { "type": "string", - "x-go-name": "UserUid", - "description": "user uid", - "name": "user_uid", + "description": "business tag id", + "name": "business_tag_uid", "in": "path", "required": true + }, + { + "description": "the business tag to be updated", + "name": "business_tag", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateBusinessTagReq" + } } ], "responses": { @@ -1932,37 +2329,27 @@ } } } - } - }, - "/v1/dms/users/{user_uid}/op_permission": { - "get": { + }, + "delete": { "tags": [ - "dms" + "Project" ], - "summary": "Get user op permission info, This API is used by other component such as sqle\u0026auth to check user permissions.", - "operationId": "GetUserOpPermission", + "summary": "Delete an existing business tag.", + "operationId": "DeleteBusinessTag", "parameters": [ { "type": "string", - "x-go-name": "UserUid", - "description": "user uid", - "name": "user_uid", + "x-go-name": "BusinessTagUID", + "name": "business_tag_uid", "in": "path", "required": true - }, - { - "x-go-name": "UserOpPermission", - "description": "user op permission info", - "name": "user_op_permission", - "in": "body", - "schema": {} } ], "responses": { "200": { - "description": "GetUserOpPermissionReply", + "description": "GenericResp", "schema": { - "$ref": "#/definitions/GetUserOpPermissionReply" + "$ref": "#/definitions/GenericResp" } }, "default": { @@ -1974,27 +2361,28 @@ } } }, - "/v1/dms/webhooks": { + "/v1/dms/projects/check_db_services_privileges": { "post": { "tags": [ - "dms" + "Project" ], - "summary": "webhook send message.", - "operationId": "WebHookSendMessage", + "summary": "check if the db_services hava enough privileges.", + "operationId": "CheckDBServicesPrivileges", "parameters": [ { - "x-go-name": "WebHookMessage", - "description": "webhooks", - "name": "webhook_message", + "description": "check db_services have enough privileges", + "name": "db_services", "in": "body", - "schema": {} + "schema": { + "$ref": "#/definitions/CheckDBServicesPrivilegesReq" + } } ], "responses": { "200": { - "description": "WebHookSendMessageReply", + "description": "CheckDBServicesPrivilegesReply", "schema": { - "$ref": "#/definitions/WebHookSendMessageReply" + "$ref": "#/definitions/CheckDBServicesPrivilegesReply" } }, "default": { @@ -2005,140 +2393,15290 @@ } } } - } - }, - "definitions": { - "AddDBServicePreCheckReply": { - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - }, - "AddDBServiceReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "AddMemberReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "AddNamespaceReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "AddRoleReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "AddSessionReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "AddUserGroupReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "AddUserReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "BindOauth2UserReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" - }, - "CheckDBServiceIsConnectableReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "DelDBServicePreCheckReply": { + "/v1/dms/projects/data_export_workflows": { + "get": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "List all data_export workflow.", + "operationId": "ListAllDataExportWorkflows", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of member to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of members to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "wait_for_approve", + "wait_for_export", + "exporting", + "rejected", + "cancel", + "failed", + "finish" + ], + "type": "string", + "x-go-enum-desc": "wait_for_approve DataExportWorkflowStatusWaitForApprove\nwait_for_export DataExportWorkflowStatusWaitForExport\nexporting DataExportWorkflowStatusWaitForExporting\nrejected DataExportWorkflowStatusRejected\ncancel DataExportWorkflowStatusCancel\nfailed DataExportWorkflowStatusFailed\nfinish DataExportWorkflowStatusFinish", + "x-go-name": "FilterByStatus", + "description": "filter the status\nwait_for_approve DataExportWorkflowStatusWaitForApprove\nwait_for_export DataExportWorkflowStatusWaitForExport\nexporting DataExportWorkflowStatusWaitForExporting\nrejected DataExportWorkflowStatusRejected\ncancel DataExportWorkflowStatusCancel\nfailed DataExportWorkflowStatusFailed\nfinish DataExportWorkflowStatusFinish", + "name": "filter_by_status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByCreateUserUid", + "description": "filter create user id", + "name": "filter_by_create_user_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterCurrentStepAssigneeUserUid", + "description": "filter current assignee user id", + "name": "filter_current_step_assignee_user_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDBServiceUid", + "description": "filter db_service id", + "name": "filter_by_db_service_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterCreateTimeFrom", + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterCreateTimeTo", + "description": "filter create time end", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "filter fuzzy key word for id/name", + "name": "fuzzy_keyword", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListDataExportWorkflowsReply", + "schema": { + "$ref": "#/definitions/ListDataExportWorkflowsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/db_services_connection": { + "post": { + "tags": [ + "Project" + ], + "summary": "DBServices Connection.", + "operationId": "DBServicesConnection", + "parameters": [ + { + "description": "check db_service is connectable", + "name": "db_services", + "in": "body", + "schema": { + "$ref": "#/definitions/DBServiceConnectionReq" + } + } + ], + "responses": { + "200": { + "description": "DBServicesConnectionReply", + "schema": { + "$ref": "#/definitions/DBServicesConnectionReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/db_services_connections": { + "post": { + "tags": [ + "Project" + ], + "summary": "check if the global db_services is connectable.", + "operationId": "CheckGlobalDBServicesConnections", + "parameters": [ + { + "description": "check db_services is connectable", + "name": "db_services", + "in": "body", + "schema": { + "$ref": "#/definitions/DBServicesConnectionReq" + } + } + ], + "responses": { + "200": { + "description": "DBServicesConnectionReqReply", + "schema": { + "$ref": "#/definitions/DBServicesConnectionReqReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/export": { + "get": { + "tags": [ + "Project" + ], + "summary": "Export projects file.", + "operationId": "ExportProjects", + "parameters": [ + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name ProjectOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname ProjectOrderByName", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "filter the Project name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUID", + "description": "filter the Project UID", + "name": "filter_by_uid", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/ExportProjectsReply" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/import": { + "post": { + "tags": [ + "Project" + ], + "summary": "Import projects.", + "operationId": "ImportProjects", + "deprecated": true, + "parameters": [ + { + "description": "import projects", + "name": "projects", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ImportProjectsReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/import_db_services": { + "post": { + "tags": [ + "Project" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfProjects", + "deprecated": true, + "parameters": [ + { + "description": "new db services", + "name": "db_services", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ImportDBServicesOfProjectsReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/import_db_services_check": { + "post": { + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json", + "text/csv" + ], + "tags": [ + "Project" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfProjectsCheck", + "deprecated": true, + "parameters": [ + { + "type": "file", + "x-go-name": "DBServicesFile", + "description": "DBServices file.", + "name": "db_services_file", + "in": "formData" + } + ], + "responses": { + "200": { + "$ref": "#/responses/ImportDBServicesCheckCsvReply" + }, + "default": { + "description": "ImportDBServicesCheckReply", + "schema": { + "$ref": "#/definitions/ImportDBServicesCheckReply" + } + } + } + } + }, + "/v1/dms/projects/import_db_services_template": { + "get": { + "tags": [ + "Project" + ], + "summary": "Get import DBServices template.", + "operationId": "GetImportDBServicesTemplate", + "responses": { + "200": { + "$ref": "#/responses/GetImportDBServicesTemplateReply" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/import_template": { + "get": { + "tags": [ + "Project" + ], + "summary": "Get import projects template.", + "operationId": "GetImportProjectsTemplate", + "responses": { + "200": { + "$ref": "#/responses/GetImportProjectsTemplateReply" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/preview_import": { + "post": { + "consumes": [ + "multipart/form-data" + ], + "tags": [ + "Project" + ], + "summary": "Preview import projects.", + "operationId": "PreviewImportProjects", + "deprecated": true, + "parameters": [ + { + "type": "file", + "x-go-name": "ProjectsFile", + "description": "projects file.", + "name": "projects_file", + "in": "formData" + } + ], + "responses": { + "200": { + "description": "PreviewImportProjectsReply", + "schema": { + "$ref": "#/definitions/PreviewImportProjectsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/tips": { + "get": { + "tags": [ + "Project" + ], + "summary": "Get project tips.", + "operationId": "GetProjectTips", + "deprecated": true, + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "Project uid", + "name": "project_uid", + "in": "query" + } + ], + "responses": { + "200": { + "description": "GetProjectTipsReply", + "schema": { + "$ref": "#/definitions/GetProjectTipsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}": { + "put": { + "tags": [ + "Project" + ], + "summary": "update a project.", + "operationId": "UpdateProject", + "deprecated": true, + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "Update a project", + "name": "project", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateProjectReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "description": "Delete a project", + "tags": [ + "Project" + ], + "operationId": "DelProject", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/archive": { + "put": { + "tags": [ + "Project" + ], + "summary": "Archive a project.", + "operationId": "ArchiveProject", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "Project uid", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/cb_operation_logs": { + "get": { + "tags": [ + "CBOperationLogs" + ], + "summary": "List cb operation logs.", + "operationId": "ListCBOperationLogs", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "FilterOperationPersonUID", + "name": "filter_operation_person_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperationTimeFrom", + "name": "filter_operation_time_from", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperationTimeTo", + "name": "filter_operation_time_to", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterDBServiceUID", + "name": "filter_db_service_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterExecResult", + "name": "filter_exec_result", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "filter fuzzy key word for operation_detail/operation_ip", + "name": "fuzzy_keyword", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of member to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of members to be returned, default is 0", + "name": "page_index", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListCBOperationLogsReply", + "schema": { + "$ref": "#/definitions/ListCBOperationLogsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/cb_operation_logs/export": { + "get": { + "tags": [ + "CBOperationLogs" + ], + "summary": "Export cb operation logs.", + "operationId": "ExportCBOperationLogs", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "FilterOperationPersonUID", + "name": "filter_operation_person_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperationTimeFrom", + "name": "filter_operation_time_from", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterOperationTimeTo", + "name": "filter_operation_time_to", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterDBServiceUID", + "name": "filter_db_service_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterExecResult", + "name": "filter_exec_result", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "filter fuzzy key word for operation_detail/operation_ip", + "name": "fuzzy_keyword", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/ExportCBOperationLogsReply" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/cb_operation_logs/tips": { + "get": { + "tags": [ + "CBOperationLogs" + ], + "summary": "Get cb operation log tips.", + "operationId": "GetCBOperationLogTips", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GetCBOperationLogTipsReply", + "schema": { + "$ref": "#/definitions/GetCBOperationLogTipsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_tasks": { + "get": { + "tags": [ + "DataExportTask" + ], + "summary": "Batch get data_export task.", + "operationId": "BatchGetDataExportTask", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "TaskUids", + "name": "data_export_task_uids", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "BatchGetDataExportTaskReply", + "schema": { + "$ref": "#/definitions/BatchGetDataExportTaskReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "DataExportTask" + ], + "summary": "Add data_export task.", + "operationId": "AddDataExportTask", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "add data export workflow", + "name": "data_export_tasks", + "in": "body", + "schema": { + "$ref": "#/definitions/AddDataExportTaskReq" + } + } + ], + "responses": { + "200": { + "description": "AddDataExportTaskReply", + "schema": { + "$ref": "#/definitions/AddDataExportTaskReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/data_export_task_sqls": { + "get": { + "tags": [ + "DataExportTask" + ], + "summary": "List data_export workflow.", + "operationId": "ListDataExportTaskSQLs", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "DataExportTaskUid", + "name": "data_export_task_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of member to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of members to be returned, default is 0", + "name": "page_index", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListDataExportTaskSQLsReply", + "schema": { + "$ref": "#/definitions/ListDataExportTaskSQLsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/data_export_task_sqls/download": { + "get": { + "tags": [ + "DataExportTask" + ], + "summary": "dowload data_export sqls.", + "operationId": "DownloadDataExportTaskSQLs", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "DataExportTaskUid", + "name": "data_export_task_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/DownloadDataExportTaskSQLsReply" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/download": { + "get": { + "tags": [ + "DataExportTask" + ], + "summary": "download task file.", + "operationId": "DownloadDataExportTask", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "DataExportTaskUid", + "name": "data_export_task_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/DownloadDataExportTaskReply" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_workflows": { + "get": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "List data_export workflow.", + "operationId": "ListDataExportWorkflows", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of member to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of members to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "wait_for_approve", + "wait_for_export", + "exporting", + "rejected", + "cancel", + "failed", + "finish" + ], + "type": "string", + "x-go-enum-desc": "wait_for_approve DataExportWorkflowStatusWaitForApprove\nwait_for_export DataExportWorkflowStatusWaitForExport\nexporting DataExportWorkflowStatusWaitForExporting\nrejected DataExportWorkflowStatusRejected\ncancel DataExportWorkflowStatusCancel\nfailed DataExportWorkflowStatusFailed\nfinish DataExportWorkflowStatusFinish", + "x-go-name": "FilterByStatus", + "description": "filter the status\nwait_for_approve DataExportWorkflowStatusWaitForApprove\nwait_for_export DataExportWorkflowStatusWaitForExport\nexporting DataExportWorkflowStatusWaitForExporting\nrejected DataExportWorkflowStatusRejected\ncancel DataExportWorkflowStatusCancel\nfailed DataExportWorkflowStatusFailed\nfinish DataExportWorkflowStatusFinish", + "name": "filter_by_status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByCreateUserUid", + "description": "filter create user id", + "name": "filter_by_create_user_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterCurrentStepAssigneeUserUid", + "description": "filter current assignee user id", + "name": "filter_current_step_assignee_user_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDBServiceUid", + "description": "filter db_service id", + "name": "filter_by_db_service_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterCreateTimeFrom", + "description": "filter create time from", + "name": "filter_create_time_from", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterCreateTimeTo", + "description": "filter create time end", + "name": "filter_create_time_to", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "filter fuzzy key word for id/name", + "name": "fuzzy_keyword", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListDataExportWorkflowsReply", + "schema": { + "$ref": "#/definitions/ListDataExportWorkflowsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "Add data_export workflow.", + "operationId": "AddDataExportWorkflow", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "add data export workflow", + "name": "data_export_workflow", + "in": "body", + "schema": { + "$ref": "#/definitions/AddDataExportWorkflowReq" + } + } + ], + "responses": { + "200": { + "description": "AddDataExportWorkflowReply", + "schema": { + "$ref": "#/definitions/AddDataExportWorkflowReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_workflows/cancel": { + "post": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "Cancel data export workflows.", + "operationId": "CancelDataExportWorkflow", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/CancelDataExportWorkflowReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}": { + "get": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "Get data_export workflow.", + "operationId": "GetDataExportWorkflow", + "parameters": [ + { + "type": "string", + "x-go-name": "DataExportWorkflowUid", + "name": "data_export_workflow_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GetDataExportWorkflowReply", + "schema": { + "$ref": "#/definitions/GetDataExportWorkflowReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/approve": { + "post": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "Approve data_export workflow.", + "operationId": "ApproveDataExportWorkflow", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "DataExportWorkflowUid", + "name": "data_export_workflow_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/export": { + "post": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "exec data_export workflow.", + "operationId": "ExportDataExportWorkflow", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "DataExportWorkflowUid", + "name": "data_export_workflow_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/reject": { + "post": { + "tags": [ + "DataExportWorkflows" + ], + "summary": "Reject data_export workflow.", + "operationId": "RejectDataExportWorkflow", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "name": "data_export_workflow_uid", + "in": "path", + "required": true + }, + { + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/RejectDataExportWorkflowReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services": { + "get": { + "tags": [ + "DBService" + ], + "summary": "List db service.", + "operationId": "ListDBServices", + "deprecated": true, + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of db service to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of users to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name DBServiceOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname DBServiceOrderByName", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByBusiness", + "description": "the db service business name", + "name": "filter_by_business", + "in": "query" + }, + { + "enum": [ + "connect_success", + "connect_failed" + ], + "type": "string", + "x-go-name": "FilterLastConnectionTestStatus", + "description": "the db service connection", + "name": "filter_last_connection_test_status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByHost", + "description": "the db service host", + "name": "filter_by_host", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUID", + "description": "the db service uid", + "name": "filter_by_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "the db service name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByPort", + "description": "the db service port", + "name": "filter_by_port", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDBType", + "description": "the db service db type", + "name": "filter_by_db_type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "FilterByDBServiceIds", + "description": "filter db services by db service id list using in condition", + "name": "filter_by_db_service_ids", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "the db service fuzzy keyword,include host/port", + "name": "fuzzy_keyword", + "in": "query" + }, + { + "type": "boolean", + "x-go-name": "IsEnableMasking", + "description": "is masking", + "name": "is_enable_masking", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListDBServiceReply", + "schema": { + "$ref": "#/definitions/ListDBServiceReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "DBService" + ], + "summary": "Add DB Service.", + "operationId": "AddDBService", + "deprecated": true, + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "Add new db service", + "name": "db_service", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddDBServiceReq" + } + } + ], + "responses": { + "200": { + "description": "AddDBServiceReply", + "schema": { + "$ref": "#/definitions/AddDBServiceReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services/connection": { + "post": { + "tags": [ + "DBService" + ], + "summary": "check if the db_service is connectable.", + "operationId": "CheckDBServiceIsConnectable", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "check db_service is connectable", + "name": "db_service", + "in": "body", + "schema": { + "$ref": "#/definitions/CheckDBServiceIsConnectableReq" + } + } + ], + "responses": { + "200": { + "description": "CheckDBServiceIsConnectableReply", + "schema": { + "$ref": "#/definitions/CheckDBServiceIsConnectableReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services/connections": { + "post": { + "tags": [ + "DBService" + ], + "summary": "check if the project db_services is connectable.", + "operationId": "CheckProjectDBServicesConnections", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "check db_services is connectable", + "name": "db_services", + "in": "body", + "schema": { + "$ref": "#/definitions/CheckDBServicesIsConnectableReq" + } + } + ], + "responses": { + "200": { + "description": "CheckDBServicesIsConnectableReply", + "schema": { + "$ref": "#/definitions/CheckDBServicesIsConnectableReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services/import": { + "post": { + "tags": [ + "DBService" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfOneProject", + "deprecated": true, + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "new db services", + "name": "db_services", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ImportDBServicesOfOneProjectReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services/import_check": { + "post": { + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json", + "text/csv" + ], + "tags": [ + "DBService" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfOneProjectCheck", + "deprecated": true, + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "file", + "x-go-name": "DBServicesFile", + "description": "DBServices file.", + "name": "db_services_file", + "in": "formData" + } + ], + "responses": { + "200": { + "$ref": "#/responses/ImportDBServicesCheckCsvReply" + }, + "default": { + "description": "ImportDBServicesCheckReply", + "schema": { + "$ref": "#/definitions/ImportDBServicesCheckReply" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services/tips": { + "get": { + "tags": [ + "DBService" + ], + "summary": "List db service tip.", + "operationId": "ListDBServiceTips", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "FilterDBType", + "name": "filter_db_type", + "in": "query" + }, + { + "enum": [ + "save_audit_plan", + "create_workflow", + "create_export_task" + ], + "type": "string", + "x-go-name": "FunctionalModule", + "name": "functional_module", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListDBServiceTipsReply", + "schema": { + "$ref": "#/definitions/ListDBServiceTipsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services/{db_service_uid}": { + "put": { + "tags": [ + "DBService" + ], + "summary": "update a DB Service.", + "operationId": "UpdateDBService", + "deprecated": true, + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "db_service_uid id", + "name": "db_service_uid", + "in": "path", + "required": true + }, + { + "description": "Update a DB service", + "name": "db_service", + "in": "body", + "schema": { + "$ref": "#/definitions/UpdateDBServiceReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "DBService" + ], + "summary": "Delete a DB Service.", + "operationId": "DelDBService", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "DBServiceUid", + "description": "db service uid", + "name": "db_service_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/db_services/{db_service_uid}/connection": { + "post": { + "tags": [ + "DBService" + ], + "summary": "check if the db_service is connectable.", + "operationId": "CheckDBServiceIsConnectableById", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "db service uid", + "name": "db_service_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "CheckDBServiceIsConnectableReply", + "schema": { + "$ref": "#/definitions/CheckDBServiceIsConnectableReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/environment_tags": { + "get": { + "tags": [ + "Project" + ], + "summary": "List environment tags.", + "operationId": "ListEnvironmentTags", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUID", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "name": "page_index", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "name": "page_size", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "ListEnvironmentTagsReply", + "schema": { + "$ref": "#/definitions/ListEnvironmentTagsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "Project" + ], + "summary": "Create a new environment tag.", + "operationId": "CreateEnvironmentTag", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "the name of environment tag to be created", + "name": "environment_name", + "in": "body", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/environment_tags/{environment_tag_uid}": { + "put": { + "tags": [ + "Project" + ], + "summary": "Update an existing environment tag.", + "operationId": "UpdateEnvironmentTag", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "environment tag id", + "name": "environment_tag_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "the name of environment tag to be updated", + "name": "environment_name", + "in": "body", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "Project" + ], + "summary": "Delete an existing environment tag.", + "operationId": "DeleteEnvironmentTag", + "parameters": [ + { + "type": "string", + "x-go-name": "EnvironmentTagUID", + "name": "environment_tag_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "ProjectUID", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/approval-requests/pending": { + "get": { + "tags": [ + "Masking" + ], + "summary": "List pending approval requests.", + "operationId": "ListPendingApprovalRequests", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "example": "20", + "x-go-name": "PageSize", + "description": "the maximum count of requests to be returned, default is 20", + "name": "page_size", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "example": "0", + "x-go-name": "PageIndex", + "description": "the offset of requests to be returned, default is 0", + "name": "page_index", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List pending approval requests successfully", + "schema": { + "$ref": "#/definitions/ListPendingApprovalRequestsReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/approval-requests/{request_id}": { + "get": { + "tags": [ + "Masking" + ], + "summary": "Get plaintext access request detail.", + "operationId": "GetPlaintextAccessRequestDetail", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "int64", + "example": 1, + "x-go-name": "RequestID", + "description": "approval request id", + "name": "request_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Get plaintext access request detail successfully", + "schema": { + "$ref": "#/definitions/GetPlaintextAccessRequestDetailReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/approval-requests/{request_id}/decisions": { + "post": { + "tags": [ + "Masking" + ], + "summary": "Process approval request.", + "operationId": "ProcessApprovalRequest", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "approval request id", + "name": "request_id", + "in": "path", + "required": true + }, + { + "description": "process action info", + "name": "action", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ProcessApprovalRequestReq" + } + } + ], + "responses": { + "200": { + "description": "Process approval request successfully", + "schema": { + "$ref": "#/definitions/ProcessApprovalRequestReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/overview": { + "get": { + "tags": [ + "Masking" + ], + "summary": "Get masking overview tree.", + "operationId": "GetMaskingOverviewTree", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "example": "\"1\"", + "x-go-name": "DBServiceUID", + "description": "data source id", + "name": "db_service_uid", + "in": "query", + "required": true + }, + { + "type": "string", + "example": "\"user\"", + "x-go-name": "Keywords", + "description": "fuzzy search keyword for database name, table name, and column name", + "name": "keywords", + "in": "query" + }, + { + "enum": [ + "CONFIGURED", + "PENDING_CONFIRM", + "SYSTEM_CONFIRMED" + ], + "type": "string", + "x-go-enum-desc": "CONFIGURED MaskingConfigStatusConfigured\nPENDING_CONFIRM MaskingConfigStatusPendingConfirm\nSYSTEM_CONFIRMED MaskingConfigStatusSystemConfirmed", + "x-go-name": "MaskingConfigStatus", + "description": "masking config status filters, enum: CONFIGURED/PENDING_CONFIRM", + "name": "masking_config_statuses", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Get masking overview tree successfully", + "schema": { + "$ref": "#/definitions/GetMaskingOverviewTreeReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/rule-configs": { + "put": { + "tags": [ + "Masking" + ], + "summary": "Configure masking rules in batch.", + "operationId": "ConfigureMaskingRules", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "masking rule configurations for batch create or update", + "name": "masking_rule_configs_req", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ConfigureMaskingRulesReq" + } + } + ], + "responses": { + "200": { + "description": "Configure masking rules successfully", + "schema": { + "$ref": "#/definitions/ConfigureMaskingRulesReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks": { + "get": { + "tags": [ + "Masking" + ], + "summary": "List sensitive data discovery tasks.", + "operationId": "ListSensitiveDataDiscoveryTasks", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "example": "20", + "x-go-name": "PageSize", + "description": "the maximum count of tasks to be returned, default is 20", + "name": "page_size", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "example": "0", + "x-go-name": "PageIndex", + "description": "the offset of tasks to be returned, default is 0", + "name": "page_index", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List sensitive data discovery tasks successfully", + "schema": { + "$ref": "#/definitions/ListSensitiveDataDiscoveryTasksReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "Masking" + ], + "summary": "Add sensitive data discovery task.", + "operationId": "AddSensitiveDataDiscoveryTask", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "sensitive data discovery task info", + "name": "task", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddSensitiveDataDiscoveryTaskReq" + } + } + ], + "responses": { + "200": { + "description": "Add sensitive data discovery task successfully", + "schema": { + "$ref": "#/definitions/AddSensitiveDataDiscoveryTaskReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/creatable-db-services": { + "get": { + "tags": [ + "Masking" + ], + "summary": "List db services that can create sensitive data discovery task.", + "operationId": "ListCreatableDBServicesForMaskingTask", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "example": "100", + "x-go-name": "PageSize", + "description": "the maximum count of db services to be returned, default is 100", + "name": "page_size", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "example": "0", + "x-go-name": "PageIndex", + "description": "the offset of db services to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "type": "string", + "example": "\"mysql\"", + "x-go-name": "Keywords", + "description": "fuzzy search keywords for db service name", + "name": "keywords", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List creatable db services for masking task successfully", + "schema": { + "$ref": "#/definitions/ListCreatableDBServicesForMaskingTaskReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/{task_id}": { + "put": { + "tags": [ + "Masking" + ], + "summary": "Update sensitive data discovery task.", + "operationId": "UpdateSensitiveDataDiscoveryTask", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "sensitive data discovery task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "description": "sensitive data discovery task info", + "name": "task", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateSensitiveDataDiscoveryTaskReq" + } + } + ], + "responses": { + "200": { + "description": "Update sensitive data discovery task successfully", + "schema": { + "$ref": "#/definitions/UpdateSensitiveDataDiscoveryTaskReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "Masking" + ], + "summary": "Delete sensitive data discovery task.", + "operationId": "DeleteSensitiveDataDiscoveryTask", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "int64", + "example": 1, + "x-go-name": "TaskID", + "description": "sensitive data discovery task id", + "name": "task_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Delete sensitive data discovery task successfully", + "schema": { + "$ref": "#/definitions/DeleteSensitiveDataDiscoveryTaskReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/{task_id}/histories": { + "get": { + "tags": [ + "Masking" + ], + "summary": "List sensitive data discovery task histories.", + "operationId": "ListSensitiveDataDiscoveryTaskHistories", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "int64", + "example": 1, + "x-go-name": "TaskID", + "description": "sensitive data discovery task id", + "name": "task_id", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "example": "20", + "x-go-name": "PageSize", + "description": "the maximum count of histories to be returned, default is 20", + "name": "page_size", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "example": "0", + "x-go-name": "PageIndex", + "description": "the offset of histories to be returned, default is 0", + "name": "page_index", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List sensitive data discovery task histories successfully", + "schema": { + "$ref": "#/definitions/ListSensitiveDataDiscoveryTaskHistoriesReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/tables/{table_id}/column-masking-details": { + "get": { + "tags": [ + "Masking" + ], + "summary": "Get table column masking details.", + "operationId": "GetTableColumnMaskingDetails", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "int64", + "example": 1, + "x-go-name": "TableID", + "description": "table id from masking overview tree", + "name": "table_id", + "in": "path", + "required": true + }, + { + "type": "string", + "example": "\"phone\"", + "x-go-name": "Keywords", + "description": "fuzzy search keyword for column name", + "name": "keywords", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Get table column masking details successfully", + "schema": { + "$ref": "#/definitions/GetTableColumnMaskingDetailsReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/templates": { + "get": { + "tags": [ + "Masking" + ], + "summary": "List masking templates.", + "operationId": "ListMaskingTemplates", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of masking templates to be returned, default is 20", + "name": "page_size", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of masking templates to be returned, default is 0", + "name": "page_index", + "in": "query" + } + ], + "responses": { + "200": { + "description": "List masking templates successfully", + "schema": { + "$ref": "#/definitions/ListMaskingTemplatesReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "Masking" + ], + "summary": "Add masking template.", + "operationId": "AddMaskingTemplate", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "masking template info", + "name": "masking_template", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddMaskingTemplateReq" + } + } + ], + "responses": { + "200": { + "description": "Add masking template successfully", + "schema": { + "$ref": "#/definitions/AddMaskingTemplateReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/masking/templates/{template_id}": { + "put": { + "tags": [ + "Masking" + ], + "summary": "Update masking template.", + "operationId": "UpdateMaskingTemplate", + "parameters": [ + { + "type": "string", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "masking template id", + "name": "template_id", + "in": "path", + "required": true + }, + { + "description": "masking template info", + "name": "masking_template", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateMaskingTemplateReq" + } + } + ], + "responses": { + "200": { + "description": "Update masking template successfully", + "schema": { + "$ref": "#/definitions/UpdateMaskingTemplateReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "Masking" + ], + "summary": "Delete masking template.", + "operationId": "DeleteMaskingTemplate", + "parameters": [ + { + "type": "string", + "example": "\"project_uid\"", + "x-go-name": "ProjectUid", + "description": "project uid", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "integer", + "format": "int64", + "example": 1, + "x-go-name": "TemplateID", + "description": "masking template id", + "name": "template_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Delete masking template successfully", + "schema": { + "$ref": "#/definitions/DeleteMaskingTemplateReply" + } + }, + "default": { + "description": "Generic error response", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/member_groups": { + "get": { + "tags": [ + "MemberGroup" + ], + "summary": "List member group, for front page.", + "operationId": "ListMemberGroups", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of member to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of members to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name MemberGroupOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname MemberGroupOrderByName", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "filter the user group name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "ListMemberGroupsReply", + "schema": { + "$ref": "#/definitions/ListMemberGroupsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "MemberGroup" + ], + "summary": "Add member group.", + "operationId": "AddMemberGroup", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "Add new member group", + "name": "member_group", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddMemberGroupReq" + } + } + ], + "responses": { + "200": { + "description": "AddMemberGroupReply", + "schema": { + "$ref": "#/definitions/AddMemberGroupReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/member_groups/tips": { + "get": { + "tags": [ + "MemberGroup" + ], + "summary": "List member group tips.", + "operationId": "ListMemberGroupTips", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "ListMemberGroupTipsReply", + "schema": { + "$ref": "#/definitions/ListMemberGroupTipsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/member_groups/{member_group_uid}": { + "get": { + "tags": [ + "MemberGroup" + ], + "summary": "Get member group, for front page.", + "operationId": "GetMemberGroup", + "parameters": [ + { + "type": "string", + "x-go-name": "MemberGroupUid", + "description": "Member group id", + "name": "member_group_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GetMemberGroupReply", + "schema": { + "$ref": "#/definitions/GetMemberGroupReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "put": { + "tags": [ + "MemberGroup" + ], + "summary": "update member group, for front page.", + "operationId": "UpdateMemberGroup", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Member group id", + "name": "member_group_uid", + "in": "path", + "required": true + }, + { + "description": "Update a member group", + "name": "member_group", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateMemberGroupReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "MemberGroup" + ], + "summary": "delete member group, for front page.", + "operationId": "DeleteMemberGroup", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "MemberGroupUid", + "description": "member group id", + "name": "member_group_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/members": { + "get": { + "tags": [ + "Member" + ], + "summary": "List member, for front page.", + "operationId": "ListMembers", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of member to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of members to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "user_uid" + ], + "type": "string", + "x-go-enum-desc": "user_uid MemberOrderByUserUid", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nuser_uid MemberOrderByUserUid", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUserUid", + "description": "filter the member user uid", + "name": "filter_by_user_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "ListMemberReply", + "schema": { + "$ref": "#/definitions/ListMemberReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "Member" + ], + "summary": "Add member.", + "operationId": "AddMember", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "Add new member", + "name": "member", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddMemberReq" + } + } + ], + "responses": { + "200": { + "description": "AddMemberReply", + "schema": { + "$ref": "#/definitions/AddMemberReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/members/internal": { + "get": { + "tags": [ + "Member" + ], + "summary": "List members, for internal backend service.", + "operationId": "ListMembersForInternal", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of member to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of members to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "ListMembersForInternalReply", + "schema": { + "$ref": "#/definitions/ListMembersForInternalReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/members/tips": { + "get": { + "tags": [ + "Member" + ], + "summary": "List member tips.", + "operationId": "ListMemberTips", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "ListMemberTipsReply", + "schema": { + "$ref": "#/definitions/ListMemberTipsReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/members/{member_uid}": { + "put": { + "tags": [ + "Member" + ], + "summary": "Update a member.", + "operationId": "UpdateMember", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Member uid", + "name": "member_uid", + "in": "path", + "required": true + }, + { + "description": "Update a member", + "name": "member", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateMemberReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "Member" + ], + "summary": "Delete a member.", + "operationId": "DelMember", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "MemberUid", + "description": "member uid", + "name": "member_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/projects/{project_uid}/unarchive": { + "put": { + "tags": [ + "Project" + ], + "summary": "Unarchive a project.", + "operationId": "UnarchiveProject", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "Project uid", + "name": "project_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/proxys": { + "post": { + "tags": [ + "DMSProxy" + ], + "summary": "Register dms proxy target.", + "operationId": "RegisterDMSProxyTarget", + "parameters": [ + { + "description": "register dms proxy", + "name": "dms_proxy_target", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/RegisterDMSProxyTargetReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/resource_overview/download": { + "get": { + "tags": [ + "ResourceOverview" + ], + "summary": "download resource overview list csv file.", + "operationId": "DownloadResourceOverviewList", + "parameters": [ + { + "type": "string", + "x-go-name": "FilterByDBType", + "description": "根据数据源类型筛选", + "name": "filter_by_db_type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByBusinessTagUID", + "description": "根据所属业务标签筛选", + "name": "filter_by_business_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByEnvironmentTagUID", + "description": "根据环境属性标签筛选", + "name": "filter_by_environment_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByProjectUID", + "description": "根据所属项目筛选", + "name": "filter_by_project_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzySearchResourceName", + "description": "根据项目或数据源名称模糊搜索", + "name": "fuzzy_search_resource_name", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/DownloadResourceOverviewListRes" + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/resource_overview/resource_list": { + "get": { + "tags": [ + "ResourceOverview" + ], + "summary": "Get resource overview resource list.", + "operationId": "GetResourceOverviewResourceListV1", + "parameters": [ + { + "type": "string", + "x-go-name": "FilterByDBType", + "description": "根据数据源类型筛选", + "name": "filter_by_db_type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByBusinessTagUID", + "description": "根据所属业务标签筛选", + "name": "filter_by_business_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByEnvironmentTagUID", + "description": "根据环境属性标签筛选", + "name": "filter_by_environment_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByProjectUID", + "description": "根据所属项目筛选", + "name": "filter_by_project_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzySearchResourceName", + "description": "根据项目或数据源名称模糊搜索", + "name": "fuzzy_search_resource_name", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "name": "page_index", + "in": "query" + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "name": "page_size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "resource overview resource list response body", + "schema": { + "$ref": "#/definitions/ResourceOverviewResourceListResV1" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/resource_overview/resource_type_distribution": { + "get": { + "tags": [ + "ResourceOverview" + ], + "summary": "Get resource overview resource type distribution.", + "operationId": "GetResourceOverviewResourceTypeDistributionV1", + "responses": { + "200": { + "description": "resource overview resource type distribution response body", + "schema": { + "$ref": "#/definitions/ResourceOverviewResourceTypeDistributionResV1" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/resource_overview/statistics": { + "get": { + "tags": [ + "ResourceOverview" + ], + "summary": "Get resource overview statistics.", + "operationId": "GetResourceOverviewStatisticsV1", + "responses": { + "200": { + "description": "resource overview statistics response body", + "schema": { + "$ref": "#/definitions/ResourceOverviewStatisticsResV1" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/resource_overview/topology": { + "get": { + "tags": [ + "ResourceOverview" + ], + "summary": "Get resource overview topology.", + "operationId": "GetResourceOverviewTopologyV1", + "parameters": [ + { + "type": "string", + "x-go-name": "FilterByDBType", + "description": "根据数据源类型筛选", + "name": "filter_by_db_type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByBusinessTagUID", + "description": "根据所属业务标签筛选", + "name": "filter_by_business_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByEnvironmentTagUID", + "description": "根据环境属性标签筛选", + "name": "filter_by_environment_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByProjectUID", + "description": "根据所属项目筛选", + "name": "filter_by_project_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzySearchResourceName", + "description": "根据项目或数据源名称模糊搜索", + "name": "fuzzy_search_resource_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "resource overview topology response body", + "schema": { + "$ref": "#/definitions/ResourceOverviewTopologyResV1" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/roles": { + "get": { + "tags": [ + "Role" + ], + "summary": "List roles.", + "operationId": "ListRoles", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of role to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of roles to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name RoleOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname RoleOrderByName", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "filter the role name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "the db service fuzzy keyword,include op_permission", + "name": "fuzzy_keyword", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListRoleReply", + "schema": { + "$ref": "#/definitions/ListRoleReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "Role" + ], + "summary": "Add role.", + "operationId": "AddRole", + "parameters": [ + { + "description": "Add new role", + "name": "role", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddRoleReq" + } + } + ], + "responses": { + "200": { + "description": "AddRoleReply", + "schema": { + "$ref": "#/definitions/AddRoleReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/roles/{role_uid}": { + "put": { + "tags": [ + "Role" + ], + "summary": "Update a role.", + "operationId": "UpdateRole", + "parameters": [ + { + "type": "string", + "description": "Role uid", + "name": "role_uid", + "in": "path", + "required": true + }, + { + "description": "Update a role", + "name": "role", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateRoleReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "Role" + ], + "summary": "Delete a role.", + "operationId": "DelRole", + "parameters": [ + { + "type": "string", + "x-go-name": "RoleUid", + "description": "role uid", + "name": "role_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/sessions": { + "post": { + "tags": [ + "Session" + ], + "summary": "Add a session.", + "operationId": "AddSession", + "parameters": [ + { + "description": "Add a new session", + "name": "session", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddSessionReq" + } + } + ], + "responses": { + "200": { + "description": "AddSessionReply", + "schema": { + "$ref": "#/definitions/AddSessionReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "Session" + ], + "summary": "del a session.", + "operationId": "DelSession", + "responses": { + "200": { + "description": "DelSessionReply", + "schema": { + "$ref": "#/definitions/DelSessionReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/sessions/refresh": { + "post": { + "tags": [ + "Session" + ], + "summary": "refresh a session.", + "operationId": "RefreshSession", + "responses": { + "200": { + "description": "RefreshSession reply", + "schema": { + "$ref": "#/definitions/AddSessionReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/sessions/user": { + "get": { + "tags": [ + "Session" + ], + "summary": "Get current user.", + "operationId": "GetUserBySession", + "parameters": [ + { + "type": "string", + "x-go-name": "UserUid", + "name": "user_uid", + "in": "query" + } + ], + "responses": { + "200": { + "description": "GetUserBySessionReply", + "schema": { + "$ref": "#/definitions/GetUserBySessionReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/user_groups": { + "get": { + "tags": [ + "UserGroup" + ], + "summary": "List user groups.", + "operationId": "ListUserGroups", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of user to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of user groups to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name UserGroupOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname UserGroupOrderByName", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "filter the user group name", + "name": "filter_by_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListUserGroupReply", + "schema": { + "$ref": "#/definitions/ListUserGroupReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "UserGroup" + ], + "summary": "Add user group.", + "operationId": "AddUserGroup", + "parameters": [ + { + "description": "Add new user group", + "name": "user_group", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddUserGroupReq" + } + } + ], + "responses": { + "200": { + "description": "AddUserGroupReply", + "schema": { + "$ref": "#/definitions/AddUserGroupReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/user_groups/{user_group_uid}": { + "put": { + "tags": [ + "UserGroup" + ], + "summary": "Update a user group.", + "operationId": "UpdateUserGroup", + "parameters": [ + { + "type": "string", + "description": "UserGroup uid", + "name": "user_group_uid", + "in": "path", + "required": true + }, + { + "description": "Update a user group", + "name": "user_group", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateUserGroupReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "UserGroup" + ], + "summary": "Delete a user group.", + "operationId": "DelUserGroup", + "parameters": [ + { + "type": "string", + "x-go-name": "UserGroupUid", + "description": "user group uid", + "name": "user_group_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/users": { + "get": { + "tags": [ + "User" + ], + "summary": "List users.", + "operationId": "ListUsers", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of user to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of users to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name UserOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname UserOrderByName", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "filter the user name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUids", + "description": "filter the user uids", + "name": "filter_by_uids", + "in": "query" + }, + { + "type": "boolean", + "x-go-name": "FilterDeletedUser", + "description": "filter deleted user to be return ,default is false", + "name": "filter_del_user", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "fuzzy keyword", + "name": "fuzzy_keyword", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByEmail", + "description": "filter the user email", + "name": "filter_by_email", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByPhone", + "description": "filter the user phone", + "name": "filter_by_phone", + "in": "query" + }, + { + "enum": [ + "Normal", + "Disabled" + ], + "type": "string", + "x-go-enum-desc": "Normal UserStatFilterNormal\nDisabled UserStatFilterDisabled", + "x-go-name": "FilterByStat", + "description": "filter the user stat (0: normal, 1: disabled)\nNormal UserStatFilterNormal\nDisabled UserStatFilterDisabled", + "name": "filter_by_stat", + "in": "query" + }, + { + "enum": [ + "ldap", + "dms", + "oauth2", + "unknown" + ], + "type": "string", + "x-go-enum-desc": "ldap UserAuthenticationTypeLDAP\ndms UserAuthenticationTypeDMS\noauth2 UserAuthenticationTypeOAUTH2\nunknown UserAuthenticationTypeUnknown", + "x-go-name": "FilterByAuthenticationType", + "description": "filter the user authentication type (ldap, dms, oauth2)\nldap UserAuthenticationTypeLDAP\ndms UserAuthenticationTypeDMS\noauth2 UserAuthenticationTypeOAUTH2\nunknown UserAuthenticationTypeUnknown", + "name": "filter_by_authentication_type", + "in": "query" + }, + { + "enum": [ + "WORKBENCH", + "MANAGEMENT" + ], + "type": "string", + "x-go-enum-desc": "WORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "x-go-name": "FilterBySystem", + "description": "filter the user system (WORKBENCH, MANAGEMENT)\nWORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "name": "filter_by_system", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListUserReply", + "schema": { + "$ref": "#/definitions/ListUserReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "put": { + "tags": [ + "User" + ], + "summary": "Update current user.", + "operationId": "UpdateCurrentUser", + "parameters": [ + { + "description": "Update current user", + "name": "current_user", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateCurrentUserReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "User" + ], + "summary": "Add user.", + "operationId": "AddUser", + "parameters": [ + { + "description": "Add new user", + "name": "user", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddUserReq" + } + } + ], + "responses": { + "200": { + "description": "AddUserReply", + "schema": { + "$ref": "#/definitions/AddUserReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/users/gen_token": { + "post": { + "tags": [ + "User" + ], + "summary": "Gen user access token.", + "operationId": "GenAccessToken", + "parameters": [ + { + "name": "expiration_days", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/GenAccessToken" + } + } + ], + "responses": { + "200": { + "description": "GenAccessTokenReply", + "schema": { + "$ref": "#/definitions/GenAccessTokenReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/users/verify_user_login": { + "post": { + "tags": [ + "User" + ], + "summary": "Verify user login.", + "operationId": "VerifyUserLogin", + "parameters": [ + { + "description": "Add a new session", + "name": "session", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddSessionReq" + } + } + ], + "responses": { + "200": { + "description": "VerifyUserLoginReply", + "schema": { + "$ref": "#/definitions/VerifyUserLoginReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/users/{user_uid}": { + "get": { + "tags": [ + "User" + ], + "summary": "Get user info, This API is used by other component such as sqle\u0026auth to get user info.", + "operationId": "GetUser", + "parameters": [ + { + "type": "string", + "x-go-name": "UserUid", + "description": "user uid", + "name": "user_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GetUserReply", + "schema": { + "$ref": "#/definitions/GetUserReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "put": { + "tags": [ + "User" + ], + "summary": "Update a user.", + "operationId": "UpdateUser", + "parameters": [ + { + "type": "string", + "description": "User uid", + "name": "user_uid", + "in": "path", + "required": true + }, + { + "description": "Update a user", + "name": "user", + "in": "body", + "schema": { + "$ref": "#/definitions/UpdateUserReq" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "delete": { + "tags": [ + "User" + ], + "summary": "Delete a user.", + "operationId": "DelUser", + "parameters": [ + { + "type": "string", + "x-go-name": "UserUid", + "description": "user uid", + "name": "user_uid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/users/{user_uid}/op_permission": { + "get": { + "tags": [ + "User" + ], + "summary": "Get user op permission info, This API is used by other component such as sqle\u0026auth to check user permissions.", + "operationId": "GetUserOpPermission", + "parameters": [ + { + "type": "string", + "x-go-name": "UserUid", + "description": "user uid", + "name": "user_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "name": "project_uid", + "in": "query" + }, + { + "x-go-name": "UserOpPermission", + "description": "user op permission info", + "name": "user_op_permission", + "in": "body", + "schema": { + "$ref": "#/definitions/UserOpPermission" + } + } + ], + "responses": { + "200": { + "description": "GetUserOpPermissionReply", + "schema": { + "$ref": "#/definitions/GetUserOpPermissionReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v1/dms/webhooks": { + "post": { + "tags": [ + "Webhook" + ], + "summary": "webhook send message.", + "operationId": "WebHookSendMessage", + "parameters": [ + { + "description": "webhooks", + "name": "webhook_message", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/WebHookSendMessageReq" + } + } + ], + "responses": { + "200": { + "description": "WebHookSendMessageReply", + "schema": { + "$ref": "#/definitions/WebHookSendMessageReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/db_services": { + "get": { + "description": "list global DBServices", + "tags": [ + "DBService" + ], + "operationId": "ListGlobalDBServicesV2", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of db service to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of users to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name DBServiceOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname DBServiceOrderByName", + "name": "order_by", + "in": "query" + }, + { + "enum": [ + "connect_success", + "connect_failed" + ], + "type": "string", + "x-go-name": "FilterLastConnectionTestStatus", + "description": "the db service connection", + "name": "filter_last_connection_test_status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByEnvironmentTagUID", + "description": "filter db services by environment tag", + "name": "filter_by_environment_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByHost", + "description": "the db service host", + "name": "filter_by_host", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUID", + "description": "the db service uid", + "name": "filter_by_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "the db service name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByPort", + "description": "the db service port", + "name": "filter_by_port", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDBType", + "description": "the db service db type", + "name": "filter_by_db_type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByProjectUid", + "description": "the db service project id", + "name": "filter_by_project_uid", + "in": "query" + }, + { + "type": "boolean", + "x-go-name": "FilterByIsEnableMasking", + "description": "is masking", + "name": "filter_by_is_enable_masking", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "the db service fuzzy keyword", + "name": "fuzzy_keyword", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListGlobalDBServicesReplyV2", + "schema": { + "$ref": "#/definitions/ListGlobalDBServicesReplyV2" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects": { + "get": { + "tags": [ + "Project" + ], + "summary": "List projects.", + "operationId": "ListProjectsV2", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of Project to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of Projects to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name ProjectOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname ProjectOrderByName", + "name": "order_by", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "filter the Project name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUID", + "description": "filter the Project UID", + "name": "filter_by_uid", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "FilterByProjectUids", + "description": "filter project by project id list, using in condition", + "name": "filter_by_project_uids", + "in": "query" + }, + { + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "type": "string", + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "FilterByProjectPriority", + "description": "filter project by project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "name": "filter_by_project_priority", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByBusinessTag", + "description": "filter project by business tag", + "name": "filter_by_business_tag", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDesc", + "description": "filter the Project By Project description", + "name": "filter_by_desc", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "fuzzy keyword", + "name": "fuzzy_keyword", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListProjectReplyV2", + "schema": { + "$ref": "#/definitions/ListProjectReplyV2" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "Project" + ], + "summary": "Add project.", + "operationId": "AddProjectV2", + "parameters": [ + { + "description": "Add new Project", + "name": "project", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddProjectReqV2" + } + } + ], + "responses": { + "200": { + "description": "AddProjectReplyV2", + "schema": { + "$ref": "#/definitions/AddProjectReplyV2" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects/import": { + "post": { + "tags": [ + "Project" + ], + "summary": "Import projects.", + "operationId": "ImportProjectsV2", + "parameters": [ + { + "description": "import projects", + "name": "projects", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ImportProjectsReqV2" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects/import_db_services": { + "post": { + "tags": [ + "Project" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfProjectsV2", + "parameters": [ + { + "description": "new db services", + "name": "db_services", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ImportDBServicesOfProjectsReqV2" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects/import_db_services_check": { + "post": { + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json", + "text/csv" + ], + "tags": [ + "Project" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfProjectsCheckV2", + "parameters": [ + { + "type": "file", + "x-go-name": "DBServicesFile", + "description": "DBServices file.", + "name": "db_services_file", + "in": "formData" + } + ], + "responses": { + "200": { + "$ref": "#/responses/ImportDBServicesCheckCsvReply" + }, + "default": { + "description": "ImportDBServicesCheckReply", + "schema": { + "$ref": "#/definitions/ImportDBServicesCheckReply" + } + } + } + } + }, + "/v2/dms/projects/preview_import": { + "post": { + "consumes": [ + "multipart/form-data" + ], + "tags": [ + "Project" + ], + "summary": "Preview import projects.", + "operationId": "PreviewImportProjectsV2", + "parameters": [ + { + "type": "file", + "x-go-name": "ProjectsFile", + "description": "projects file.", + "name": "projects_file", + "in": "formData" + } + ], + "responses": { + "200": { + "description": "PreviewImportProjectsReplyV2", + "schema": { + "$ref": "#/definitions/PreviewImportProjectsReplyV2" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects/{project_uid}": { + "put": { + "tags": [ + "Project" + ], + "summary": "update a project.", + "operationId": "UpdateProjectV2", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "Update a project", + "name": "project", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateProjectReqV2" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects/{project_uid}/db_services": { + "get": { + "tags": [ + "DBService" + ], + "summary": "List db service.", + "operationId": "ListDBServicesV2", + "parameters": [ + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageSize", + "description": "the maximum count of db service to be returned", + "name": "page_size", + "in": "query", + "required": true + }, + { + "type": "integer", + "format": "uint32", + "x-go-name": "PageIndex", + "description": "the offset of users to be returned, default is 0", + "name": "page_index", + "in": "query" + }, + { + "enum": [ + "name" + ], + "type": "string", + "x-go-enum-desc": "name DBServiceOrderByName", + "x-go-name": "OrderBy", + "description": "Multiple of [\"name\"], default is [\"name\"]\nname DBServiceOrderByName", + "name": "order_by", + "in": "query" + }, + { + "enum": [ + "connect_success", + "connect_failed" + ], + "type": "string", + "x-go-name": "FilterLastConnectionTestStatus", + "description": "the db service connection", + "name": "filter_last_connection_test_status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByHost", + "description": "the db service host", + "name": "filter_by_host", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByUID", + "description": "the db service uid", + "name": "filter_by_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByName", + "description": "the db service name", + "name": "filter_by_name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByPort", + "description": "the db service port", + "name": "filter_by_port", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByDBType", + "description": "the db service db type", + "name": "filter_by_db_type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "FilterByDBServiceIds", + "description": "filter db services by db service id list using in condition", + "name": "filter_by_db_service_ids", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FilterByEnvironmentTagUID", + "description": "filter db services by environment tag", + "name": "filter_by_environment_tag_uid", + "in": "query" + }, + { + "type": "string", + "x-go-name": "FuzzyKeyword", + "description": "the db service fuzzy keyword,include host/port", + "name": "fuzzy_keyword", + "in": "query" + }, + { + "type": "boolean", + "x-go-name": "IsEnableMasking", + "description": "is masking", + "name": "is_enable_masking", + "in": "query" + } + ], + "responses": { + "200": { + "description": "ListDBServiceReplyV2", + "schema": { + "$ref": "#/definitions/ListDBServiceReplyV2" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + }, + "post": { + "tags": [ + "DBService" + ], + "summary": "Add DB Service.", + "operationId": "AddDBServiceV2", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "Add new db service", + "name": "db_service", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/AddDBServiceReqV2" + } + } + ], + "responses": { + "200": { + "description": "AddDBServiceReply", + "schema": { + "$ref": "#/definitions/AddDBServiceReply" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects/{project_uid}/db_services/import": { + "post": { + "tags": [ + "DBService" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfOneProjectV2", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "description": "new db services", + "name": "db_services", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ImportDBServicesOfOneProjectReqV2" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + }, + "/v2/dms/projects/{project_uid}/db_services/import_check": { + "post": { + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json", + "text/csv" + ], + "tags": [ + "DBService" + ], + "summary": "Import DBServices.", + "operationId": "ImportDBServicesOfOneProjectCheckV2", + "parameters": [ + { + "type": "string", + "x-go-name": "ProjectUid", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "file", + "x-go-name": "DBServicesFile", + "description": "DBServices file.", + "name": "db_services_file", + "in": "formData" + } + ], + "responses": { + "200": { + "$ref": "#/responses/ImportDBServicesCheckCsvReply" + }, + "default": { + "description": "ImportDBServicesCheckReply", + "schema": { + "$ref": "#/definitions/ImportDBServicesCheckReply" + } + } + } + } + }, + "/v2/dms/projects/{project_uid}/db_services/{db_service_uid}": { + "put": { + "tags": [ + "DBService" + ], + "summary": "update a DB Service.", + "operationId": "UpdateDBServiceV2", + "parameters": [ + { + "type": "string", + "description": "project id", + "name": "project_uid", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "db_service_uid id", + "name": "db_service_uid", + "in": "path", + "required": true + }, + { + "description": "Update a DB service", + "name": "db_service", + "in": "body", + "schema": { + "$ref": "#/definitions/UpdateDBServiceReqV2" + } + } + ], + "responses": { + "200": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + }, + "default": { + "description": "GenericResp", + "schema": { + "$ref": "#/definitions/GenericResp" + } + } + } + } + } + }, + "definitions": { + "AccessTokenInfo": { + "type": "object", + "properties": { + "access_token": { + "type": "string", + "x-go-name": "AccessToken" + }, + "is_expired": { + "type": "boolean", + "x-go-name": "IsExpired" + }, + "token_expired_timestamp": { + "type": "string", + "x-go-name": "ExpiredTime" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "AddDBServiceReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add db service reply", + "type": "object", + "properties": { + "uid": { + "description": "db service UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddDBServiceReq": { + "type": "object", + "properties": { + "db_service": { + "$ref": "#/definitions/DBService" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddDBServiceReqV2": { + "type": "object", + "properties": { + "db_service": { + "$ref": "#/definitions/DBServiceV2" + } + }, + "x-go-name": "AddDBServiceReq", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "AddDBServiceSyncTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "add database source service reply", + "type": "object", + "properties": { + "uid": { + "description": "db service UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddDBServiceSyncTaskReq": { + "type": "object", + "properties": { + "db_service_sync_task": { + "$ref": "#/definitions/DBServiceSyncTask" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddDataExportTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "add data export workflow reply", + "type": "object", + "properties": { + "data_export_task_uids": { + "description": "data export task UIDs", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Uids" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddDataExportTaskReq": { + "type": "object", + "properties": { + "data_export_tasks": { + "type": "array", + "items": { + "$ref": "#/definitions/DataExportTask" + }, + "x-go-name": "DataExportTasks" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddDataExportWorkflowReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "add data export workflow reply", + "type": "object", + "properties": { + "export_data_workflow_uid": { + "description": "data export workflow UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddDataExportWorkflowReq": { + "type": "object", + "properties": { + "data_export_workflow": { + "$ref": "#/definitions/DataExportWorkflow" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddGatewayReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddGatewayReq": { + "type": "object", + "properties": { + "add_gateway": { + "$ref": "#/definitions/Gateway" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddMaskingTemplate": { + "type": "object", + "required": [ + "name", + "rule_ids" + ], + "properties": { + "name": { + "description": "masking template name", + "type": "string", + "x-go-name": "Name", + "example": "\"New Template\"" + }, + "rule_ids": { + "description": "masking rule id list", + "type": "array", + "minLength": 1, + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "RuleIDs", + "example": [ + 1, + 2, + 3 + ] + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddMaskingTemplateReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddMaskingTemplateReq": { + "type": "object", + "required": [ + "masking_template" + ], + "properties": { + "masking_template": { + "$ref": "#/definitions/AddMaskingTemplate" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddMemberGroupReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add member group reply", + "type": "object", + "properties": { + "id": { + "description": "member group ID", + "type": "string", + "x-go-name": "Id" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddMemberGroupReq": { + "type": "object", + "properties": { + "member_group": { + "$ref": "#/definitions/MemberGroup" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddMemberReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add member reply", + "type": "object", + "properties": { + "uid": { + "description": "member UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddMemberReq": { + "type": "object", + "properties": { + "member": { + "$ref": "#/definitions/Member" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddOperationRecordReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddOperationRecordReq": { + "type": "object", + "properties": { + "operation_record": { + "$ref": "#/definitions/OperationRecord" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddProjectReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add Project reply", + "type": "object", + "properties": { + "uid": { + "description": "Project UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddProjectReplyV2": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add Project reply", + "type": "object", + "properties": { + "uid": { + "description": "Project UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-name": "AddProjectReply", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "AddProjectReq": { + "type": "object", + "properties": { + "project": { + "$ref": "#/definitions/ProjectV1" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddProjectReqV2": { + "type": "object", + "properties": { + "project": { + "$ref": "#/definitions/ProjectV2" + } + }, + "x-go-name": "AddProjectReq", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "AddRoleReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add role reply", + "type": "object", + "properties": { + "uid": { + "description": "role UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddRoleReq": { + "type": "object", + "properties": { + "role": { + "$ref": "#/definitions/Role" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddSensitiveDataDiscoveryTask": { + "type": "object", + "required": [ + "db_service_uid", + "masking_template_id", + "identification_method", + "execution_plan" + ], + "properties": { + "cron_expression": { + "description": "cron expression, required when execution_plan is PERIODIC", + "type": "string", + "x-go-name": "CronExpression", + "example": "\"0 0 * * *\"" + }, + "db_service_uid": { + "description": "database instance id", + "type": "string", + "x-go-name": "DBServiceUID", + "example": "\"1\"" + }, + "execution_plan": { + "description": "execution plan\nPERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "type": "string", + "enum": [ + "PERIODIC", + "ONE_TIME" + ], + "x-go-enum-desc": "PERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "x-go-name": "ExecutionPlan", + "example": "\"ONE_TIME\"" + }, + "identification_method": { + "description": "sensitive data identification method\nBY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName\nBY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData", + "type": "string", + "enum": [ + "BY_FIELD_NAME", + "BY_SAMPLE_DATA" + ], + "x-go-enum-desc": "BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName\nBY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData", + "x-go-name": "IdentificationMethod", + "example": "\"BY_FIELD_NAME\"" + }, + "is_periodic_scan_enabled": { + "description": "whether periodic scanning is enabled, default is true", + "type": "boolean", + "x-go-name": "IsPeriodicScanEnabled", + "example": true + }, + "masking_template_id": { + "description": "masking template id", + "type": "integer", + "format": "int64", + "x-go-name": "MaskingTemplateID", + "example": 1 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddSensitiveDataDiscoveryTaskData": { + "type": "object", + "properties": { + "suspected_sensitive_fields_tree": { + "$ref": "#/definitions/SuspectedSensitiveFieldsTree" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddSensitiveDataDiscoveryTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/AddSensitiveDataDiscoveryTaskData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddSensitiveDataDiscoveryTaskReq": { + "type": "object", + "required": [ + "task" + ], + "properties": { + "task": { + "$ref": "#/definitions/AddSensitiveDataDiscoveryTask" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddSession": { + "description": "Use this struct to add a new session", + "type": "object", + "required": [ + "username", + "password" + ], + "properties": { + "password": { + "description": "User password", + "type": "string", + "x-go-name": "Password" + }, + "username": { + "description": "User name", + "type": "string", + "x-go-name": "UserName" + }, + "verify_code": { + "description": "VerifyCode", + "type": "string", + "x-go-name": "VerifyCode" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddSessionReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add user reply", + "type": "object", + "properties": { + "message": { + "description": "Message", + "type": "string", + "x-go-name": "Message" + }, + "token": { + "description": "Session token", + "type": "string", + "x-go-name": "Token" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddSessionReq": { + "type": "object", + "properties": { + "session": { + "$ref": "#/definitions/AddSession" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddUserGroupReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add user group reply", + "type": "object", + "properties": { + "uid": { + "description": "user group UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddUserGroupReq": { + "type": "object", + "properties": { + "user_group": { + "$ref": "#/definitions/UserGroup" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddUserReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Add user reply", + "type": "object", + "properties": { + "uid": { + "description": "user UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AddUserReq": { + "type": "object", + "properties": { + "user": { + "$ref": "#/definitions/User" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AdditionalParam": { + "type": "object", + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "type": { + "type": "string", + "x-go-name": "Type" + }, + "value": { + "type": "string", + "x-go-name": "Value" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "AuditPlanTypes": { + "type": "object", + "properties": { + "audit_plan_id": { + "type": "integer", + "format": "uint64", + "x-go-name": "AuditPlanId" + }, + "desc": { + "type": "string", + "x-go-name": "AuditPlanTypeDesc" + }, + "type": { + "type": "string", + "x-go-name": "AuditPlanType" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "AuditSQLResult": { + "type": "object", + "properties": { + "db_type": { + "type": "string", + "x-go-name": "DBType" + }, + "error_info": { + "type": "string", + "x-go-name": "ErrorInfo" + }, + "execution_failed": { + "type": "boolean", + "x-go-name": "ExecutionFailed" + }, + "level": { + "type": "string", + "x-go-name": "Level" + }, + "message": { + "type": "string", + "x-go-name": "Message" + }, + "rule_name": { + "type": "string", + "x-go-name": "RuleName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "AuditTaskResult": { + "description": "SQL审核结果", + "type": "object", + "properties": { + "audit_level": { + "type": "string", + "x-go-name": "AuditLevel" + }, + "pass_rate": { + "type": "number", + "format": "double", + "x-go-name": "PassRate" + }, + "score": { + "type": "integer", + "format": "int32", + "x-go-name": "Score" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "BasicInfo": { + "type": "object", + "properties": { + "components": { + "type": "array", + "items": { + "$ref": "#/definitions/ComponentNameWithVersion" + }, + "x-go-name": "Components" + }, + "logo_url": { + "type": "string", + "x-go-name": "LogoUrl" + }, + "title": { + "type": "string", + "x-go-name": "Title" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "BatchGetDataExportTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/GetDataExportTask" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "BindOauth2UserReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/BindOauth2UserResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "BindOauth2UserReq": { + "type": "object", + "properties": { + "oauth2_token": { + "type": "string", + "x-go-name": "Oauth2Token" + }, + "pwd": { + "type": "string", + "x-go-name": "Pwd" + }, + "refresh_token": { + "type": "string", + "x-go-name": "RefreshToken" + }, + "user_name": { + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "BindOauth2UserResData": { + "type": "object", + "properties": { + "token": { + "type": "string", + "x-go-name": "Token" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Business": { + "type": "object", + "properties": { + "id": { + "type": "string", + "x-go-name": "Id" + }, + "is_used": { + "type": "boolean", + "x-go-name": "IsUsed" + }, + "name": { + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "BusinessForUpdate": { + "type": "object", + "properties": { + "id": { + "type": "string", + "x-go-name": "ID" + }, + "name": { + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "BusinessTag": { + "type": "object", + "properties": { + "name": { + "description": "业务标签最多50个字符", + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "UID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "BusinessTagCommon": { + "type": "object", + "properties": { + "name": { + "description": "业务标签最多50个字符", + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "UID" + } + }, + "x-go-name": "BusinessTag", + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + }, + "CBOperationLog": { + "type": "object", + "properties": { + "audit_result": { + "type": "array", + "items": { + "$ref": "#/definitions/AuditSQLResult" + }, + "x-go-name": "AuditResult" + }, + "db_service": { + "$ref": "#/definitions/UidWithDBServiceName" + }, + "exec_result": { + "type": "string", + "x-go-name": "ExecResult" + }, + "exec_time_second": { + "type": "integer", + "format": "int64", + "x-go-name": "ExecTimeSecond" + }, + "operation": { + "$ref": "#/definitions/Operation" + }, + "operation_ip": { + "type": "string", + "x-go-name": "OperationIp" + }, + "operation_person": { + "$ref": "#/definitions/UidWithName" + }, + "operation_time": { + "type": "string", + "format": "date-time", + "x-go-name": "OperationTime" + }, + "result_set_row_count": { + "type": "integer", + "format": "int64", + "x-go-name": "ResultSetRowCount" + }, + "session_id": { + "type": "string", + "x-go-name": "SessionID" + }, + "uid": { + "type": "string", + "x-go-name": "UID" + }, + "workflow_id": { + "type": "string", + "x-go-name": "WorkflowID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CBOperationLogTips": { + "type": "object", + "properties": { + "exec_result": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ExecResult" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CancelDataExportWorkflowPayload": { + "type": "object", + "required": [ + "data_export_workflow_uids" + ], + "properties": { + "data_export_workflow_uids": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "DataExportWorkflowUids" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CancelDataExportWorkflowReq": { + "type": "object", + "properties": { + "payload": { + "$ref": "#/definitions/CancelDataExportWorkflowPayload" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServiceIsConnectableByIdReq": { + "type": "object", + "properties": { + "db_service_uid": { + "type": "string", + "x-go-name": "DBServiceUid" + }, + "project_uid": { + "type": "string", + "x-go-name": "ProjectUid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServiceIsConnectableReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/CheckDBServiceIsConnectableReplyItem" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServiceIsConnectableReplyItem": { + "type": "object", + "properties": { + "component": { + "type": "string", + "x-go-name": "Component" + }, + "connect_error_message": { + "type": "string", + "x-go-name": "ConnectErrorMessage" + }, + "is_connectable": { + "type": "boolean", + "x-go-name": "IsConnectable" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServiceIsConnectableReq": { + "type": "object", + "properties": { + "db_service": { + "$ref": "#/definitions/CheckDbConnectable" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServicesIsConnectableReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/DBServiceIsConnectableReply" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServicesIsConnectableReq": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/DbServiceConnections" + }, + "x-go-name": "DBServices" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServicesPrivilegesItem": { + "type": "object", + "properties": { + "CheckDBServicesPrivileges": { + "type": "array", + "items": { + "$ref": "#/definitions/CheckDBServiceIsConnectableReplyItem" + } + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServicesPrivilegesReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/CheckDBServicesPrivilegesItem" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDBServicesPrivilegesReq": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/CheckDbConnectable" + }, + "x-go-name": "DBServices" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckDbConnectable": { + "type": "object", + "required": [ + "db_type", + "user", + "host", + "port", + "password" + ], + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "db_type": { + "description": "DB Service type", + "type": "string", + "x-go-name": "DBType", + "example": "MySQL" + }, + "host": { + "description": "DB Service host", + "type": "string", + "x-go-name": "Host", + "example": "127.0.0.1" + }, + "password": { + "description": "DB Service admin password", + "type": "string", + "x-go-name": "Password", + "example": "123456" + }, + "port": { + "description": "DB Service port", + "type": "string", + "x-go-name": "Port", + "example": "3306" + }, + "user": { + "description": "DB Service admin user", + "type": "string", + "x-go-name": "User", + "example": "root" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "CheckDbsConnectable": { + "type": "object", + "required": [ + "name", + "db_type", + "user", + "host", + "port", + "password" + ], + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "db_type": { + "description": "DB Service type", + "type": "string", + "x-go-name": "DBType", + "example": "MySQL" + }, + "host": { + "description": "DB Service host", + "type": "string", + "x-go-name": "Host", + "example": "127.0.0.1" + }, + "name": { + "description": "DB Service name", + "type": "string", + "x-go-name": "Name", + "example": "mysql_1" + }, + "password": { + "description": "DB Service admin password", + "type": "string", + "x-go-name": "Password", + "example": "123456" + }, + "port": { + "description": "DB Service port", + "type": "string", + "x-go-name": "Port", + "example": "3306" + }, + "user": { + "description": "DB Service admin user", + "type": "string", + "x-go-name": "User", + "example": "root" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CheckLicenseReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "content": { + "type": "string", + "x-go-name": "Content" + }, + "license": { + "type": "array", + "items": { + "$ref": "#/definitions/LicenseItem" + }, + "x-go-name": "License" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CompanyNotice": { + "description": "A companynotice", + "type": "object", + "properties": { + "create_user_name": { + "description": "companynotice creator name", + "type": "string", + "x-go-name": "CreateUserName" + }, + "expire_time": { + "description": "notice expire time", + "type": "string", + "format": "date-time", + "x-go-name": "ExpireTime" + }, + "notice_str": { + "description": "companynotice info", + "type": "string", + "x-go-name": "NoticeStr" + }, + "read_by_current_user": { + "description": "current user has been read", + "type": "boolean", + "x-go-name": "ReadByCurrentUser" + }, + "start_time": { + "description": "notice show start time", + "type": "string", + "format": "date-time", + "x-go-name": "StartTime" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ComponentNameWithVersion": { + "type": "object", + "properties": { + "name": { + "type": "string", + "x-go-name": "Name" + }, + "version": { + "type": "string", + "x-go-name": "Version" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ConfigureMaskingRulesReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ConfigureMaskingRulesReq": { + "type": "object", + "required": [ + "masking_rule_configs" + ], + "properties": { + "masking_rule_configs": { + "description": "masking rule configurations for batch create or update", + "type": "array", + "minLength": 1, + "items": { + "$ref": "#/definitions/MaskingRuleConfig" + }, + "x-go-name": "MaskingRuleConfigs" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CreateBusinessTagReq": { + "type": "object", + "properties": { + "business_tag": { + "$ref": "#/definitions/BusinessTag" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CreateEnvironmentTagReq": { + "type": "object", + "properties": { + "environment_name": { + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "CurrentProjectAdmin": { + "type": "object", + "properties": { + "is_admin": { + "type": "boolean", + "x-go-name": "IsAdmin" + }, + "member_groups": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "MemberGroups" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBService": { + "description": "A db service", + "type": "object", + "required": [ + "name", + "db_type", + "host", + "port", + "user", + "password", + "business", + "maintenance_times" + ], + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "backup_max_rows": { + "description": "backup switch", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "business": { + "description": "DB Service business name", + "type": "string", + "x-go-name": "Business" + }, + "db_type": { + "description": "Service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "Service description", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "host": { + "description": "DB Service Host", + "type": "string", + "x-go-name": "Host" + }, + "maintenance_times": { + "description": "DB Service maintenance time\nempty value means that maintenance time is unlimited", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "Service name", + "type": "string", + "x-go-name": "Name" + }, + "password": { + "description": "DB Service admin password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "DB Service port", + "type": "string", + "x-go-name": "Port" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "user": { + "description": "DB Service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServiceConnectionReq": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/CheckDbsConnectable" + }, + "x-go-name": "DBServices" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServiceIsConnectableReply": { + "type": "object", + "properties": { + "connect_error_message": { + "type": "string", + "x-go-name": "ConnectErrorMessage" + }, + "connection_status": { + "type": "string", + "enum": [ + "connect_success", + "connect_failed" + ], + "x-go-enum-desc": "connect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "x-go-name": "ConnectionStatus" + }, + "db_service_uid": { + "type": "string", + "x-go-name": "DBServiceUid" + }, + "test_connection_time": { + "type": "string", + "format": "date-time", + "x-go-name": "TestConnectionTime" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServiceSourceName": { + "type": "string", + "x-go-package": "github.com/actiontech/dms/internal/dms/pkg/constant" + }, + "DBServiceSyncTask": { + "type": "object", + "required": [ + "name", + "source", + "url", + "db_type", + "cron_express" + ], + "properties": { + "additional_params": { + "$ref": "#/definitions/Params" + }, + "cron_express": { + "description": "cron expression", + "type": "string", + "x-go-name": "CronExpress", + "example": "0 0 * * *" + }, + "db_type": { + "description": "database type", + "type": "string", + "x-go-name": "DbType", + "example": "MySQL" + }, + "name": { + "description": "name", + "type": "string", + "x-go-name": "Name", + "example": "dmp" + }, + "source": { + "description": "source", + "type": "string", + "x-go-name": "Source", + "example": "actiontech-dmp" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "url": { + "description": "addr", + "type": "string", + "x-go-name": "URL", + "example": "http://10.186.62.56:10000" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServiceSyncTaskTip": { + "type": "object", + "properties": { + "db_type": { + "type": "array", + "items": { + "$ref": "#/definitions/DBType" + }, + "x-go-name": "DBType" + }, + "description": { + "type": "string", + "x-go-name": "Desc" + }, + "params": { + "$ref": "#/definitions/Params" + }, + "service_source_name": { + "$ref": "#/definitions/DBServiceSourceName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServiceUidWithNameInfo": { + "type": "object", + "properties": { + "DBServiceName": { + "type": "string" + }, + "DBServiceUid": { + "type": "string" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "DBServiceV2": { + "type": "object", + "required": [ + "name", + "db_type", + "host", + "port", + "user", + "password", + "environment_tag_uid", + "maintenance_times" + ], + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "backup_max_rows": { + "description": "backup switch", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "db_type": { + "description": "Service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "Service description", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "environment_tag_uid": { + "description": "DB Service environment tag", + "type": "string", + "x-go-name": "EnvironmentTagUID" + }, + "host": { + "description": "DB Service Host", + "type": "string", + "x-go-name": "Host" + }, + "maintenance_times": { + "description": "DB Service maintenance time\nempty value means that maintenance time is unlimited", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "Service name", + "type": "string", + "x-go-name": "Name" + }, + "password": { + "description": "DB Service admin password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "DB Service port", + "type": "string", + "x-go-name": "Port" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "user": { + "description": "DB Service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-name": "DBService", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "DBServicesConnectionItem": { + "type": "object", + "properties": { + "failed_names": { + "description": "Failed DBServices name", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "FailedNames" + }, + "failed_num": { + "description": "Failed connection num", + "type": "integer", + "format": "int64", + "x-go-name": "FailedNum" + }, + "successful_num": { + "description": "Successful connection num", + "type": "integer", + "format": "int64", + "x-go-name": "SuccessfulNum" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServicesConnectionReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/DBServicesConnectionItem" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServicesConnectionReq": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/DbServiceConnections" + }, + "x-go-name": "DBServices" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBServicesConnectionReqReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/DBServiceIsConnectableReply" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DBType": { + "type": "string", + "x-go-package": "github.com/actiontech/dms/internal/dms/pkg/constant" + }, + "DMSProxyTarget": { + "description": "A dms proxy target", + "type": "object", + "required": [ + "name", + "addr", + "version", + "proxy_url_prefixs" + ], + "properties": { + "addr": { + "description": "target addr, eg: http://10.1.2.1:5432", + "type": "string", + "x-go-name": "Addr" + }, + "name": { + "description": "target name", + "type": "string", + "x-go-name": "Name" + }, + "proxy_url_prefixs": { + "description": "url prefix that need to be proxy, eg: /v1/user", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ProxyUrlPrefixs" + }, + "scenario": { + "description": "the scenario is used to differentiate scenarios\ninternal_service ProxyScenarioInternalService\nthrid_party_integrate ProxyScenarioThirdPartyIntegrate", + "type": "string", + "enum": [ + "internal_service", + "thrid_party_integrate" + ], + "x-go-enum-desc": "internal_service ProxyScenarioInternalService\nthrid_party_integrate ProxyScenarioThirdPartyIntegrate", + "x-go-name": "Scenario" + }, + "version": { + "description": "version number", + "type": "string", + "x-go-name": "Version" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "DataExportTask": { + "type": "object", + "required": [ + "db_service_uid" + ], + "properties": { + "database_name": { + "description": "DB Service name", + "type": "string", + "x-go-name": "DatabaseName" + }, + "db_service_uid": { + "description": "DB Service uid", + "type": "string", + "x-go-name": "DBServiceUid" + }, + "export_sql": { + "description": "The exported SQL statement executed. it's necessary when ExportType is SQL\nSELECT * FROM DMS_test LIMIT 20;", + "type": "string", + "x-go-name": "ExportSQL" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DataExportWorkflow": { + "type": "object", + "required": [ + "name", + "tasks" + ], + "properties": { + "desc": { + "description": "desc", + "type": "string", + "x-go-name": "Desc", + "example": "transaction data export" + }, + "name": { + "description": "name", + "type": "string", + "x-go-name": "Name", + "example": "d1" + }, + "tasks": { + "description": "export task info", + "type": "array", + "items": { + "$ref": "#/definitions/Task" + }, + "x-go-name": "Tasks", + "example": "[export_task_uid1,export_task_uid2]" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DatabaseDriverAdditionalParam": { + "type": "object", + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "type": { + "type": "string", + "x-go-name": "Type" + }, + "value": { + "type": "string", + "x-go-name": "Value" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DatabaseDriverOption": { + "type": "object", + "properties": { + "db_type": { + "type": "string", + "x-go-name": "DBType" + }, + "logo_path": { + "type": "string", + "x-go-name": "LogoPath" + }, + "params": { + "type": "array", + "items": { + "$ref": "#/definitions/DatabaseDriverAdditionalParam" + }, + "x-go-name": "Params" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DateTime": { + "description": "DateTime is a time but it serializes to ISO8601 format with millis\nIt knows how to read 3 different variations of a RFC3339 date time.\nMost APIs we encounter want either millisecond or second precision times.\nThis just tries to make it worry-free.", + "type": "string", + "format": "date-time", + "x-go-package": "github.com/go-openapi/strfmt" + }, + "DbServiceConnections": { + "type": "object", + "properties": { + "db_service_uid": { + "type": "string", + "x-go-name": "DBServiceUid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DelSessionReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Del session reply", + "type": "object", + "properties": { + "location": { + "description": "Session token", + "type": "string", + "x-go-name": "Location" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DeleteGatewayReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DeleteMaskingTemplateReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "DeleteSensitiveDataDiscoveryTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "EnvironmentTag": { + "type": "object", + "properties": { + "name": { + "description": "环境属性标签最多50个字符", + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "UID" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "FeishuConfigurationResData": { + "type": "object", + "properties": { + "app_id": { + "type": "string", + "x-go-name": "AppID" + }, + "is_feishu_notification_enabled": { + "type": "boolean", + "x-go-name": "IsFeishuNotificationEnabled" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "FileHeader": { + "type": "object", + "title": "A FileHeader describes a file part of a multipart request.", + "properties": { + "Filename": { + "type": "string" + }, + "Header": { + "$ref": "#/definitions/MIMEHeader" + }, + "Size": { + "type": "integer", + "format": "int64" + } + }, + "x-go-package": "mime/multipart" + }, + "Gateway": { + "type": "object", + "properties": { + "gateway_address": { + "type": "string", + "x-go-name": "GatewayAddress" + }, + "gateway_desc": { + "type": "string", + "x-go-name": "GatewayDesc" + }, + "gateway_id": { + "type": "string", + "x-go-name": "GatewayID" + }, + "gateway_name": { + "type": "string", + "x-go-name": "GatewayName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GenAccessToken": { + "type": "object", + "properties": { + "expiration_days": { + "type": "string", + "x-go-name": "ExpirationDays" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GenAccessTokenReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/AccessTokenInfo" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GenericResp": { + "description": "GenericResp defines the return code and msg", + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + }, + "GetBasicInfoReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/BasicInfo" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetCBOperationLogTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/CBOperationLogTips" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetCompanyNoticeReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/CompanyNotice" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetDBServiceSyncTask": { + "type": "object", + "required": [ + "name", + "source", + "url", + "db_type", + "cron_express" + ], + "properties": { + "additional_params": { + "$ref": "#/definitions/Params" + }, + "cron_express": { + "description": "cron expression", + "type": "string", + "x-go-name": "CronExpress", + "example": "0 0 * * *" + }, + "db_type": { + "description": "database type", + "type": "string", + "x-go-name": "DbType", + "example": "MySQL" + }, + "name": { + "description": "name", + "type": "string", + "x-go-name": "Name", + "example": "dmp" + }, + "source": { + "description": "source", + "type": "string", + "x-go-name": "Source", + "example": "actiontech-dmp" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "uid": { + "type": "string", + "x-go-name": "UID" + }, + "url": { + "description": "addr", + "type": "string", + "x-go-name": "URL", + "example": "http://10.186.62.56:10000" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetDBServiceSyncTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetDBServiceSyncTask" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetDataExportTask": { + "type": "object", + "properties": { + "audit_result": { + "$ref": "#/definitions/AuditTaskResult" + }, + "db_info": { + "$ref": "#/definitions/TaskDBInfo" + }, + "export_end_time": { + "type": "string", + "format": "date-time", + "x-go-name": "ExportEndTime" + }, + "export_file_type": { + "type": "string", + "x-go-name": "ExportFileType" + }, + "export_start_time": { + "type": "string", + "format": "date-time", + "x-go-name": "ExportStartTime" + }, + "export_type": { + "type": "string", + "x-go-name": "ExportType" + }, + "file_name": { + "type": "string", + "x-go-name": "FileName" + }, + "status": { + "type": "string", + "enum": [ + "init", + "exporting", + "finish", + "failed", + "file_deleted" + ], + "x-go-enum-desc": "init StatusInit\nexporting StatusExporting\nfinish StatusFinish\nfailed StatusFailed\nfile_deleted StatusFileDeleted", + "x-go-name": "Status" + }, + "task_uid": { + "type": "string", + "x-go-name": "TaskUid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetDataExportWorkflow": { + "type": "object", + "properties": { + "create_time": { + "type": "string", + "format": "date-time", + "x-go-name": "CreateTime" + }, + "create_user": { + "$ref": "#/definitions/UidWithName" + }, + "desc": { + "type": "string", + "x-go-name": "Desc" + }, + "workflow_name": { + "type": "string", + "x-go-name": "Name" + }, + "workflow_record": { + "$ref": "#/definitions/WorkflowRecord" + }, + "workflow_record_history": { + "type": "array", + "items": { + "$ref": "#/definitions/WorkflowRecord" + }, + "x-go-name": "WorkflowRecordHistory" + }, + "workflow_uid": { + "type": "string", + "x-go-name": "WorkflowID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetDataExportWorkflowReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetDataExportWorkflow" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetFeishuConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/FeishuConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetGatewayReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/Gateway" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetGatewayTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "GatewayTips" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetGlobalDataExportWorkflowsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/GlobalDataExportWorkflow" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetLDAPConfigurationResDataReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/LDAPConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-name": "GetLDAPConfigurationReply", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetLicenseReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "content": { + "type": "string", + "x-go-name": "Content" + }, + "license": { + "type": "array", + "items": { + "$ref": "#/definitions/LicenseItem" + }, + "x-go-name": "License" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetLicenseUsageReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/LicenseUsage" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetLoginTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/LoginTipsResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetMaskingOverviewTreeData": { + "type": "object", + "properties": { + "dashboard": { + "$ref": "#/definitions/MaskingOverviewDashboard" + }, + "databases": { + "description": "database_name -\u003e database node", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/MaskingOverviewDatabaseNode" + }, + "x-go-name": "Databases" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetMaskingOverviewTreeReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetMaskingOverviewTreeData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetMemberGroup": { + "type": "object", + "properties": { + "is_project_admin": { + "description": "Whether the member has project admin permission", + "type": "boolean", + "x-go-name": "IsProjectAdmin" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "role_with_op_ranges": { + "description": "member op permission", + "type": "array", + "items": { + "$ref": "#/definitions/ListMemberRoleWithOpRange" + }, + "x-go-name": "RoleWithOpRanges" + }, + "uid": { + "description": "member group uid", + "type": "string", + "x-go-name": "Uid" + }, + "users": { + "description": "member user", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "Users" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GetMemberGroupReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetMemberGroup" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GetOauth2ConfigurationResData": { + "type": "object", + "properties": { + "access_token_tag": { + "type": "string", + "x-go-name": "AccessTokenTag" + }, + "auto_bind_same_name_user": { + "type": "boolean", + "x-go-name": "AutoBindSameNameUser" + }, + "auto_create_user": { + "type": "boolean", + "x-go-name": "AutoCreateUser" + }, + "back_channel_logout_uri": { + "type": "string", + "x-go-name": "BackChannelLogoutUri" + }, + "client_host": { + "type": "string", + "x-go-name": "ClientHost" + }, + "client_id": { + "type": "string", + "x-go-name": "ClientID" + }, + "enable_manually_bind": { + "type": "boolean", + "x-go-name": "EnableManuallyBind" + }, + "enable_oauth2": { + "type": "boolean", + "x-go-name": "EnableOauth2" + }, + "login_perm_expr": { + "type": "string", + "x-go-name": "LoginPermExpr" + }, + "login_tip": { + "type": "string", + "x-go-name": "LoginTip" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Scopes" + }, + "server_auth_url": { + "type": "string", + "x-go-name": "ServerAuthUrl" + }, + "server_logout_url": { + "type": "string", + "x-go-name": "ServerLogoutUrl" + }, + "server_token_url": { + "type": "string", + "x-go-name": "ServerTokenUrl" + }, + "server_user_id_url": { + "type": "string", + "x-go-name": "ServerUserIdUrl" + }, + "skip_check_state": { + "type": "boolean", + "x-go-name": "SkipCheckState" + }, + "user_email_tag": { + "type": "string", + "x-go-name": "UserEmailTag" + }, + "user_id_tag": { + "type": "string", + "x-go-name": "UserIdTag" + }, + "user_wechat_tag": { + "type": "string", + "x-go-name": "UserWeChatTag" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetOauth2ConfigurationResDataReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetOauth2ConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-name": "GetOauth2ConfigurationReply", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetOauth2TipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetOauth2TipsResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetOauth2TipsResData": { + "type": "object", + "properties": { + "enable_oauth2": { + "type": "boolean", + "x-go-name": "EnableOauth2" + }, + "login_tip": { + "type": "string", + "x-go-name": "LoginTip" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetOperationRecordListReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/OperationRecordListItem" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "uint64", + "x-go-name": "TotalNums" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetPlaintextAccessRequestDetailReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "plaintext access request detail reply", + "type": "object", + "properties": { + "masking_preview": { + "$ref": "#/definitions/MaskingPreviewData" + }, + "query_sql": { + "description": "query sql statement", + "type": "string", + "x-go-name": "QuerySQL", + "example": "\"SELECT * FROM users\"" + }, + "reason": { + "description": "application reason", + "type": "string", + "x-go-name": "Reason", + "example": "\"troubleshooting\"" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetProjectTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "project tips", + "type": "array", + "items": { + "$ref": "#/definitions/ProjectTips" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetSMTPConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/SMTPConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetSQLQueryConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "object", + "properties": { + "enable_odc_query": { + "type": "boolean", + "x-go-name": "EnableOdcQuery" + }, + "enable_sql_query": { + "type": "boolean", + "x-go-name": "EnableSQLQuery" + }, + "odc_query_root_uri": { + "type": "string", + "x-go-name": "OdcQueryRootURI" + }, + "sql_query_root_uri": { + "type": "string", + "x-go-name": "SQLQueryRootURI" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetSmsConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetSmsConfigurationReplyItem" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetSmsConfigurationReplyItem": { + "type": "object", + "properties": { + "configuration": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "x-go-name": "Configuration" + }, + "enable": { + "type": "boolean", + "x-go-name": "Enable" + }, + "sms_type": { + "type": "string", + "x-go-name": "SmsType" + }, + "url": { + "type": "string", + "x-go-name": "Url" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetSystemVariablesReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/SystemVariablesResV1" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GetTableColumnMaskingDetailsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "table column masking details reply", + "type": "array", + "items": { + "$ref": "#/definitions/TableColumnMaskingDetail" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetUser": { + "description": "A dms user", + "type": "object", + "properties": { + "access_token_info": { + "$ref": "#/definitions/AccessTokenInfo" + }, + "authentication_type": { + "description": "user authentication type\nldap UserAuthenticationTypeLDAP\ndms UserAuthenticationTypeDMS\noauth2 UserAuthenticationTypeOAUTH2\nunknown UserAuthenticationTypeUnknown", + "type": "string", + "enum": [ + "ldap", + "dms", + "oauth2", + "unknown" + ], + "x-go-enum-desc": "ldap UserAuthenticationTypeLDAP\ndms UserAuthenticationTypeDMS\noauth2 UserAuthenticationTypeOAUTH2\nunknown UserAuthenticationTypeUnknown", + "x-go-name": "AuthenticationType" + }, + "email": { + "description": "user email", + "type": "string", + "x-go-name": "Email" + }, + "is_admin": { + "description": "is admin", + "type": "boolean", + "x-go-name": "IsAdmin" + }, + "language": { + "description": "user language", + "type": "string", + "x-go-name": "Language" + }, + "name": { + "description": "user name", + "type": "string", + "x-go-name": "Name" + }, + "op_permissions": { + "description": "user operation permissions", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "OpPermissions" + }, + "phone": { + "description": "user phone", + "type": "string", + "x-go-name": "Phone" + }, + "stat": { + "description": "user stat\n正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "type": "string", + "enum": [ + "正常", + "被禁用", + "未知", + "Normal", + "Disabled", + "Unknown" + ], + "x-go-enum-desc": "正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "x-go-name": "Stat" + }, + "system": { + "description": "user system\nWORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "type": "string", + "enum": [ + "WORKBENCH", + "MANAGEMENT" + ], + "x-go-enum-desc": "WORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "x-go-name": "System" + }, + "third_party_user_info": { + "type": "string", + "x-go-name": "ThirdPartyUserInfo" + }, + "two_factor_enabled": { + "description": "user two factor enabled", + "type": "boolean", + "x-go-name": "TwoFactorEnabled" + }, + "uid": { + "description": "user uid", + "type": "string", + "x-go-name": "UserUid" + }, + "user_bind_projects": { + "description": "user bind name space", + "type": "array", + "items": { + "$ref": "#/definitions/UserBindProject" + }, + "x-go-name": "UserBindProjects" + }, + "user_groups": { + "description": "user groups", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "UserGroups" + }, + "wxid": { + "description": "user wxid", + "type": "string", + "x-go-name": "WxID" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GetUserBySessionReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "Get user reply", + "type": "object", + "properties": { + "name": { + "description": "User name", + "type": "string", + "x-go-name": "Name" + }, + "user_uid": { + "description": "User UID", + "type": "string", + "x-go-name": "UserUid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetUserOpPermissionReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "user op permission reply\nis user admin, admin has all permissions", + "type": "object", + "properties": { + "is_admin": { + "type": "boolean", + "x-go-name": "IsAdmin" + }, + "op_permission_list": { + "description": "user op permissions", + "type": "array", + "items": { + "$ref": "#/definitions/OpPermissionItem" + }, + "x-go-name": "OpPermissionList" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GetUserReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetUser" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "GetWeChatConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/WeChatConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetWebHookConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/GetWebHookConfigurationReplyItem" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GetWebHookConfigurationReplyItem": { + "type": "object", + "properties": { + "enable": { + "type": "boolean", + "x-go-name": "Enable" + }, + "max_retry_times": { + "description": "minlength(3) maxlength(100)", + "type": "integer", + "format": "int64", + "x-go-name": "MaxRetryTimes" + }, + "retry_interval_seconds": { + "type": "integer", + "format": "int64", + "x-go-name": "RetryIntervalSeconds" + }, + "token": { + "type": "string", + "x-go-name": "Token" + }, + "url": { + "type": "string", + "x-go-name": "URL" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "GlobalDataExportWorkflow": { + "type": "object", + "properties": { + "created_at": { + "type": "string", + "format": "date-time", + "x-go-name": "CreatedAt" + }, + "creater": { + "$ref": "#/definitions/UidWithName" + }, + "current_step_assignee_user_list": { + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "CurrentStepAssigneeUsers" + }, + "db_service_info": { + "type": "array", + "items": { + "$ref": "#/definitions/DBServiceUidWithNameInfo" + }, + "x-go-name": "DBServiceInfos" + }, + "desc": { + "type": "string", + "x-go-name": "Description" + }, + "project_info": { + "$ref": "#/definitions/ProjectInfo" + }, + "status": { + "type": "string", + "enum": [ + "wait_for_approve", + "wait_for_export", + "exporting", + "rejected", + "cancel", + "failed", + "finish" + ], + "x-go-enum-desc": "wait_for_approve DataExportWorkflowStatusWaitForApprove\nwait_for_export DataExportWorkflowStatusWaitForExport\nexporting DataExportWorkflowStatusWaitForExporting\nrejected DataExportWorkflowStatusRejected\ncancel DataExportWorkflowStatusCancel\nfailed DataExportWorkflowStatusFailed\nfinish DataExportWorkflowStatusFinish", + "x-go-name": "Status" + }, + "workflow_name": { + "type": "string", + "x-go-name": "WorkflowName" + }, + "workflow_uid": { + "type": "string", + "x-go-name": "WorkflowID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "I18nStr": { + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + }, + "ImportDBService": { + "type": "object", + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "business": { + "description": "the db service business name\nDeprecated: the business field is replaced with the environmentTag of the v2 interface.", + "type": "string", + "x-go-name": "Business" + }, + "db_type": { + "description": "db service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "DB desc", + "type": "string", + "x-go-name": "Desc" + }, + "host": { + "description": "db service host", + "type": "string", + "x-go-name": "Host" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "db service name", + "type": "string", + "x-go-name": "Name" + }, + "password": { + "description": "db service admin encrypted password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "db service port", + "type": "string", + "x-go-name": "Port" + }, + "project_uid": { + "description": "DB project uid", + "type": "string", + "x-go-name": "ProjectUID" + }, + "source": { + "description": "DB source", + "type": "string", + "x-go-name": "Source" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "user": { + "description": "db service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ImportDBServiceV2": { + "type": "object", + "required": [ + "environment_tag_name" + ], + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "db_type": { + "description": "db service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "DB desc", + "type": "string", + "x-go-name": "Desc" + }, + "environment_tag_name": { + "description": "DB Service environment tag uid", + "type": "string", + "x-go-name": "EnvironmentTagName" + }, + "host": { + "description": "db service host", + "type": "string", + "x-go-name": "Host" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "db service name", + "type": "string", + "x-go-name": "Name" + }, + "password": { + "description": "db service admin encrypted password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "db service port", + "type": "string", + "x-go-name": "Port" + }, + "project_uid": { + "description": "DB project uid", + "type": "string", + "x-go-name": "ProjectUID" + }, + "source": { + "description": "DB source", + "type": "string", + "x-go-name": "Source" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "user": { + "description": "db service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-name": "ImportDBService", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ImportDBServicesCheckReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "db services", + "type": "array", + "items": { + "$ref": "#/definitions/ImportDBService" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ImportDBServicesCheckReplyV2": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "db services", + "type": "array", + "items": { + "$ref": "#/definitions/ImportDBServiceV2" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-name": "ImportDBServicesCheckReply", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ImportDBServicesOfOneProjectReq": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/ImportDBService" + }, + "x-go-name": "DBServices" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ImportDBServicesOfOneProjectReqV2": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/ImportDBServiceV2" + }, + "x-go-name": "DBServices" + } + }, + "x-go-name": "ImportDBServicesOfOneProjectReq", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ImportDBServicesOfProjectsReq": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/ImportDBService" + }, + "x-go-name": "DBServices" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ImportDBServicesOfProjectsReqV2": { + "type": "object", + "properties": { + "db_services": { + "type": "array", + "items": { + "$ref": "#/definitions/ImportDBServiceV2" + }, + "x-go-name": "DBServices" + } + }, + "x-go-name": "ImportDBServicesOfProjectsReq", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ImportProjects": { + "type": "object", + "properties": { + "business": { + "description": "business", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Business" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "Project name", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ImportProjectsReq": { + "type": "object", + "properties": { + "projects": { + "type": "array", + "items": { + "$ref": "#/definitions/ImportProjects" + }, + "x-go-name": "Projects" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ImportProjectsReqV2": { + "type": "object", + "properties": { + "projects": { + "type": "array", + "items": { + "$ref": "#/definitions/ImportProjectsV2" + }, + "x-go-name": "Projects" + } + }, + "x-go-name": "ImportProjectsReq", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ImportProjectsV2": { + "type": "object", + "properties": { + "business_tag": { + "$ref": "#/definitions/BusinessTag" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "Project name", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-name": "ImportProjects", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "LDAPConfiguration": { + "type": "object", + "properties": { + "enable_ldap": { + "type": "boolean", + "x-go-name": "EnableLdap" + }, + "enable_ssl": { + "type": "boolean", + "x-go-name": "EnableSSL" + }, + "ldap_connect_dn": { + "type": "string", + "x-go-name": "LdapConnectDn" + }, + "ldap_connect_pwd": { + "type": "string", + "x-go-name": "LdapConnectPwd" + }, + "ldap_search_base_dn": { + "type": "string", + "x-go-name": "LdapSearchBaseDn" + }, + "ldap_server_host": { + "type": "string", + "x-go-name": "LdapServerHost" + }, + "ldap_server_port": { + "type": "string", + "x-go-name": "LdapServerPort" + }, + "ldap_user_email_rdn_key": { + "type": "string", + "x-go-name": "LdapUserEmailRdnKey" + }, + "ldap_user_name_rdn_key": { + "type": "string", + "x-go-name": "LdapUserNameRdnKey" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "LDAPConfigurationResData": { + "type": "object", + "properties": { + "enable_ldap": { + "type": "boolean", + "x-go-name": "EnableLdap" + }, + "enable_ssl": { + "type": "boolean", + "x-go-name": "EnableSSL" + }, + "ldap_connect_dn": { + "type": "string", + "x-go-name": "LdapConnectDn" + }, + "ldap_search_base_dn": { + "type": "string", + "x-go-name": "LdapSearchBaseDn" + }, + "ldap_server_host": { + "type": "string", + "x-go-name": "LdapServerHost" + }, + "ldap_server_port": { + "type": "string", + "x-go-name": "LdapServerPort" + }, + "ldap_user_email_rdn_key": { + "type": "string", + "x-go-name": "LdapUserEmailRdnKey" + }, + "ldap_user_name_rdn_key": { + "type": "string", + "x-go-name": "LdapUserNameRdnKey" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "LicenseItem": { + "type": "object", + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "limit": { + "type": "string", + "x-go-name": "Limit" + }, + "name": { + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "LicenseUsage": { + "type": "object", + "properties": { + "db_services_usage": { + "type": "array", + "items": { + "$ref": "#/definitions/LicenseUsageItem" + }, + "x-go-name": "DbServicesUsage" + }, + "users_usage": { + "$ref": "#/definitions/LicenseUsageItem" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "LicenseUsageItem": { + "type": "object", + "properties": { + "is_limited": { + "type": "boolean", + "x-go-name": "IsLimited" + }, + "limit": { + "type": "integer", + "format": "uint64", + "x-go-name": "Limit" + }, + "resource_type": { + "type": "string", + "x-go-name": "ResourceType" + }, + "resource_type_desc": { + "type": "string", + "x-go-name": "ResourceTypeDesc" + }, + "used": { + "type": "integer", + "format": "uint64", + "x-go-name": "Used" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListBusinessTagsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/BusinessTag" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListCBOperationLogsReply": { + "type": "object", + "properties": { + "audit_intercepted_sql_count": { + "description": "审核拦截的异常SQL数量", + "type": "integer", + "format": "int64", + "x-go-name": "AuditInterceptedSQLCount" + }, + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "list cb operation logs reply", + "type": "array", + "items": { + "$ref": "#/definitions/CBOperationLog" + }, + "x-go-name": "Data" + }, + "exec_failed_sql_count": { + "description": "执行失败的SQL", + "type": "integer", + "format": "int64", + "x-go-name": "ExecFailedSQLCount" + }, + "exec_sql_total": { + "description": "执行SQL总量", + "type": "integer", + "format": "int64", + "x-go-name": "ExecSQLTotal" + }, + "exec_success_rate": { + "description": "执行成功率", + "type": "number", + "format": "double", + "x-go-name": "ExecSuccessRate" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListCreatableDBServicesForMaskingTaskData": { + "type": "object", + "properties": { + "db_service_host": { + "description": "database instance host", + "type": "string", + "x-go-name": "DBServiceHost", + "example": "\"10.10.10.10\"" + }, + "db_service_name": { + "description": "database instance name", + "type": "string", + "x-go-name": "DBServiceName", + "example": "\"mysql-01\"" + }, + "db_service_port": { + "description": "database instance port", + "type": "string", + "x-go-name": "DBServicePort", + "example": "\"3306\"" + }, + "db_service_uid": { + "description": "database instance uid", + "type": "string", + "x-go-name": "DBServiceUID", + "example": "\"db_service_uid_1\"" + }, + "db_type": { + "description": "database type", + "type": "string", + "x-go-name": "DBType", + "example": "\"MySQL\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListCreatableDBServicesForMaskingTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "list of db services that can create masking discovery task", + "type": "array", + "items": { + "$ref": "#/definitions/ListCreatableDBServicesForMaskingTaskData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "description": "total count of db services", + "type": "integer", + "format": "int64", + "x-go-name": "Total", + "example": 10 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDBService": { + "description": "A dms db Service", + "type": "object", + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "audit_plan_types": { + "description": "audit plan types", + "type": "array", + "items": { + "$ref": "#/definitions/AuditPlanTypes" + }, + "x-go-name": "AuditPlanTypes" + }, + "backup_max_rows": { + "description": "backup max rows", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "business": { + "description": "TODO This parameter is deprecated and will be removed soon.\nthe db service business name", + "type": "string", + "x-go-name": "Business" + }, + "db_type": { + "description": "db service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "DB desc", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "host": { + "description": "db service host", + "type": "string", + "x-go-name": "Host" + }, + "instance_audit_plan_id": { + "description": "instance audit plan id", + "type": "integer", + "format": "uint64", + "x-go-name": "InstanceAuditPlanID" + }, + "is_enable_masking": { + "description": "is enable masking", + "type": "boolean", + "x-go-name": "IsEnableMasking" + }, + "last_connection_test_error_message": { + "description": "DB connect test error message", + "type": "string", + "x-go-name": "LastConnectionTestErrorMessage" + }, + "last_connection_test_status": { + "description": "DB connect test status\nconnect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "type": "string", + "enum": [ + "connect_success", + "connect_failed" + ], + "x-go-enum-desc": "connect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "x-go-name": "LastConnectionTestStatus" + }, + "last_connection_test_time": { + "description": "DB connection test time", + "type": "string", + "format": "date-time", + "x-go-name": "LastConnectionTestTime" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "db service name", + "type": "string", + "x-go-name": "Name" + }, + "password": { + "description": "db service admin encrypted password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "db service port", + "type": "string", + "x-go-name": "Port" + }, + "project_uid": { + "description": "DB project uid", + "type": "string", + "x-go-name": "ProjectUID" + }, + "source": { + "description": "DB source", + "type": "string", + "x-go-name": "Source" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "uid": { + "description": "db service uid", + "type": "string", + "x-go-name": "DBServiceUid" + }, + "user": { + "description": "db service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ListDBServiceDriverOptionReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List db service reply", + "type": "array", + "items": { + "$ref": "#/definitions/DatabaseDriverOption" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDBServiceReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List db service reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListDBService" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ListDBServiceReplyV2": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List db service reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListDBServiceV2" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-name": "ListDBServiceReply", + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + }, + "ListDBServiceSyncTask": { + "type": "object", + "required": [ + "name", + "source", + "url", + "db_type", + "cron_express" + ], + "properties": { + "additional_params": { + "$ref": "#/definitions/Params" + }, + "cron_express": { + "description": "cron expression", + "type": "string", + "x-go-name": "CronExpress", + "example": "0 0 * * *" + }, + "db_type": { + "description": "database type", + "type": "string", + "x-go-name": "DbType", + "example": "MySQL" + }, + "last_sync_err": { + "description": "last sync error message", + "type": "string", + "x-go-name": "LastSyncErr" + }, + "last_sync_success_time": { + "type": "string", + "format": "date-time", + "x-go-name": "LastSyncSuccessTime" + }, + "name": { + "description": "name", + "type": "string", + "x-go-name": "Name", + "example": "dmp" + }, + "source": { + "description": "source", + "type": "string", + "x-go-name": "Source", + "example": "actiontech-dmp" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "uid": { + "type": "string", + "x-go-name": "UID" + }, + "url": { + "description": "addr", + "type": "string", + "x-go-name": "URL", + "example": "http://10.186.62.56:10000" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDBServiceSyncTaskTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/DBServiceSyncTaskTip" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDBServiceSyncTasksReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/ListDBServiceSyncTask" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDBServiceTipItem": { + "type": "object", + "properties": { + "db_type": { + "type": "string", + "x-go-name": "Type" + }, + "host": { + "type": "string", + "x-go-name": "Host" + }, + "id": { + "type": "string", + "x-go-name": "Id" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "port": { + "type": "string", + "x-go-name": "Port" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDBServiceTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List db service reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListDBServiceTipItem" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDBServiceV2": { + "type": "object", + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "audit_plan_types": { + "description": "audit plan types", + "type": "array", + "items": { + "$ref": "#/definitions/AuditPlanTypes" + }, + "x-go-name": "AuditPlanTypes" + }, + "backup_max_rows": { + "description": "backup max rows", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "db_type": { + "description": "db service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "DB desc", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "environment_tag": { + "$ref": "#/definitions/EnvironmentTag" + }, + "host": { + "description": "db service host", + "type": "string", + "x-go-name": "Host" + }, + "instance_audit_plan_id": { + "description": "instance audit plan id", + "type": "integer", + "format": "uint64", + "x-go-name": "InstanceAuditPlanID" + }, + "is_enable_masking": { + "description": "is enable masking", + "type": "boolean", + "x-go-name": "IsEnableMasking" + }, + "last_connection_test_error_message": { + "description": "DB connect test error message", + "type": "string", + "x-go-name": "LastConnectionTestErrorMessage" + }, + "last_connection_test_status": { + "description": "DB connect test status\nconnect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "type": "string", + "enum": [ + "connect_success", + "connect_failed" + ], + "x-go-enum-desc": "connect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "x-go-name": "LastConnectionTestStatus" + }, + "last_connection_test_time": { + "description": "DB connection test time", + "type": "string", + "format": "date-time", + "x-go-name": "LastConnectionTestTime" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "db service name", + "type": "string", + "x-go-name": "Name" + }, + "password": { + "description": "db service admin encrypted password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "db service port", + "type": "string", + "x-go-name": "Port" + }, + "project_uid": { + "description": "DB project uid", + "type": "string", + "x-go-name": "ProjectUID" + }, + "source": { + "description": "DB source", + "type": "string", + "x-go-name": "Source" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "uid": { + "description": "db service uid", + "type": "string", + "x-go-name": "DBServiceUid" + }, + "user": { + "description": "db service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-name": "ListDBService", + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + }, + "ListDataExportTaskSQL": { + "type": "object", + "properties": { + "audit_level": { + "type": "string", + "x-go-name": "AuditLevel" + }, + "audit_sql_result": { + "type": "array", + "items": { + "$ref": "#/definitions/AuditSQLResult" + }, + "x-go-name": "AuditSQLResult" + }, + "export_result": { + "type": "string", + "x-go-name": "ExportResult" + }, + "export_sql_type": { + "type": "string", + "x-go-name": "ExportSQLType" + }, + "sql": { + "type": "string", + "x-go-name": "ExportSQL" + }, + "uid": { + "type": "integer", + "format": "uint64", + "x-go-name": "ID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDataExportTaskSQLsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/ListDataExportTaskSQL" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDataExportWorkflow": { + "type": "object", + "properties": { + "created_at": { + "type": "string", + "format": "date-time", + "x-go-name": "CreatedAt" + }, + "creater": { + "$ref": "#/definitions/UidWithName" + }, + "current_step_assignee_user_list": { + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "CurrentStepAssigneeUsers" + }, + "db_service_info": { + "type": "array", + "items": { + "$ref": "#/definitions/DBServiceUidWithNameInfo" + }, + "x-go-name": "DBServiceInfos" + }, + "desc": { + "type": "string", + "x-go-name": "Description" + }, + "exported_at": { + "type": "string", + "format": "date-time", + "x-go-name": "ExportedAt" + }, + "project_info": { + "$ref": "#/definitions/ProjectInfo" + }, + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + }, + "project_uid": { + "type": "string", + "x-go-name": "ProjectUid" + }, + "status": { + "type": "string", + "enum": [ + "wait_for_approve", + "wait_for_export", + "exporting", + "rejected", + "cancel", + "failed", + "finish" + ], + "x-go-enum-desc": "wait_for_approve DataExportWorkflowStatusWaitForApprove\nwait_for_export DataExportWorkflowStatusWaitForExport\nexporting DataExportWorkflowStatusWaitForExporting\nrejected DataExportWorkflowStatusRejected\ncancel DataExportWorkflowStatusCancel\nfailed DataExportWorkflowStatusFailed\nfinish DataExportWorkflowStatusFinish", + "x-go-name": "Status" + }, + "workflow_name": { + "type": "string", + "x-go-name": "WorkflowName" + }, + "workflow_uid": { + "type": "string", + "x-go-name": "WorkflowID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListDataExportWorkflowsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/ListDataExportWorkflow" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListEnvironmentTagsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/EnvironmentTag" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListGatewaysReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/Gateway" + }, + "x-go-name": "Gateways" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListGlobalDBService": { + "type": "object", + "properties": { + "backup_max_rows": { + "description": "backup switch", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "business": { + "description": "TODO This parameter is deprecated and will be removed soon.\nthe db service business name\nDeprecated: the business field is replaced with the environmentTag of the v2 interface.", + "type": "string", + "x-go-name": "Business" + }, + "db_type": { + "description": "db service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "DB desc", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "host": { + "description": "db service host", + "type": "string", + "x-go-name": "Host" + }, + "is_enable_audit": { + "description": "is enable audit", + "type": "boolean", + "x-go-name": "IsEnableAudit" + }, + "is_enable_masking": { + "description": "is enable masking", + "type": "boolean", + "x-go-name": "IsEnableMasking" + }, + "last_connection_test_error_message": { + "description": "DB connect test error message", + "type": "string", + "x-go-name": "LastConnectionTestErrorMessage" + }, + "last_connection_test_status": { + "description": "DB connect test status\nconnect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "type": "string", + "enum": [ + "connect_success", + "connect_failed" + ], + "x-go-enum-desc": "connect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "x-go-name": "LastConnectionTestStatus" + }, + "last_connection_test_time": { + "description": "DB connection test time", + "type": "string", + "format": "date-time", + "x-go-name": "LastConnectionTestTime" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "db service name", + "type": "string", + "x-go-name": "Name" + }, + "port": { + "description": "db service port", + "type": "string", + "x-go-name": "Port" + }, + "project_name": { + "description": "db service project_name", + "type": "string", + "x-go-name": "ProjectName" + }, + "project_uid": { + "description": "DB project uid", + "type": "string", + "x-go-name": "ProjectUID" + }, + "source": { + "description": "DB source", + "type": "string", + "x-go-name": "Source" + }, + "uid": { + "description": "db service uid", + "type": "string", + "x-go-name": "DBServiceUid" + }, + "unfinished_workflow_num": { + "description": "db service unfinished workflow num", + "type": "integer", + "format": "int64", + "x-go-name": "UnfinishedWorkflowNum" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListGlobalDBServiceTips": { + "type": "object", + "properties": { + "db_type": { + "description": "DBType 数据库类型列表\n当请求参数 function_support 为空时,返回所有数据库类型\n当请求参数 function_support 有效时,仅返回支持该功能的数据库类型", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "DBType" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListGlobalDBServiceV2": { + "type": "object", + "required": [ + "environment_tag" + ], + "properties": { + "backup_max_rows": { + "description": "backup switch", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "db_type": { + "description": "db service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "DB desc", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "environment_tag": { + "$ref": "#/definitions/EnvironmentTag" + }, + "host": { + "description": "db service host", + "type": "string", + "x-go-name": "Host" + }, + "is_enable_audit": { + "description": "is enable audit", + "type": "boolean", + "x-go-name": "IsEnableAudit" + }, + "is_enable_masking": { + "description": "is enable masking", + "type": "boolean", + "x-go-name": "IsEnableMasking" + }, + "last_connection_test_error_message": { + "description": "DB connect test error message", + "type": "string", + "x-go-name": "LastConnectionTestErrorMessage" + }, + "last_connection_test_status": { + "description": "DB connect test status\nconnect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "type": "string", + "enum": [ + "connect_success", + "connect_failed" + ], + "x-go-enum-desc": "connect_success LastConnectionTestStatusSuccess\nconnect_failed LastConnectionTestStatusFailed", + "x-go-name": "LastConnectionTestStatus" + }, + "last_connection_test_time": { + "description": "DB connection test time", + "type": "string", + "format": "date-time", + "x-go-name": "LastConnectionTestTime" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "name": { + "description": "db service name", + "type": "string", + "x-go-name": "Name" + }, + "port": { + "description": "db service port", + "type": "string", + "x-go-name": "Port" + }, + "project_name": { + "description": "db service project_name", + "type": "string", + "x-go-name": "ProjectName" + }, + "project_uid": { + "description": "DB project uid", + "type": "string", + "x-go-name": "ProjectUID" + }, + "source": { + "description": "DB source", + "type": "string", + "x-go-name": "Source" + }, + "uid": { + "description": "db service uid", + "type": "string", + "x-go-name": "DBServiceUid" + }, + "unfinished_workflow_num": { + "description": "db service unfinished workflow num", + "type": "integer", + "format": "int64", + "x-go-name": "UnfinishedWorkflowNum" + }, + "workflow_exec_enabled": { + "description": "is enabled workflow exec", + "type": "boolean", + "x-go-name": "WorkflowExecEnabled" + } + }, + "x-go-name": "ListGlobalDBService", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ListGlobalDBServicesReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List global db service reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListGlobalDBService" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListGlobalDBServicesReplyV2": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List global db service reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListGlobalDBServiceV2" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-name": "ListGlobalDBServicesReply", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ListGlobalDBServicesTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/ListGlobalDBServiceTips" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMaskingRulesData": { + "type": "object", + "properties": { + "description": { + "description": "description", + "type": "string", + "x-go-name": "Description", + "example": "\"mask digits\"" + }, + "effect": { + "description": "effect description for users", + "type": "string", + "x-go-name": "Effect", + "example": "\"保留开头2位和结尾2位,中间字符替换为*\"" + }, + "effect_example_after": { + "description": "effect example after masking", + "type": "string", + "x-go-name": "EffectExampleAfter", + "example": "\"138******78\"" + }, + "effect_example_before": { + "description": "effect example before masking", + "type": "string", + "x-go-name": "EffectExampleBefore", + "example": "\"13812345678\"" + }, + "id": { + "description": "masking rule id", + "type": "integer", + "format": "int64", + "x-go-name": "Id", + "example": 1 + }, + "masking_type": { + "description": "masking type", + "type": "string", + "x-go-name": "MaskingType", + "example": "\"MASK_DIGIT\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMaskingRulesReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "list masking rule reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListMaskingRulesData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMaskingTemplatesData": { + "type": "object", + "properties": { + "id": { + "description": "masking template id", + "type": "integer", + "format": "int64", + "x-go-name": "Id", + "example": 1 + }, + "name": { + "description": "masking template name", + "type": "string", + "x-go-name": "Name", + "example": "\"Standard Template\"" + }, + "rule_count": { + "description": "count of rules in the template", + "type": "integer", + "format": "int64", + "x-go-name": "RuleCount", + "example": 5 + }, + "rule_names": { + "description": "preview of rule name in the template, up to 3 items", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "RuleNames" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMaskingTemplatesReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "list masking templates reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListMaskingTemplatesData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "description": "total count of masking templates", + "type": "integer", + "format": "int64", + "x-go-name": "Total", + "example": 100 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMember": { + "description": "A dms member", + "type": "object", + "properties": { + "current_project_admin": { + "$ref": "#/definitions/CurrentProjectAdmin" + }, + "current_project_manage_permissions": { + "description": "current project manage permissions", + "type": "array", + "items": { + "$ref": "#/definitions/ProjectManagePermission" + }, + "x-go-name": "CurrentProjectManagePermissions" + }, + "current_project_op_permissions": { + "description": "current project permission", + "type": "array", + "items": { + "$ref": "#/definitions/ProjectOpPermission" + }, + "x-go-name": "CurrentProjectOpPermissions" + }, + "is_group_member": { + "description": "Whether the member is a group member", + "type": "boolean", + "x-go-name": "IsGroupMember" + }, + "is_project_admin": { + "description": "Whether the member has project admin permission", + "type": "boolean", + "x-go-name": "IsProjectAdmin" + }, + "platform_roles": { + "description": "member platform roles", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "PlatformRoles" + }, + "projects": { + "description": "member projects", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Projects" + }, + "role_with_op_ranges": { + "description": "member op permission", + "type": "array", + "items": { + "$ref": "#/definitions/ListMemberRoleWithOpRange" + }, + "x-go-name": "RoleWithOpRanges" + }, + "uid": { + "description": "member uid", + "type": "string", + "x-go-name": "MemberUid" + }, + "user": { + "$ref": "#/definitions/UidWithName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMemberGroup": { + "type": "object", + "properties": { + "current_project_manage_permissions": { + "description": "member project manage permissions", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "CurrentProjectManagePermissions" + }, + "current_project_op_permissions": { + "description": "current project permission", + "type": "array", + "items": { + "$ref": "#/definitions/ProjectOpPermission" + }, + "x-go-name": "CurrentProjectOpPermissions" + }, + "is_project_admin": { + "description": "Whether the member has project admin permission", + "type": "boolean", + "x-go-name": "IsProjectAdmin" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "role_with_op_ranges": { + "description": "member op permission", + "type": "array", + "items": { + "$ref": "#/definitions/ListMemberRoleWithOpRange" + }, + "x-go-name": "RoleWithOpRanges" + }, + "uid": { + "description": "member uid", + "type": "string", + "x-go-name": "Uid" + }, + "users": { + "description": "member user", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "Users" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMemberGroupTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List member group tip reply", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMemberGroupsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List member reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListMemberGroup" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMemberReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List member reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListMember" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMemberRoleWithOpRange": { + "type": "object", + "properties": { + "member_group": { + "$ref": "#/definitions/ProjectMemberGroup" + }, + "op_permissions": { + "description": "member op permissions", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "OpPermissions" + }, + "op_range_type": { + "description": "op permission range type, only support db service now\nunknown OpRangeTypeUnknown\nglobal OpRangeTypeGlobal 全局权限: 该权限只能被用户使用\nproject OpRangeTypeProject 项目权限: 该权限只能被成员使用\ndb_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用", + "type": "string", + "enum": [ + "unknown", + "global", + "project", + "db_service" + ], + "x-go-enum-desc": "unknown OpRangeTypeUnknown\nglobal OpRangeTypeGlobal 全局权限: 该权限只能被用户使用\nproject OpRangeTypeProject 项目权限: 该权限只能被成员使用\ndb_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用", + "x-go-name": "OpRangeType" + }, + "range_uids": { + "description": "op range uids", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "RangeUIDs" + }, + "role_uid": { + "$ref": "#/definitions/UidWithName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMemberTipsItem": { + "type": "object", + "properties": { + "user_id": { + "type": "string", + "x-go-name": "UserId" + }, + "user_name": { + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMemberTipsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List member tip reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListMemberTipsItem" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListMembersForInternalItem": { + "description": "A dms member for internal", + "type": "object", + "properties": { + "is_admin": { + "description": "is member project admin, admin has all permissions", + "type": "boolean", + "x-go-name": "IsAdmin" + }, + "member_op_permission_list": { + "description": "member op permissions", + "type": "array", + "items": { + "$ref": "#/definitions/OpPermissionItem" + }, + "x-go-name": "MemberOpPermissionList" + }, + "user": { + "$ref": "#/definitions/UidWithName" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ListMembersForInternalReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List member reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListMembersForInternalItem" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ListOpPermission": { + "description": "A dms op permission", + "type": "object", + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "module": { + "type": "string", + "x-go-name": "Module" + }, + "op_permission": { + "$ref": "#/definitions/UidWithName" + }, + "range_type": { + "type": "string", + "enum": [ + "unknown", + "global", + "project", + "db_service" + ], + "x-go-enum-desc": "unknown OpRangeTypeUnknown\nglobal OpRangeTypeGlobal 全局权限: 该权限只能被用户使用\nproject OpRangeTypeProject 项目权限: 该权限只能被成员使用\ndb_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用", + "x-go-name": "RangeType" + }, + "service": { + "type": "string", + "enum": [ + "dms", + "sqle" + ], + "x-go-enum-desc": "dms ServiceDMS\nsqle ServiceSQLE", + "x-go-name": "Service" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListOpPermissionReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List op_permission reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListOpPermission" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListPendingApprovalRequestsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "pending approval requests reply", + "type": "array", + "items": { + "$ref": "#/definitions/PendingApprovalRequestData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "description": "total count of pending approval requests", + "type": "integer", + "format": "int64", + "x-go-name": "Total", + "example": 100 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListProjectReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List project reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListProjectV1" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ListProjectReplyV2": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List project reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListProjectV2" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-name": "ListProjectReply", + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + }, + "ListProjectV1": { + "type": "object", + "properties": { + "archived": { + "description": "Project is archived", + "type": "boolean", + "x-go-name": "Archived" + }, + "business": { + "description": "Project business", + "type": "array", + "items": { + "$ref": "#/definitions/Business" + }, + "x-go-name": "Business" + }, + "create_time": { + "description": "create time", + "type": "string", + "format": "date-time", + "x-go-name": "CreateTime" + }, + "create_user": { + "$ref": "#/definitions/UidWithName" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "is_fixed_business": { + "description": "is fixed business", + "type": "boolean", + "x-go-name": "IsFixedBusiness" + }, + "name": { + "description": "Project name", + "type": "string", + "x-go-name": "Name" + }, + "project_priority": { + "description": "project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "type": "string", + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "ProjectPriority" + }, + "uid": { + "description": "Project uid", + "type": "string", + "x-go-name": "ProjectUid" + } + }, + "x-go-name": "ListProject", + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ListProjectV2": { + "type": "object", + "properties": { + "archived": { + "description": "Project is archived", + "type": "boolean", + "x-go-name": "Archived" + }, + "business_tag": { + "$ref": "#/definitions/BusinessTagCommon" + }, + "create_time": { + "description": "create time", + "type": "string", + "format": "date-time", + "x-go-name": "CreateTime" + }, + "create_user": { + "$ref": "#/definitions/UidWithName" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "Project name", + "type": "string", + "x-go-name": "Name" + }, + "project_priority": { + "description": "project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "type": "string", + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "ProjectPriority" + }, + "uid": { + "description": "Project uid", + "type": "string", + "x-go-name": "ProjectUid" + } + }, + "x-go-name": "ListProject", + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + }, + "ListRole": { + "description": "A dms role", + "type": "object", + "properties": { + "desc": { + "description": "role desc", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "role name", + "type": "string", + "x-go-name": "Name" + }, + "op_permissions": { + "description": "op permissions", + "type": "array", + "items": { + "$ref": "#/definitions/ListRoleOpPermission" + }, + "x-go-name": "OpPermissions" + }, + "stat": { + "description": "role stat\n正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "type": "string", + "enum": [ + "正常", + "被禁用", + "未知", + "Normal", + "Disabled", + "Unknown" + ], + "x-go-enum-desc": "正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "x-go-name": "Stat" + }, + "uid": { + "description": "role uid", + "type": "string", + "x-go-name": "RoleUid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListRoleOpPermission": { + "type": "object", + "properties": { + "module": { + "type": "string", + "x-go-name": "Module" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListRoleReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List role reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListRole" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListSensitiveDataDiscoveryTaskHistoriesData": { + "type": "object", + "properties": { + "executed_at": { + "description": "execution time in RFC3339 format\nFormat: date-time (RFC3339)", + "type": "string", + "x-go-name": "ExecutedAt", + "example": "\"2024-01-15T10:30:00Z\"" + }, + "new_sensitive_field_count": { + "description": "newly discovered sensitive field count", + "type": "integer", + "format": "int64", + "x-go-name": "NewSensitiveFieldCount", + "example": 10 + }, + "remark": { + "description": "remark", + "type": "string", + "x-go-name": "Remark", + "example": "\"scan completed successfully\"" + }, + "status": { + "description": "execution status\nPENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm\nNORMAL SensitiveDataDiscoveryTaskStatusNormal\nCOMPLETED SensitiveDataDiscoveryTaskStatusCompleted\nRUNNING SensitiveDataDiscoveryTaskStatusRunning\nFAILED SensitiveDataDiscoveryTaskStatusFailed\nSTOPPED SensitiveDataDiscoveryTaskStatusStopped", + "type": "string", + "enum": [ + "PENDING_CONFIRM", + "NORMAL", + "COMPLETED", + "RUNNING", + "FAILED", + "STOPPED" + ], + "x-go-enum-desc": "PENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm\nNORMAL SensitiveDataDiscoveryTaskStatusNormal\nCOMPLETED SensitiveDataDiscoveryTaskStatusCompleted\nRUNNING SensitiveDataDiscoveryTaskStatusRunning\nFAILED SensitiveDataDiscoveryTaskStatusFailed\nSTOPPED SensitiveDataDiscoveryTaskStatusStopped", + "x-go-name": "Status", + "example": "\"NORMAL\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListSensitiveDataDiscoveryTaskHistoriesReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "sensitive data discovery task histories reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListSensitiveDataDiscoveryTaskHistoriesData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "description": "total count of sensitive data discovery task histories", + "type": "integer", + "format": "int64", + "x-go-name": "Total", + "example": 100 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListSensitiveDataDiscoveryTasksData": { + "type": "object", + "properties": { + "db_service_host": { + "description": "database instance host", + "type": "string", + "x-go-name": "DBServiceHost", + "example": "\"10.10.10.10\"" + }, + "db_service_name": { + "description": "database instance name", + "type": "string", + "x-go-name": "DBServiceName", + "example": "\"mysql-01\"" + }, + "db_service_port": { + "description": "database instance port", + "type": "string", + "x-go-name": "DBServicePort", + "example": "\"3306\"" + }, + "db_service_uid": { + "description": "database instance id", + "type": "string", + "x-go-name": "DBServiceUID", + "example": "\"db_service_uid_1\"" + }, + "execution_frequency": { + "description": "cron expression of execution frequency, periodic task returns cron, one-time task returns empty", + "type": "string", + "x-go-name": "ExecutionFrequency", + "example": "\"0 2 * * *\"" + }, + "execution_plan": { + "description": "execution plan\nPERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "type": "string", + "enum": [ + "PERIODIC", + "ONE_TIME" + ], + "x-go-enum-desc": "PERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "x-go-name": "ExecutionPlan", + "example": "\"ONE_TIME\"" + }, + "id": { + "description": "sensitive data discovery task id", + "type": "integer", + "format": "int64", + "x-go-name": "ID", + "example": 1 + }, + "identification_method": { + "description": "sensitive data identification method\nBY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName\nBY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData", + "type": "string", + "enum": [ + "BY_FIELD_NAME", + "BY_SAMPLE_DATA" + ], + "x-go-enum-desc": "BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName\nBY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData", + "x-go-name": "IdentificationMethod", + "example": "\"BY_FIELD_NAME\"" + }, + "is_periodic_scan_enabled": { + "description": "whether periodic scanning is enabled", + "type": "boolean", + "x-go-name": "IsPeriodicScanEnabled", + "example": true + }, + "masking_template_id": { + "description": "related masking template id", + "type": "integer", + "format": "int64", + "x-go-name": "MaskingTemplateID", + "example": 1 + }, + "masking_template_name": { + "description": "related masking template name", + "type": "string", + "x-go-name": "MaskingTemplateName", + "example": "\"Standard Template\"" + }, + "next_execution_at": { + "description": "next run time, periodic task returns RFC3339 time, one-time task returns null\nFormat: date-time (RFC3339)", + "type": "string", + "x-go-name": "NextExecutionAt", + "example": "\"2024-01-15T10:30:00Z\"" + }, + "status": { + "description": "task status\nPENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm\nNORMAL SensitiveDataDiscoveryTaskStatusNormal\nCOMPLETED SensitiveDataDiscoveryTaskStatusCompleted\nRUNNING SensitiveDataDiscoveryTaskStatusRunning\nFAILED SensitiveDataDiscoveryTaskStatusFailed\nSTOPPED SensitiveDataDiscoveryTaskStatusStopped", + "type": "string", + "enum": [ + "PENDING_CONFIRM", + "NORMAL", + "COMPLETED", + "RUNNING", + "FAILED", + "STOPPED" + ], + "x-go-enum-desc": "PENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm\nNORMAL SensitiveDataDiscoveryTaskStatusNormal\nCOMPLETED SensitiveDataDiscoveryTaskStatusCompleted\nRUNNING SensitiveDataDiscoveryTaskStatusRunning\nFAILED SensitiveDataDiscoveryTaskStatusFailed\nSTOPPED SensitiveDataDiscoveryTaskStatusStopped", + "x-go-name": "Status", + "example": "\"NORMAL\"" + }, + "task_type": { + "description": "task type\nPERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "type": "string", + "enum": [ + "PERIODIC", + "ONE_TIME" + ], + "x-go-enum-desc": "PERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "x-go-name": "TaskType", + "example": "\"PERIODIC\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListSensitiveDataDiscoveryTasksReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "sensitive data discovery tasks list reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListSensitiveDataDiscoveryTasksData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "description": "total count of sensitive data discovery tasks", + "type": "integer", + "format": "int64", + "x-go-name": "Total", + "example": 100 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListUser": { + "description": "A dms user", + "type": "object", + "properties": { + "authentication_type": { + "description": "user authentication type\nldap UserAuthenticationTypeLDAP\ndms UserAuthenticationTypeDMS\noauth2 UserAuthenticationTypeOAUTH2\nunknown UserAuthenticationTypeUnknown", + "type": "string", + "enum": [ + "ldap", + "dms", + "oauth2", + "unknown" + ], + "x-go-enum-desc": "ldap UserAuthenticationTypeLDAP\ndms UserAuthenticationTypeDMS\noauth2 UserAuthenticationTypeOAUTH2\nunknown UserAuthenticationTypeUnknown", + "x-go-name": "AuthenticationType" + }, + "email": { + "description": "user email", + "type": "string", + "x-go-name": "Email" + }, + "is_deleted": { + "description": "user is deleted", + "type": "boolean", + "x-go-name": "IsDeleted" + }, + "name": { + "description": "user name", + "type": "string", + "x-go-name": "Name" + }, + "op_permissions": { + "description": "user operation permissions", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "OpPermissions" + }, + "phone": { + "description": "user phone", + "type": "string", + "x-go-name": "Phone" + }, + "projects": { + "description": "projects", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Projects" + }, + "stat": { + "description": "user stat\n正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "type": "string", + "enum": [ + "正常", + "被禁用", + "未知", + "Normal", + "Disabled", + "Unknown" + ], + "x-go-enum-desc": "正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "x-go-name": "Stat" + }, + "system": { + "description": "user system\nWORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "type": "string", + "enum": [ + "WORKBENCH", + "MANAGEMENT" + ], + "x-go-enum-desc": "WORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "x-go-name": "System" + }, + "third_party_user_info": { + "description": "third party user info", + "type": "string", + "x-go-name": "ThirdPartyUserInfo" + }, + "uid": { + "description": "user uid", + "type": "string", + "x-go-name": "UserUid" + }, + "user_groups": { + "description": "user groups", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "UserGroups" + }, + "wxid": { + "description": "user wxid", + "type": "string", + "x-go-name": "WxID" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ListUserGroup": { + "description": "A dms user group", + "type": "object", + "properties": { + "desc": { + "description": "user group description", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "user group name", + "type": "string", + "x-go-name": "Name" + }, + "stat": { + "description": "user group stat\n正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "type": "string", + "enum": [ + "正常", + "被禁用", + "未知", + "Normal", + "Disabled", + "Unknown" + ], + "x-go-enum-desc": "正常 StatOK\n被禁用 StatDisable\n未知 StatUnknown\nNormal StatOKEn\nDisabled StatDisableEn\nUnknown StatUnknownEn", + "x-go-name": "Stat" + }, + "uid": { + "description": "user group uid", + "type": "string", + "x-go-name": "UserGroupUid" + }, + "users": { + "description": "users", + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "Users" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListUserGroupReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List user reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListUserGroup" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ListUserReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "List user reply", + "type": "array", + "items": { + "$ref": "#/definitions/ListUser" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "LoginConfiguration": { + "type": "object", + "properties": { + "disable_user_pwd_login": { + "type": "boolean", + "x-go-name": "DisableUserPwdLogin" + }, + "login_button_text": { + "type": "string", + "x-go-name": "LoginButtonText" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "LoginTipsResData": { + "type": "object", + "properties": { + "disable_user_pwd_login": { + "type": "boolean", + "x-go-name": "DisableUserPwdLogin" + }, + "login_button_text": { + "type": "string", + "x-go-name": "LoginButtonText" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "MIMEHeader": { + "description": "A MIMEHeader represents a MIME-style header mapping\nkeys to sets of values.", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "x-go-package": "net/textproto" + }, + "MaintenanceTime": { + "type": "object", + "properties": { + "maintenance_start_time": { + "$ref": "#/definitions/Time" + }, + "maintenance_stop_time": { + "$ref": "#/definitions/Time" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "MaskingOverviewDashboard": { + "type": "object", + "properties": { + "configured_masking_columns": { + "description": "total count of columns with configured masking", + "type": "integer", + "format": "int64", + "x-go-name": "ConfiguredMaskingColumns", + "example": 120 + }, + "pending_confirm_masking_columns": { + "description": "total count of columns pending masking confirmation", + "type": "integer", + "format": "int64", + "x-go-name": "PendingConfirmMaskingColumns", + "example": 5 + }, + "total_sensitive_tables": { + "description": "total count of tables that contain sensitive data", + "type": "integer", + "format": "int64", + "x-go-name": "TotalSensitiveTables", + "example": 50 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "MaskingOverviewDatabaseNode": { + "type": "object", + "properties": { + "tables": { + "description": "table_name -\u003e table overview data", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/MaskingOverviewTableData" + }, + "x-go-name": "Tables" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "MaskingOverviewTableData": { + "type": "object", + "properties": { + "configured_masking_columns": { + "description": "configured masking column count for this table", + "type": "integer", + "format": "int64", + "x-go-name": "ConfiguredMaskingColumns", + "example": 3 + }, + "pending_confirm_masking_columns": { + "description": "pending masking confirmation column count for this table", + "type": "integer", + "format": "int64", + "x-go-name": "PendingConfirmMaskingColumns", + "example": 1 + }, + "table_id": { + "description": "table id", + "type": "integer", + "format": "int64", + "x-go-name": "TableID", + "example": 1 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "MaskingPreviewData": { + "type": "object", + "properties": { + "columns": { + "description": "preview columns", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Columns", + "example": [ + "id", + "name", + "email" + ] + }, + "rows": { + "description": "preview rows", + "type": "array", + "items": { + "type": "array", + "items": { + "type": "string" + } + }, + "x-go-name": "Rows", + "example": [ + [ + "1", + "John", + "j***@example.com" + ], + [ + "2", + "Alice", + "a***@example.com" + ] + ] + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "MaskingRuleConfig": { + "type": "object", + "required": [ + "db_service_uid", + "schema_name", + "table_name", + "column_name", + "masking_rule_id", + "is_masking_enabled" + ], + "properties": { + "column_name": { + "description": "column name", + "type": "string", + "x-go-name": "ColumnName", + "example": "\"email\"" + }, + "db_service_uid": { + "description": "data source id", + "type": "string", + "x-go-name": "DBServiceUID", + "example": "\"1\"" + }, + "is_masking_enabled": { + "description": "whether to enable masking for this column", + "type": "boolean", + "x-go-name": "IsMaskingEnabled", + "example": true + }, + "masking_rule_id": { + "description": "masking rule id", + "type": "integer", + "format": "int64", + "x-go-name": "MaskingRuleID", + "example": 1 + }, + "schema_name": { + "description": "schema name", + "type": "string", + "x-go-name": "SchemaName", + "example": "\"db1\"" + }, + "table_name": { + "description": "table name", + "type": "string", + "x-go-name": "TableName", + "example": "\"users\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Member": { + "description": "A member", + "type": "object", + "required": [ + "user_uid" + ], + "properties": { + "is_project_admin": { + "description": "Whether the member has project admin permission", + "type": "boolean", + "x-go-name": "IsProjectAdmin" + }, + "project_manage_permissions": { + "description": "member project manage permissions", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ProjectManagePermissions" + }, + "role_with_op_ranges": { + "description": "member role with op ranges", + "type": "array", + "items": { + "$ref": "#/definitions/MemberRoleWithOpRange" + }, + "x-go-name": "RoleWithOpRanges" + }, + "user_uid": { + "description": "member user uid", + "type": "string", + "x-go-name": "UserUid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "MemberGroup": { + "type": "object", + "required": [ + "name", + "user_uids" + ], + "properties": { + "is_project_admin": { + "description": "Whether the member has project admin permission", + "type": "boolean", + "x-go-name": "IsProjectAdmin" + }, + "name": { + "description": "member group name", + "type": "string", + "x-go-name": "Name" + }, + "project_manage_permissions": { + "description": "member project manage permissions", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ProjectManagePermissions" + }, + "role_with_op_ranges": { + "description": "member role with op ranges", + "type": "array", + "items": { + "$ref": "#/definitions/MemberRoleWithOpRange" + }, + "x-go-name": "RoleWithOpRanges" + }, + "user_uids": { + "description": "member user uid", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "UserUids" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "MemberRoleWithOpRange": { + "type": "object", + "properties": { + "op_range_type": { + "description": "op permission range type, only support db service now\nunknown OpRangeTypeUnknown\nglobal OpRangeTypeGlobal 全局权限: 该权限只能被用户使用\nproject OpRangeTypeProject 项目权限: 该权限只能被成员使用\ndb_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用", + "type": "string", + "enum": [ + "unknown", + "global", + "project", + "db_service" + ], + "x-go-enum-desc": "unknown OpRangeTypeUnknown\nglobal OpRangeTypeGlobal 全局权限: 该权限只能被用户使用\nproject OpRangeTypeProject 项目权限: 该权限只能被成员使用\ndb_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用", + "x-go-name": "OpRangeType" + }, + "range_uids": { + "description": "op range uids", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "RangeUIDs" + }, + "role_uid": { + "description": "role uid", + "type": "string", + "x-go-name": "RoleUID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Notification": { + "type": "object", + "properties": { + "notification_body": { + "$ref": "#/definitions/I18nStr" + }, + "notification_subject": { + "$ref": "#/definitions/I18nStr" + }, + "user_uids": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "UserUids" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "NotificationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "Oauth2Configuration": { + "type": "object", + "properties": { + "access_token_tag": { + "type": "string", + "x-go-name": "AccessTokenTag" + }, + "auto_bind_same_name_user": { + "type": "boolean", + "x-go-name": "AutoBindSameNameUser" + }, + "auto_create_user": { + "type": "boolean", + "x-go-name": "AutoCreateUser" + }, + "auto_create_user_pwd": { + "type": "string", + "x-go-name": "AutoCreateUserPWD" + }, + "client_host": { + "type": "string", + "x-go-name": "ClientHost" + }, + "client_id": { + "type": "string", + "x-go-name": "ClientID" + }, + "client_key": { + "type": "string", + "x-go-name": "ClientKey" + }, + "enable_manually_bind": { + "type": "boolean", + "x-go-name": "EnableManuallyBind" + }, + "enable_oauth2": { + "type": "boolean", + "x-go-name": "EnableOauth2" + }, + "login_perm_expr": { + "type": "string", + "x-go-name": "LoginPermExpr" + }, + "login_tip": { + "type": "string", + "maximum": 28, + "x-go-name": "LoginTip" + }, + "scopes": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Scopes" + }, + "server_auth_url": { + "type": "string", + "x-go-name": "ServerAuthUrl" + }, + "server_logout_url": { + "type": "string", + "x-go-name": "ServerLogoutUrl" + }, + "server_token_url": { + "type": "string", + "x-go-name": "ServerTokenUrl" + }, + "server_user_id_url": { + "type": "string", + "x-go-name": "ServerUserIdUrl" + }, + "skip_check_state": { + "type": "boolean", + "x-go-name": "SkipCheckState" + }, + "user_email_tag": { + "type": "string", + "x-go-name": "UserEmailTag" + }, + "user_id_tag": { + "type": "string", + "x-go-name": "UserIdTag" + }, + "user_wechat_tag": { + "type": "string", + "x-go-name": "UserWeChatTag" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Oauth2ConfigurationReq": { + "type": "object", + "properties": { + "oauth2": { + "$ref": "#/definitions/Oauth2Configuration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "OpPermissionItem": { + "type": "object", + "properties": { + "op_permission_type": { + "description": "op permission type\nunknown OpPermissionTypeUnknown\ncreate_project OpPermissionTypeCreateProject 创建项目;创建项目的用户自动拥有该项目管理权限\nglobal_view OpPermissionTypeGlobalView 项目管理;拥有该权限的用户可以管理项目下的所有资源\nglobal_management OpPermissionTypeGlobalManagement 全局浏览;拥有该权限的用户可以浏览全局的资源\nproject_admin OpPermissionTypeProjectAdmin 全局管理;拥有该权限的用户可以浏览和管理全局的资源\ncreate_workflow OpPermissionTypeCreateWorkflow 创建/编辑工单;拥有该权限的用户可以创建/编辑工单\naudit_workflow OpPermissionTypeAuditWorkflow 审核/驳回工单;拥有该权限的用户可以审核/驳回工单\nauth_db_service_data OpPermissionTypeAuthDBServiceData 账号管理;拥有该权限的用户可以授权数据源数据权限\nview_others_workflow OpPermissionTypeViewOthersWorkflow 查看其他工单权限\nexecute_workflow OpPermissionTypeExecuteWorkflow 上线工单;拥有该权限的用户可以上线工单\nview_other_audit_plan OpPermissionTypeViewOtherAuditPlan 查看其他扫描任务权限\nview_sql_insight OpPermissionTypeViewSQLInsight 查看SQL洞察权限\nsave_audit_plan OpPermissionTypeSaveAuditPlan 创建扫描任务权限;拥有该权限的用户可以创建/更新扫描任务\nsql_query OpPermissionTypeSQLQuery SQL查询;SQL查询权限\ncreate_export_task OpPermissionTypeExportCreate 创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单\naudit_export_workflow OpPermissionTypeAuditExportWorkflow 审核/驳回数据导出工单;拥有该权限的用户可以审核/驳回数据导出工单\ncreate_optimization OpPermissionTypeCreateOptimization 创建智能调优;拥有该权限的用户可以创建智能调优\nview_others_optimization OpPermissionTypeViewOthersOptimization 查看他人创建的智能调优\ncreate_pipeline OpPermissionTypeCreatePipeline 配置流水线\nview_operation_record OpPermissionViewOperationRecord SQL工作台;查看所有操作记录\nview_export_task OpPermissionViewExportTask 数据导出;查看所有导出任务\nview_quick_audit_record OpPermissionViewQuickAuditRecord 快捷审核;查看所有快捷审核记录\nview_ide_audit_record OpPermissionViewIDEAuditRecord IDE审核;查看所有IDE审核记录\nview_optimization_record OpPermissionViewOptimizationRecord SQL优化;查看所有优化记录\nview_version_manage OpPermissionViewVersionManage 版本管理;查看他人创建的版本记录\nversion_manage OpPermissionVersionManage 版本管理;配置版本\nview_pipeline OpPermissionViewPipeline CI/CD集成;查看所有流水线\nmanage_project_data_source OpPermissionManageProjectDataSource 数据源管理;管理项目数据源管理\nmanage_audit_rule_template OpPermissionManageAuditRuleTemplate 审核规则模版;管理审核规则模版\nmanage_approval_template OpPermissionManageApprovalTemplate 审批流程模版;管理审批流程模版\nmanage_member OpPermissionManageMember 成员与权限;管理成员与权限\nmanage_push_rule OpPermissionPushRule 推送规则;管理推送规则\nmanage_audit_sql_white_list OpPermissionMangeAuditSQLWhiteList 审核SQL例外;管理审核SQL例外\nmanage_sql_mange_white_list OpPermissionManageSQLMangeWhiteList 管控SQL例外;管理管控SQL例外\nmanage_role_mange OpPermissionManageRoleMange 角色管理;角色管理权限\ndesensitization OpPermissionDesensitization 脱敏规则;脱敏规则配置权限\nmasking_audit OpPermissionMaskingAudit 脱敏审核;拥有该权限的用户可以查看和处理脱敏审批请求\nnone OpPermissionTypeNone 无任何权限", + "type": "string", + "enum": [ + "unknown", + "create_project", + "global_view", + "global_management", + "project_admin", + "create_workflow", + "audit_workflow", + "auth_db_service_data", + "view_others_workflow", + "execute_workflow", + "view_other_audit_plan", + "view_sql_insight", + "save_audit_plan", + "sql_query", + "create_export_task", + "audit_export_workflow", + "create_optimization", + "view_others_optimization", + "create_pipeline", + "view_operation_record", + "view_export_task", + "view_quick_audit_record", + "view_ide_audit_record", + "view_optimization_record", + "view_version_manage", + "version_manage", + "view_pipeline", + "manage_project_data_source", + "manage_audit_rule_template", + "manage_approval_template", + "manage_member", + "manage_push_rule", + "manage_audit_sql_white_list", + "manage_sql_mange_white_list", + "manage_role_mange", + "desensitization", + "masking_audit", + "none" + ], + "x-go-enum-desc": "unknown OpPermissionTypeUnknown\ncreate_project OpPermissionTypeCreateProject 创建项目;创建项目的用户自动拥有该项目管理权限\nglobal_view OpPermissionTypeGlobalView 项目管理;拥有该权限的用户可以管理项目下的所有资源\nglobal_management OpPermissionTypeGlobalManagement 全局浏览;拥有该权限的用户可以浏览全局的资源\nproject_admin OpPermissionTypeProjectAdmin 全局管理;拥有该权限的用户可以浏览和管理全局的资源\ncreate_workflow OpPermissionTypeCreateWorkflow 创建/编辑工单;拥有该权限的用户可以创建/编辑工单\naudit_workflow OpPermissionTypeAuditWorkflow 审核/驳回工单;拥有该权限的用户可以审核/驳回工单\nauth_db_service_data OpPermissionTypeAuthDBServiceData 账号管理;拥有该权限的用户可以授权数据源数据权限\nview_others_workflow OpPermissionTypeViewOthersWorkflow 查看其他工单权限\nexecute_workflow OpPermissionTypeExecuteWorkflow 上线工单;拥有该权限的用户可以上线工单\nview_other_audit_plan OpPermissionTypeViewOtherAuditPlan 查看其他扫描任务权限\nview_sql_insight OpPermissionTypeViewSQLInsight 查看SQL洞察权限\nsave_audit_plan OpPermissionTypeSaveAuditPlan 创建扫描任务权限;拥有该权限的用户可以创建/更新扫描任务\nsql_query OpPermissionTypeSQLQuery SQL查询;SQL查询权限\ncreate_export_task OpPermissionTypeExportCreate 创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单\naudit_export_workflow OpPermissionTypeAuditExportWorkflow 审核/驳回数据导出工单;拥有该权限的用户可以审核/驳回数据导出工单\ncreate_optimization OpPermissionTypeCreateOptimization 创建智能调优;拥有该权限的用户可以创建智能调优\nview_others_optimization OpPermissionTypeViewOthersOptimization 查看他人创建的智能调优\ncreate_pipeline OpPermissionTypeCreatePipeline 配置流水线\nview_operation_record OpPermissionViewOperationRecord SQL工作台;查看所有操作记录\nview_export_task OpPermissionViewExportTask 数据导出;查看所有导出任务\nview_quick_audit_record OpPermissionViewQuickAuditRecord 快捷审核;查看所有快捷审核记录\nview_ide_audit_record OpPermissionViewIDEAuditRecord IDE审核;查看所有IDE审核记录\nview_optimization_record OpPermissionViewOptimizationRecord SQL优化;查看所有优化记录\nview_version_manage OpPermissionViewVersionManage 版本管理;查看他人创建的版本记录\nversion_manage OpPermissionVersionManage 版本管理;配置版本\nview_pipeline OpPermissionViewPipeline CI/CD集成;查看所有流水线\nmanage_project_data_source OpPermissionManageProjectDataSource 数据源管理;管理项目数据源管理\nmanage_audit_rule_template OpPermissionManageAuditRuleTemplate 审核规则模版;管理审核规则模版\nmanage_approval_template OpPermissionManageApprovalTemplate 审批流程模版;管理审批流程模版\nmanage_member OpPermissionManageMember 成员与权限;管理成员与权限\nmanage_push_rule OpPermissionPushRule 推送规则;管理推送规则\nmanage_audit_sql_white_list OpPermissionMangeAuditSQLWhiteList 审核SQL例外;管理审核SQL例外\nmanage_sql_mange_white_list OpPermissionManageSQLMangeWhiteList 管控SQL例外;管理管控SQL例外\nmanage_role_mange OpPermissionManageRoleMange 角色管理;角色管理权限\ndesensitization OpPermissionDesensitization 脱敏规则;脱敏规则配置权限\nmasking_audit OpPermissionMaskingAudit 脱敏审核;拥有该权限的用户可以查看和处理脱敏审批请求\nnone OpPermissionTypeNone 无任何权限", + "x-go-name": "OpPermissionType" + }, + "range_type": { + "description": "object type of RangeUids\nunknown OpRangeTypeUnknown\nglobal OpRangeTypeGlobal 全局权限: 该权限只能被用户使用\nproject OpRangeTypeProject 项目权限: 该权限只能被成员使用\ndb_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用", + "type": "string", + "enum": [ + "unknown", + "global", + "project", + "db_service" + ], + "x-go-enum-desc": "unknown OpRangeTypeUnknown\nglobal OpRangeTypeGlobal 全局权限: 该权限只能被用户使用\nproject OpRangeTypeProject 项目权限: 该权限只能被成员使用\ndb_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用", + "x-go-name": "RangeType" + }, + "range_uids": { + "description": "object uids, object type is defined by RangeType", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "RangeUids" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "OperateDataResourceHandleReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "Operation": { + "type": "object", + "properties": { + "operation_detail": { + "type": "string", + "x-go-name": "OperationDetail" + }, + "operation_type": { + "type": "string", + "enum": [ + "SQL" + ], + "x-go-enum-desc": "SQL CbOperationTypeSQL", + "x-go-name": "OperationType" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "OperationRecord": { + "type": "object", + "properties": { + "operation_action": { + "type": "string", + "x-go-name": "OperationAction" + }, + "operation_i18n_content": { + "$ref": "#/definitions/I18nStr" + }, + "operation_project_name": { + "type": "string", + "x-go-name": "OperationProjectName" + }, + "operation_req_ip": { + "type": "string", + "x-go-name": "OperationReqIP" + }, + "operation_status": { + "type": "string", + "x-go-name": "OperationStatus" + }, + "operation_time": { + "type": "string", + "format": "date-time", + "x-go-name": "OperationTime" + }, + "operation_type_name": { + "type": "string", + "x-go-name": "OperationTypeName" + }, + "operation_user_agent": { + "type": "string", + "x-go-name": "OperationUserAgent" + }, + "operation_user_name": { + "type": "string", + "x-go-name": "OperationUserName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "OperationRecordListItem": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "uint64", + "x-go-name": "ID" + }, + "operation_action": { + "type": "string", + "x-go-name": "OperationAction" + }, + "operation_content": { + "type": "string", + "x-go-name": "OperationContent" + }, + "operation_time": { + "type": "string", + "format": "date-time", + "x-go-name": "OperationTime" + }, + "operation_type_name": { + "type": "string", + "x-go-name": "OperationTypeName" + }, + "operation_user": { + "$ref": "#/definitions/OperationUser" + }, + "operation_user_agent": { + "type": "string", + "x-go-name": "OperationUserAgent" + }, + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + }, + "status": { + "type": "string", + "enum": [ + "succeeded", + "failed" + ], + "x-go-name": "Status" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "OperationUser": { + "type": "object", + "properties": { + "ip": { + "type": "string", + "x-go-name": "IP" + }, + "user_name": { + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Param": { + "type": "object", + "properties": { + "desc": { + "type": "string", + "x-go-name": "Desc" + }, + "key": { + "type": "string", + "x-go-name": "Key" + }, + "type": { + "$ref": "#/definitions/ParamType" + }, + "value": { + "type": "string", + "x-go-name": "Value" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/params" + }, + "ParamType": { + "type": "string", + "x-go-package": "github.com/actiontech/dms/pkg/params" + }, + "Params": { + "type": "array", + "items": { + "$ref": "#/definitions/Param" + }, + "x-go-package": "github.com/actiontech/dms/pkg/params" + }, + "PendingApprovalRequestData": { + "type": "object", + "properties": { + "applicant_name": { + "description": "applicant name", + "type": "string", + "x-go-name": "ApplicantName", + "example": "\"admin\"" + }, + "applied_at": { + "description": "application time in RFC3339 format\nFormat: date-time (RFC3339)", + "type": "string", + "x-go-name": "AppliedAt", + "example": "\"2024-01-15T10:30:00Z\"" + }, + "data_scope": { + "description": "data scope", + "type": "string", + "x-go-name": "DataScope", + "example": "\"database 'db1', table 'users'\"" + }, + "id": { + "description": "approval request id", + "type": "integer", + "format": "int64", + "x-go-name": "ID", + "example": 1 + }, + "reason": { + "description": "application reason", + "type": "string", + "x-go-name": "Reason", + "example": "\"data analysis\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "PersonalizationReq": { + "type": "object", + "properties": { + "file": { + "$ref": "#/definitions/FileHeader" + }, + "title": { + "type": "string", + "x-go-name": "Title" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Plugin": { + "type": "object", + "properties": { + "get_database_driver_logos_url": { + "type": "string", + "x-go-name": "GetDatabaseDriverLogosUrl" + }, + "get_database_driver_options_url": { + "type": "string", + "x-go-name": "GetDatabaseDriverOptionsUrl" + }, + "name": { + "description": "插件名称", + "type": "string", + "x-go-name": "Name" + }, + "operate_data_resource_handle_url": { + "description": "操作资源处理接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/data_resource_operate/handle\n该地址目的是统一调用其他服务 数据资源变更前后校验/更新数据的 接口\neg: 删除数据源前:\n需要sqle服务中实现接口逻辑,判断该数据源上已经没有进行中的工单", + "type": "string", + "x-go-name": "OperateDataResourceHandleUrl" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "PreviewImportProjects": { + "type": "object", + "properties": { + "business": { + "description": "business", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Business" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "Project name", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "PreviewImportProjectsReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "list preview import projects", + "type": "array", + "items": { + "$ref": "#/definitions/PreviewImportProjects" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "PreviewImportProjectsReplyV2": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "list preview import projects", + "type": "array", + "items": { + "$ref": "#/definitions/PreviewImportProjectsV2" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-name": "PreviewImportProjectsReply", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "PreviewImportProjectsV2": { + "type": "object", + "properties": { + "business_tag": { + "$ref": "#/definitions/BusinessTag" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "Project name", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-name": "PreviewImportProjects", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "ProcessApprovalRequestReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProcessApprovalRequestReq": { + "type": "object", + "required": [ + "action" + ], + "properties": { + "action": { + "description": "process action\nAPPROVE ApprovalActionApprove\nREJECT ApprovalActionReject", + "type": "string", + "enum": [ + "APPROVE", + "REJECT" + ], + "x-go-enum-desc": "APPROVE ApprovalActionApprove\nREJECT ApprovalActionReject", + "x-go-name": "Action", + "example": "\"APPROVE\"" + }, + "approve_remark": { + "description": "approval remark, optional when action is APPROVE", + "type": "string", + "x-go-name": "ApproveRemark", + "example": "\"approved for one-time access\"" + }, + "reject_reason": { + "description": "reject reason, required when action is REJECT", + "type": "string", + "x-go-name": "RejectReason", + "example": "\"insufficient reason\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProjectInfo": { + "type": "object", + "properties": { + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + }, + "project_priority": { + "type": "string", + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "ProjectPriority" + }, + "project_uid": { + "type": "string", + "x-go-name": "ProjectUid" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "ProjectManagePermission": { + "type": "object", + "properties": { + "member_group": { + "type": "string", + "x-go-name": "MemberGroup" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProjectMemberGroup": { + "type": "object", + "properties": { + "name": { + "type": "string", + "x-go-name": "Name" + }, + "op_permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "OpPermissions" + }, + "uid": { + "type": "string", + "x-go-name": "Uid" + }, + "users": { + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "Users" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProjectOpPermission": { + "type": "object", + "properties": { + "data_source": { + "type": "string", + "x-go-name": "DataSource" + }, + "roles": { + "type": "array", + "items": { + "$ref": "#/definitions/ProjectRole" + }, + "x-go-name": "Roles" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProjectRole": { + "type": "object", + "properties": { + "member_group": { + "$ref": "#/definitions/ProjectMemberGroup" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "op_permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "OpPermissions" + }, + "uid": { + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProjectTips": { + "type": "object", + "properties": { + "business": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Business" + }, + "is_fixed_business": { + "type": "boolean", + "x-go-name": "IsFixedBusiness" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProjectV1": { + "type": "object", + "properties": { + "business": { + "description": "project business", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Business" + }, + "desc": { + "description": "project desc", + "type": "string", + "x-go-name": "Desc" + }, + "is_fixed_business": { + "description": "is fixed business", + "type": "boolean", + "x-go-name": "IsFixedBusiness" + }, + "name": { + "description": "project name", + "type": "string", + "x-go-name": "Name" + }, + "project_priority": { + "description": "project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "type": "string", + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "ProjectPriority" + } + }, + "x-go-name": "Project", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ProjectV2": { + "type": "object", + "properties": { + "business_tag": { + "$ref": "#/definitions/BusinessTag" + }, + "desc": { + "description": "project desc", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "project name", + "type": "string", + "x-go-name": "Name" + }, + "project_priority": { + "description": "project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "type": "string", + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "ProjectPriority" + } + }, + "x-go-name": "Project", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "RegisterDMSPluginReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "RegisterDMSPluginReq": { + "type": "object", + "properties": { + "plugin": { + "$ref": "#/definitions/Plugin" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "RegisterDMSProxyTargetReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "RegisterDMSProxyTargetReq": { + "type": "object", + "properties": { + "dms_proxy_target": { + "$ref": "#/definitions/DMSProxyTarget" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "RejectDataExportWorkflowPayload": { + "type": "object", + "required": [ + "reason" + ], + "properties": { + "reason": { + "type": "string", + "x-go-name": "Reason" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "RejectDataExportWorkflowReq": { + "type": "object", + "properties": { + "payload": { + "$ref": "#/definitions/RejectDataExportWorkflowPayload" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceBusiness": { + "type": "object", + "properties": { + "business_tag": { + "$ref": "#/definitions/BusinessTag" + }, + "project": { + "type": "array", + "items": { + "$ref": "#/definitions/ResourceProject" + }, + "x-go-name": "Project" + } + }, + "x-go-name": "Business", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceDBService": { + "type": "object", + "properties": { + "db_service_name": { + "type": "string", + "x-go-name": "DBServiceName" + }, + "db_service_uid": { + "type": "string", + "x-go-name": "DBServiceUID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceListData": { + "type": "object", + "properties": { + "audit_score": { + "description": "审核评分", + "type": "number", + "format": "float", + "x-go-name": "AuditScore" + }, + "business_tag": { + "$ref": "#/definitions/BusinessTag" + }, + "environment_tag": { + "$ref": "#/definitions/EnvironmentTag" + }, + "high_priority_sql_count": { + "description": "高优先级SQL数", + "type": "integer", + "format": "int32", + "x-go-name": "HighPrioritySQLCount" + }, + "pending_workflow_count": { + "description": "待处理工单数", + "type": "integer", + "format": "int32", + "x-go-name": "PendingWorkflowCount" + }, + "project": { + "$ref": "#/definitions/ResourceProject" + }, + "resource_name": { + "description": "资源名称", + "type": "string", + "x-go-name": "ResourceName" + }, + "resource_type": { + "description": "资源类型", + "type": "string", + "x-go-name": "ResourceType" + }, + "resource_uid": { + "description": "资源UID", + "type": "string", + "x-go-name": "ResourceUID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceOverviewResourceListResV1": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/ResourceListData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-name": "ResourceOverviewResourceListRes", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceOverviewResourceTypeDistributionResV1": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/ResourceTypeDistributionData" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-name": "ResourceOverviewResourceTypeDistributionRes", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceOverviewStatisticsResV1": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "object", + "properties": { + "business_total_number": { + "description": "业务总数", + "type": "integer", + "format": "int64", + "x-go-name": "BusinessTotalNumber" + }, + "db_service_total_number": { + "description": "数据源总数", + "type": "integer", + "format": "int64", + "x-go-name": "DBServiceTotalNumber" + }, + "project_total_number": { + "description": "项目总数", + "type": "integer", + "format": "int64", + "x-go-name": "ProjectTotalNumber" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-name": "ResourceOverviewStatisticsRes", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceOverviewTopologyResV1": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "business:project = 1:n project:db_service = 1:n", + "type": "array", + "items": { + "$ref": "#/definitions/ResourceBusiness" + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + }, + "total_nums": { + "type": "integer", + "format": "int64", + "x-go-name": "Total" + } + }, + "x-go-name": "ResourceOverviewTopologyRes", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceProject": { + "type": "object", + "properties": { + "db_service": { + "type": "array", + "items": { + "$ref": "#/definitions/ResourceDBService" + }, + "x-go-name": "DBService" + }, + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + }, + "project_uid": { + "type": "string", + "x-go-name": "ProjectUID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "ResourceTypeDistributionData": { + "type": "object", + "properties": { + "count": { + "description": "数量", + "type": "integer", + "format": "int64", + "x-go-name": "Count" + }, + "resource_type": { + "description": "资源类型", + "type": "string", + "x-go-name": "ResourceType" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Role": { + "description": "A role", + "type": "object", + "required": [ + "name" + ], + "properties": { + "desc": { + "description": "role description", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "role name", + "type": "string", + "x-go-name": "Name" + }, + "op_permission_uids": { + "description": "op permission uid", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "OpPermissionUids" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SMTPConfigurationResData": { + "type": "object", + "properties": { + "enable_smtp_notify": { + "type": "boolean", + "x-go-name": "EnableSMTPNotify" + }, + "is_skip_verify": { + "type": "boolean", + "x-go-name": "IsSkipVerify" + }, + "smtp_host": { + "type": "string", + "x-go-name": "Host" + }, + "smtp_port": { + "type": "string", + "x-go-name": "Port" + }, + "smtp_username": { + "type": "string", + "x-go-name": "Username" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SQLEConfig": { + "type": "object", + "properties": { + "audit_enabled": { + "description": "DB Service audit enabled", + "type": "boolean", + "x-go-name": "AuditEnabled" + }, + "data_export_rule_template_id": { + "description": "DB Service data export rule template id", + "type": "string", + "x-go-name": "DataExportRuleTemplateID" + }, + "data_export_rule_template_name": { + "description": "DB Service data export rule template name", + "type": "string", + "x-go-name": "DataExportRuleTemplateName" + }, + "rule_template_id": { + "description": "DB Service rule template id", + "type": "string", + "x-go-name": "RuleTemplateID" + }, + "rule_template_name": { + "description": "DB Service rule template name", + "type": "string", + "x-go-name": "RuleTemplateName" + }, + "sql_query_config": { + "$ref": "#/definitions/SQLQueryConfig" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "SQLQueryConfig": { + "type": "object", + "properties": { + "allow_query_when_less_than_audit_level": { + "type": "string", + "enum": [ + "normal", + "notice", + "warn", + "error" + ], + "x-go-enum-desc": "normal AuditLevelNormal\nnotice AuditLevelNotice\nwarn AuditLevelWarn\nerror AuditLevelError", + "x-go-name": "AllowQueryWhenLessThanAuditLevel" + }, + "audit_enabled": { + "type": "boolean", + "x-go-name": "AuditEnabled" + }, + "maintenance_times": { + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "max_pre_query_rows": { + "type": "integer", + "format": "int64", + "x-go-name": "MaxPreQueryRows" + }, + "query_timeout_second": { + "type": "integer", + "format": "int64", + "x-go-name": "QueryTimeoutSecond" + }, + "rule_template_id": { + "type": "string", + "x-go-name": "RuleTemplateID" + }, + "rule_template_name": { + "type": "string", + "x-go-name": "RuleTemplateName" + }, + "workflow_exec_enabled": { + "type": "boolean", + "x-go-name": "WorkflowExecEnabled" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "SendSmsCodeReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/SendSmsCodeReplyData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SendSmsCodeReplyData": { + "type": "object", + "properties": { + "is_sms_code_sent_normally": { + "type": "boolean", + "x-go-name": "IsSmsCodeSentNormally" + }, + "send_error_message": { + "type": "string", + "x-go-name": "SendErrorMessage" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SendSmsCodeReq": { + "type": "object", + "properties": { + "username": { + "type": "string", + "x-go-name": "Username" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SensitiveFieldScanResult": { + "type": "object", + "properties": { + "confidence": { + "description": "confidence level\nHIGH ConfidenceHigh\nMEDIUM ConfidenceMedium\nLOW ConfidenceLow", + "type": "string", + "enum": [ + "HIGH", + "MEDIUM", + "LOW" + ], + "x-go-enum-desc": "HIGH ConfidenceHigh\nMEDIUM ConfidenceMedium\nLOW ConfidenceLow", + "x-go-name": "Confidence", + "example": "\"High\"" + }, + "recommended_masking_rule_id": { + "description": "recommended masking rule id", + "type": "integer", + "format": "int64", + "x-go-name": "RecommendedMaskingRuleID", + "example": 1 + }, + "recommended_masking_rule_name": { + "description": "recommended masking rule name", + "type": "string", + "x-go-name": "RecommendedMaskingRuleName", + "example": "\"Email Masking\"" + }, + "scan_info": { + "description": "scan information for the field", + "type": "string", + "x-go-name": "ScanInfo", + "example": "\"matched by field name 'email'\"" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SuspectedSensitiveDatabaseNode": { + "type": "object", + "properties": { + "tables": { + "description": "table_name -\u003e table node", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/SuspectedSensitiveTableNode" + }, + "x-go-name": "Tables" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SuspectedSensitiveFieldsTree": { + "type": "object", + "properties": { + "databases": { + "description": "database_name -\u003e database node", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/SuspectedSensitiveDatabaseNode" + }, + "x-go-name": "Databases" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SuspectedSensitiveTableNode": { + "type": "object", + "properties": { + "fields": { + "description": "field_name -\u003e scan result", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/SensitiveFieldScanResult" + }, + "x-go-name": "Fields" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SyncGatewayReq": { + "type": "object", + "properties": { + "gateways": { + "type": "array", + "items": { + "$ref": "#/definitions/Gateway" + }, + "x-go-name": "Gateways" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "SystemVariablesResV1": { + "type": "object", + "properties": { + "cb_operation_logs_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "CbOperationLogsExpiredHours" + }, + "operation_record_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "OperationRecordExpiredHours" + }, + "system_variable_sql_manage_raw_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "SystemVariableSqlManageRawExpiredHours" + }, + "system_variable_ssh_primary_key": { + "type": "string", + "x-go-name": "SystemVariableSSHPrimaryKey" + }, + "system_variable_workflow_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "SystemVariableWorkflowExpiredHours" + }, + "url": { + "type": "string", + "x-go-name": "Url" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "TableColumnMaskingDetail": { + "type": "object", + "properties": { + "column_name": { + "description": "column name", + "type": "string", + "x-go-name": "ColumnName", + "example": "\"email\"" + }, + "confidence": { + "description": "confidence level of masking recommendation,null if no masking rule is applied\nHIGH ConfidenceHigh\nMEDIUM ConfidenceMedium\nLOW ConfidenceLow", + "type": "string", + "enum": [ + "HIGH", + "MEDIUM", + "LOW" + ], + "x-go-enum-desc": "HIGH ConfidenceHigh\nMEDIUM ConfidenceMedium\nLOW ConfidenceLow", + "x-go-name": "Confidence", + "example": "2" + }, + "masking_rule_id": { + "description": "current masking rule id, null if no masking rule is applied", + "type": "integer", + "format": "int64", + "x-go-name": "MaskingRuleID", + "example": 1 + }, + "masking_rule_name": { + "description": "current masking rule name, null if no masking rule is applied", + "type": "string", + "x-go-name": "MaskingRuleName", + "example": "\"Email Masking\"" + }, + "status": { + "description": "current masking config status\nCONFIGURED MaskingConfigStatusConfigured\nPENDING_CONFIRM MaskingConfigStatusPendingConfirm\nSYSTEM_CONFIRMED MaskingConfigStatusSystemConfirmed", + "type": "string", + "enum": [ + "CONFIGURED", + "PENDING_CONFIRM", + "SYSTEM_CONFIRMED" + ], + "x-go-enum-desc": "CONFIGURED MaskingConfigStatusConfigured\nPENDING_CONFIRM MaskingConfigStatusPendingConfirm\nSYSTEM_CONFIRMED MaskingConfigStatusSystemConfirmed", + "x-go-name": "Status" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Task": { + "type": "object", + "properties": { + "task_uid": { + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TaskDBInfo": { + "type": "object", + "properties": { + "database_name": { + "type": "string", + "x-go-name": "DatabaseName" + }, + "db_type": { + "type": "string", + "x-go-name": "DBType" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestFeishuConfiguration": { + "type": "object", + "properties": { + "account": { + "type": "string", + "x-go-name": "Account" + }, + "account_type": { + "type": "string", + "enum": [ + "email", + "phone" + ], + "x-go-enum-desc": "email FeishuAccountTypeEmail\nphone FeishuAccountTypePhone", + "x-go-name": "AccountType" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestFeishuConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/TestFeishuConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestFeishuConfigurationReq": { + "type": "object", + "properties": { + "test_feishu_configuration": { + "$ref": "#/definitions/TestFeishuConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestFeishuConfigurationResData": { + "type": "object", + "properties": { + "error_message": { + "type": "string", + "x-go-name": "ErrorMessage" + }, + "is_message_sent_normally": { + "type": "boolean", + "x-go-name": "IsMessageSentNormally" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSMTPConfiguration": { + "type": "object", + "properties": { + "recipient_addr": { + "type": "string", + "x-go-name": "RecipientAddr" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSMTPConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/TestSMTPConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSMTPConfigurationReq": { + "type": "object", + "properties": { + "test_smtp_configuration": { + "$ref": "#/definitions/TestSMTPConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSMTPConfigurationResData": { + "type": "object", + "properties": { + "is_smtp_send_normal": { + "type": "boolean", + "x-go-name": "IsSMTPSendNormal" + }, + "send_error_message": { + "type": "string", + "x-go-name": "SendErrorMessage" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSmsConfiguration": { + "type": "object", + "properties": { + "recipient_phone": { + "type": "string", + "x-go-name": "RecipientPhone" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSmsConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/TestSmsConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSmsConfigurationReq": { + "type": "object", + "properties": { + "test_sms_configuration": { + "$ref": "#/definitions/TestSmsConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestSmsConfigurationResData": { + "type": "object", + "properties": { + "is_smtp_send_normal": { + "type": "boolean", + "x-go-name": "IsSmsSendNormal" + }, + "send_error_message": { + "type": "string", + "x-go-name": "SendErrorMessage" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestWeChatConfiguration": { + "type": "object", + "properties": { + "recipient_id": { + "type": "string", + "x-go-name": "RecipientID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestWeChatConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/TestWeChatConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestWeChatConfigurationReq": { + "type": "object", + "properties": { + "test_wechat_configuration": { + "$ref": "#/definitions/TestWeChatConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestWeChatConfigurationResData": { + "type": "object", + "properties": { + "is_wechat_send_normal": { + "type": "boolean", + "x-go-name": "IsWeChatSendNormal" + }, + "send_error_message": { + "type": "string", + "x-go-name": "SendErrorMessage" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestWebHookConfigurationReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/TestWebHookConfigurationResData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "TestWebHookConfigurationResData": { + "type": "object", + "properties": { + "is_message_sent_normally": { + "type": "boolean", + "x-go-name": "IsMessageSentNormally" + }, + "send_error_message": { + "type": "string", + "x-go-name": "SendErrorMessage" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "Time": { + "type": "object", + "properties": { + "hour": { + "type": "integer", + "format": "int64", + "x-go-name": "Hour" + }, + "minute": { + "type": "integer", + "format": "int64", + "x-go-name": "Minute" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "TriggerEventType": { + "type": "string", + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + }, + "UidWithDBServiceName": { + "type": "object", + "properties": { + "name": { + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UidWithName": { + "type": "object", + "properties": { + "name": { + "type": "string", + "x-go-name": "Name" + }, + "uid": { + "type": "string", + "x-go-name": "Uid" + } + }, "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" }, - "DelUserGroupPreCheckReply": { - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "UpdateBusinessTagReq": { + "type": "object", + "properties": { + "business_tag": { + "$ref": "#/definitions/BusinessTag" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateCompanyNotice": { + "description": "A companynotice", + "type": "object", + "properties": { + "end_time": { + "description": "notice show end time", + "type": "string", + "format": "date-time", + "x-go-name": "EndTime" + }, + "notice_str": { + "description": "companynotice info", + "type": "string", + "x-go-name": "NoticeStr" + }, + "start_time": { + "description": "notice show start time", + "type": "string", + "format": "date-time", + "x-go-name": "StartTime" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateCompanyNoticeReq": { + "type": "object", + "properties": { + "company_notice": { + "$ref": "#/definitions/UpdateCompanyNotice" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateCurrentUser": { + "type": "object", + "properties": { + "email": { + "description": "User email", + "type": "string", + "x-go-name": "Email" + }, + "language": { + "description": "User language", + "type": "string", + "x-go-name": "Language" + }, + "old_password": { + "description": "User old password", + "type": "string", + "x-go-name": "OldPassword" + }, + "password": { + "description": "User new password", + "type": "string", + "x-go-name": "Password" + }, + "phone": { + "description": "User phone", + "type": "string", + "x-go-name": "Phone" + }, + "system": { + "description": "User system\nWORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "type": "string", + "enum": [ + "WORKBENCH", + "MANAGEMENT" + ], + "x-go-enum-desc": "WORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "x-go-name": "System" + }, + "two_factor_enabled": { + "description": "User two factor enabled", + "type": "boolean", + "x-go-name": "TwoFactorEnabled" + }, + "wxid": { + "description": "User wxid", + "type": "string", + "x-go-name": "WxID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateCurrentUserReq": { + "type": "object", + "properties": { + "current_user": { + "$ref": "#/definitions/UpdateCurrentUser" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateDBService": { + "description": "update db service", + "type": "object", + "required": [ + "db_type", + "host", + "port", + "user", + "business", + "maintenance_times" + ], + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "backup_max_rows": { + "description": "backup switch", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "business": { + "description": "DB Service business name", + "type": "string", + "x-go-name": "Business" + }, + "db_type": { + "description": "Service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "Service description", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "host": { + "description": "DB Service Host", + "type": "string", + "x-go-name": "Host" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "password": { + "description": "DB Service admin password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "DB Service port", + "type": "string", + "x-go-name": "Port" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "user": { + "description": "DB Service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateDBServiceReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "description": "update db service reply", + "type": "object", + "properties": { + "uid": { + "description": "db service UID", + "type": "string", + "x-go-name": "Uid" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateDBServiceReq": { + "type": "object", + "properties": { + "db_service": { + "$ref": "#/definitions/UpdateDBService" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateDBServiceReqV2": { + "type": "object", + "properties": { + "db_service": { + "$ref": "#/definitions/UpdateDBServiceV2" + } + }, + "x-go-name": "UpdateDBServiceReq", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "UpdateDBServiceSyncTaskReq": { + "type": "object", + "properties": { + "db_service_sync_task": { + "$ref": "#/definitions/DBServiceSyncTask" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateDBServiceV2": { + "type": "object", + "required": [ + "db_type", + "host", + "port", + "user", + "environment_tag_uid", + "maintenance_times" + ], + "properties": { + "additional_params": { + "description": "DB Service Custom connection parameters", + "type": "array", + "items": { + "$ref": "#/definitions/AdditionalParam" + }, + "x-go-name": "AdditionalParams" + }, + "backup_max_rows": { + "description": "backup switch", + "type": "integer", + "format": "uint64", + "x-go-name": "BackupMaxRows" + }, + "db_type": { + "description": "Service DB type", + "type": "string", + "x-go-name": "DBType" + }, + "desc": { + "description": "Service description", + "type": "string", + "x-go-name": "Desc" + }, + "enable_backup": { + "description": "backup switch", + "type": "boolean", + "x-go-name": "EnableBackup" + }, + "environment_tag_uid": { + "description": "DB Service environment tag", + "type": "string", + "x-go-name": "EnvironmentTagUID" + }, + "host": { + "description": "DB Service Host", + "type": "string", + "x-go-name": "Host" + }, + "maintenance_times": { + "description": "DB Service maintenance time", + "type": "array", + "items": { + "$ref": "#/definitions/MaintenanceTime" + }, + "x-go-name": "MaintenanceTimes" + }, + "password": { + "description": "DB Service admin password", + "type": "string", + "x-go-name": "Password" + }, + "port": { + "description": "DB Service port", + "type": "string", + "x-go-name": "Port" + }, + "sqle_config": { + "$ref": "#/definitions/SQLEConfig" + }, + "user": { + "description": "DB Service admin user", + "type": "string", + "x-go-name": "User" + } + }, + "x-go-name": "UpdateDBService", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "UpdateEnvironmentTagReq": { + "type": "object", + "properties": { + "environment_name": { + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateFeishuConfiguration": { + "type": "object", + "properties": { + "app_id": { + "type": "string", + "x-go-name": "AppID" + }, + "app_secret": { + "type": "string", + "x-go-name": "AppSecret" + }, + "is_feishu_notification_enabled": { + "type": "boolean", + "x-go-name": "IsFeishuNotificationEnabled" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateFeishuConfigurationReq": { + "type": "object", + "properties": { + "update_feishu_configuration": { + "$ref": "#/definitions/UpdateFeishuConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateGateway": { + "type": "object", + "properties": { + "gateway_address": { + "type": "string", + "x-go-name": "GatewayAddress" + }, + "gateway_desc": { + "type": "string", + "x-go-name": "GatewayDesc" + }, + "gateway_name": { + "type": "string", + "x-go-name": "GatewayName" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateGatewayReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateGatewayReq": { + "type": "object", + "properties": { + "update_gateway": { + "$ref": "#/definitions/UpdateGateway" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateLDAPConfigurationReq": { + "type": "object", + "properties": { + "ldap": { + "$ref": "#/definitions/LDAPConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateLoginConfigurationReq": { + "type": "object", + "properties": { + "login": { + "$ref": "#/definitions/LoginConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateMaskingTemplate": { + "type": "object", + "required": [ + "rule_ids" + ], + "properties": { + "rule_ids": { + "description": "masking rule id list", + "type": "array", + "minLength": 1, + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "RuleIDs", + "example": [ + 1, + 2 + ] + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateMaskingTemplateReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateMaskingTemplateReq": { + "type": "object", + "required": [ + "masking_template" + ], + "properties": { + "masking_template": { + "$ref": "#/definitions/UpdateMaskingTemplate" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateMember": { + "type": "object", + "properties": { + "is_project_admin": { + "description": "Whether the member has project admin permission", + "type": "boolean", + "x-go-name": "IsProjectAdmin" + }, + "project_manage_permissions": { + "description": "member project manage permissions", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ProjectManagePermissions" + }, + "role_with_op_ranges": { + "description": "member role with op ranges", + "type": "array", + "items": { + "$ref": "#/definitions/MemberRoleWithOpRange" + }, + "x-go-name": "RoleWithOpRanges" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateMemberGroup": { + "type": "object", + "required": [ + "user_uids" + ], + "properties": { + "is_project_admin": { + "description": "Whether the member has project admin permission", + "type": "boolean", + "x-go-name": "IsProjectAdmin" + }, + "project_manage_permissions": { + "description": "member project manage permissions", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ProjectManagePermissions" + }, + "role_with_op_ranges": { + "description": "member role with op ranges", + "type": "array", + "items": { + "$ref": "#/definitions/MemberRoleWithOpRange" + }, + "x-go-name": "RoleWithOpRanges" + }, + "user_uids": { + "description": "member user uid", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "UserUids" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateMemberGroupReq": { + "type": "object", + "properties": { + "member_group": { + "$ref": "#/definitions/UpdateMemberGroup" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateMemberReq": { + "type": "object", + "properties": { + "member": { + "$ref": "#/definitions/UpdateMember" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateProject": { + "type": "object", + "properties": { + "business": { + "description": "Project business", + "type": "array", + "items": { + "$ref": "#/definitions/BusinessForUpdate" + }, + "x-go-name": "Business" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "is_fixed_business": { + "description": "is fixed business", + "type": "boolean", + "x-go-name": "IsFixedBusiness" + }, + "project_priority": { + "description": "project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "type": "string", + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "ProjectPriority" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateProjectReq": { + "type": "object", + "properties": { + "project": { + "$ref": "#/definitions/UpdateProject" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateProjectReqV2": { + "type": "object", + "properties": { + "project": { + "$ref": "#/definitions/UpdateProjectV2" + } + }, + "x-go-name": "UpdateProjectReq", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "UpdateProjectV2": { + "type": "object", + "properties": { + "business_tag": { + "$ref": "#/definitions/BusinessTag" + }, + "desc": { + "description": "Project desc", + "type": "string", + "x-go-name": "Desc" + }, + "project_priority": { + "description": "project priority\nhigh ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "type": "string", + "enum": [ + "high", + "medium", + "low", + "unknown" + ], + "x-go-enum-desc": "high ProjectPriorityHigh\nmedium ProjectPriorityMedium\nlow ProjectPriorityLow\nunknown ProjectPriorityUnknown", + "x-go-name": "ProjectPriority" + } + }, + "x-go-name": "UpdateProject", + "x-go-package": "github.com/actiontech/dms/api/dms/service/v2" + }, + "UpdateRole": { + "type": "object", + "properties": { + "desc": { + "description": "Role desc", + "type": "string", + "x-go-name": "Desc" + }, + "is_disabled": { + "description": "Whether the role is disabled or not", + "type": "boolean", + "x-go-name": "IsDisabled" + }, + "op_permission_uids": { + "description": "Op permission uids", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "OpPermissionUids" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateRoleReq": { + "type": "object", + "properties": { + "role": { + "$ref": "#/definitions/UpdateRole" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSMTPConfiguration": { + "type": "object", + "properties": { + "enable_smtp_notify": { + "type": "boolean", + "x-go-name": "EnableSMTPNotify" + }, + "is_skip_verify": { + "type": "boolean", + "x-go-name": "IsSkipVerify" + }, + "smtp_host": { + "type": "string", + "x-go-name": "Host" + }, + "smtp_password": { + "type": "string", + "x-go-name": "Password" + }, + "smtp_port": { + "type": "string", + "x-go-name": "Port" + }, + "smtp_username": { + "type": "string", + "x-go-name": "Username" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSMTPConfigurationReq": { + "type": "object", + "properties": { + "smtp_configuration": { + "$ref": "#/definitions/UpdateSMTPConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSensitiveDataDiscoveryTask": { + "type": "object", + "properties": { + "cron_expression": { + "description": "cron expression, only used when execution_plan is PERIODIC", + "type": "string", + "x-go-name": "CronExpression", + "example": "\"0 0 * * *\"" + }, + "execution_plan": { + "description": "execution plan\nPERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "type": "string", + "enum": [ + "PERIODIC", + "ONE_TIME" + ], + "x-go-enum-desc": "PERIODIC SensitiveDataDiscoveryTaskTypePeriodic\nONE_TIME SensitiveDataDiscoveryTaskTypeOneTime", + "x-go-name": "ExecutionPlan", + "example": "\"PERIODIC\"" + }, + "identification_method": { + "description": "sensitive data identification method\nBY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName\nBY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData", + "type": "string", + "enum": [ + "BY_FIELD_NAME", + "BY_SAMPLE_DATA" + ], + "x-go-enum-desc": "BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName\nBY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData", + "x-go-name": "IdentificationMethod", + "example": "\"BY_FIELD_NAME\"" + }, + "masking_template_id": { + "description": "masking template id", + "type": "integer", + "format": "int64", + "x-go-name": "MaskingTemplateID", + "example": 1 + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSensitiveDataDiscoveryTaskData": { + "type": "object", + "properties": { + "suspected_sensitive_fields_tree": { + "$ref": "#/definitions/SuspectedSensitiveFieldsTree" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSensitiveDataDiscoveryTaskReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/UpdateSensitiveDataDiscoveryTaskData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSensitiveDataDiscoveryTaskReq": { + "type": "object", + "required": [ + "action" + ], + "properties": { + "action": { + "description": "action type: ENABLE(启用周期扫描), TERMINATE(终止周期扫描), UPDATE(更新配置)\nENABLE SensitiveDataDiscoveryTaskActionEnable\nTERMINATE SensitiveDataDiscoveryTaskActionTerminate\nUPDATE SensitiveDataDiscoveryTaskActionUpdate", + "type": "string", + "enum": [ + "ENABLE", + "TERMINATE", + "UPDATE" + ], + "x-go-enum-desc": "ENABLE SensitiveDataDiscoveryTaskActionEnable\nTERMINATE SensitiveDataDiscoveryTaskActionTerminate\nUPDATE SensitiveDataDiscoveryTaskActionUpdate", + "x-go-name": "Action", + "example": "\"ENABLE\"" + }, + "task": { + "$ref": "#/definitions/UpdateSensitiveDataDiscoveryTask" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSmsConfiguration": { + "type": "object", + "properties": { + "configuration": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "x-go-name": "Configuration" + }, + "enable_sms": { + "type": "boolean", + "x-go-name": "EnableSms" + }, + "sms_type": { + "type": "string", + "x-go-name": "SmsType" + }, + "url": { + "type": "string", + "x-go-name": "Url" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + }, + "UpdateSmsConfigurationReq": { + "type": "object", + "properties": { + "update_sms_configuration": { + "$ref": "#/definitions/UpdateSmsConfiguration" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "DelUserPreCheckReply": { + "UpdateSystemVariablesReqV1": { + "type": "object", + "properties": { + "cb_operation_logs_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "CbOperationLogsExpiredHours" + }, + "operation_record_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "OperationRecordExpiredHours" + }, + "system_variable_sql_manage_raw_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "SystemVariableSqlManageRawExpiredHours" + }, + "system_variable_ssh_primary_key": { + "type": "string", + "x-go-name": "SystemVariableSSHPrimaryKey" + }, + "system_variable_workflow_expired_hours": { + "type": "integer", + "format": "int64", + "x-go-name": "SystemVariableWorkflowExpiredHours" + }, + "url": { + "type": "string", + "x-go-name": "Url" + } + }, "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" }, - "GetFeishuConfigurationReply": { + "UpdateUser": { + "type": "object", + "properties": { + "email": { + "description": "User email", + "type": "string", + "x-go-name": "Email" + }, + "is_disabled": { + "description": "Whether the user is disabled or not", + "type": "boolean", + "x-go-name": "IsDisabled" + }, + "language": { + "description": "User language", + "type": "string", + "x-go-name": "Language" + }, + "op_permission_uids": { + "description": "User operation permission uids", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "OpPermissionUids" + }, + "password": { + "description": "User password, User can login with this password", + "type": "string", + "x-go-name": "Password" + }, + "phone": { + "description": "User phone", + "type": "string", + "x-go-name": "Phone" + }, + "system": { + "description": "User system\nWORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "type": "string", + "enum": [ + "WORKBENCH", + "MANAGEMENT" + ], + "x-go-enum-desc": "WORKBENCH UserSystemWorkbench\nMANAGEMENT UserSystemManagement", + "x-go-name": "System" + }, + "third_party_user_id": { + "description": "对接登录的参数", + "type": "string", + "x-go-name": "ThirdPartyUserID" + }, + "third_party_user_info": { + "type": "string", + "x-go-name": "ThirdPartyUserInfo" + }, + "user_authentication_type": { + "type": "string", + "x-go-name": "UserAuthenticationType" + }, + "user_group_uids": { + "description": "User group uids", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "UserGroupUids" + }, + "wxid": { + "description": "User wxid", + "type": "string", + "x-go-name": "WxID" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetLDAPConfigurationResDataReply": { - "x-go-name": "GetLDAPConfigurationReply", + "UpdateUserGroup": { + "type": "object", + "properties": { + "desc": { + "description": "UserGroup description", + "type": "string", + "x-go-name": "Desc" + }, + "is_disabled": { + "description": "Whether the user group is disabled or not", + "type": "boolean", + "x-go-name": "IsDisabled" + }, + "user_uids": { + "description": "User uids", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "UserUids" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetOauth2ConfigurationResDataReply": { - "x-go-name": "GetOauth2ConfigurationReply", + "UpdateUserGroupReq": { + "type": "object", + "properties": { + "user_group": { + "$ref": "#/definitions/UpdateUserGroup" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetOauth2TipsReply": { + "UpdateUserReq": { + "type": "object", + "properties": { + "user": { + "$ref": "#/definitions/UpdateUser" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetSMTPConfigurationReply": { + "UpdateWeChatConfiguration": { + "type": "object", + "properties": { + "agent_id": { + "type": "integer", + "format": "int64", + "x-go-name": "AgentID" + }, + "corp_id": { + "type": "string", + "x-go-name": "CorpID" + }, + "corp_secret": { + "type": "string", + "x-go-name": "CorpSecret" + }, + "enable_wechat_notify": { + "type": "boolean", + "x-go-name": "EnableWeChatNotify" + }, + "proxy_ip": { + "type": "string", + "x-go-name": "ProxyIP" + }, + "safe_enabled": { + "type": "boolean", + "x-go-name": "SafeEnabled" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetSQLQueryConfigurationReply": { + "UpdateWeChatConfigurationReq": { + "type": "object", + "properties": { + "update_wechat_configuration": { + "$ref": "#/definitions/UpdateWeChatConfiguration" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetUserBySessionReply": { + "UpdateWebHookConfigurationReq": { + "type": "object", + "properties": { + "webhook_config": { + "$ref": "#/definitions/WebHookConfigurationData" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetUserOpPermissionReply": { - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "User": { + "description": "A user", + "type": "object", + "required": [ + "name" + ], + "properties": { + "desc": { + "description": "user description", + "type": "string", + "x-go-name": "Desc" + }, + "email": { + "description": "user email", + "type": "string", + "x-go-name": "Email" + }, + "name": { + "description": "user name", + "type": "string", + "x-go-name": "Name" + }, + "op_permission_uids": { + "description": "user op permission uid", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "OpPermissionUids" + }, + "password": { + "description": "user password", + "type": "string", + "x-go-name": "Password" + }, + "phone": { + "description": "user phone", + "type": "string", + "x-go-name": "Phone" + }, + "third_party_user_id": { + "description": "对接登录的参数", + "type": "string", + "x-go-name": "ThirdPartyUserID" + }, + "third_party_user_info": { + "type": "string", + "x-go-name": "ThirdPartyUserInfo" + }, + "uid": { + "type": "string", + "x-go-name": "UID" + }, + "user_authentication_type": { + "type": "string", + "x-go-name": "UserAuthenticationType" + }, + "user_group_uids": { + "description": "user group uid", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "UserGroupUids" + }, + "wxid": { + "description": "user wxid", + "type": "string", + "x-go-name": "WxID" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetUserReply": { + "UserBindProject": { + "type": "object", + "properties": { + "is_manager": { + "type": "boolean", + "x-go-name": "IsManager" + }, + "project_id": { + "type": "string", + "x-go-name": "ProjectID" + }, + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + } + }, "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" }, - "GetWeChatConfigurationReply": { + "UserGroup": { + "description": "A user group", + "type": "object", + "required": [ + "name" + ], + "properties": { + "desc": { + "description": "user group description", + "type": "string", + "x-go-name": "Desc" + }, + "name": { + "description": "user group name", + "type": "string", + "x-go-name": "Name" + }, + "user_uids": { + "description": "user uids", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "UserUids" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "GetWebHookConfigurationReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + "UserOpPermission": { + "type": "object", + "properties": { + "project_uid": { + "description": "uesr project uid", + "type": "string", + "x-go-name": "ProjectUid" + } + }, + "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" }, - "ListDBServiceReply": { + "VerifySmsCodeReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "$ref": "#/definitions/VerifySmsCodeReplyData" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "ListMemberReply": { + "VerifySmsCodeReplyData": { + "type": "object", + "properties": { + "is_verify_sent_normally": { + "type": "boolean", + "x-go-name": "IsVerifyNormally" + }, + "verify_error_message": { + "type": "string", + "x-go-name": "VerifyErrorMessage" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "ListMembersForInternalReply": { - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - }, - "ListNamespaceReply": { - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - }, - "ListOpPermissionReply": { + "VerifySmsCodeReq": { + "type": "object", + "properties": { + "code": { + "type": "string", + "x-go-name": "Code" + }, + "username": { + "type": "string", + "x-go-name": "Username" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "ListRoleReply": { + "VerifyUserLoginReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "data": { + "type": "object", + "properties": { + "phone": { + "type": "string", + "x-go-name": "Phone" + }, + "two_factor_enabled": { + "type": "boolean", + "x-go-name": "TwoFactorEnabled" + }, + "user_uid": { + "description": "If verify Successful, return user uid", + "type": "string", + "x-go-name": "UserUid" + }, + "verify_failed_msg": { + "description": "If verify Successful, return empty string, otherwise return error message", + "type": "string", + "x-go-name": "VerifyFailedMsg" + } + }, + "x-go-name": "Data" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "ListUserGroupReply": { + "WeChatConfigurationResData": { + "type": "object", + "properties": { + "agent_id": { + "type": "integer", + "format": "int64", + "x-go-name": "AgentID" + }, + "corp_id": { + "type": "string", + "x-go-name": "CorpID" + }, + "enable_wechat_notify": { + "type": "boolean", + "x-go-name": "EnableWeChatNotify" + }, + "proxy_ip": { + "type": "string", + "x-go-name": "ProxyIP" + }, + "safe_enabled": { + "type": "boolean", + "x-go-name": "SafeEnabled" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "ListUserReply": { - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - }, - "NotificationReply": { - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "WebHookConfigurationData": { + "type": "object", + "properties": { + "enable": { + "type": "boolean", + "x-go-name": "Enable" + }, + "max_retry_times": { + "description": "minlength(3) maxlength(100)", + "type": "integer", + "format": "int64", + "x-go-name": "MaxRetryTimes" + }, + "retry_interval_seconds": { + "type": "integer", + "format": "int64", + "x-go-name": "RetryIntervalSeconds" + }, + "token": { + "type": "string", + "x-go-name": "Token" + }, + "url": { + "type": "string", + "x-go-name": "URL" + } + }, + "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "OperateDataResourceHandleReply": { + "WebHookSendMessageReply": { + "type": "object", + "properties": { + "code": { + "description": "code", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "message", + "type": "string", + "x-go-name": "Message" + } + }, + "x-go-name": "WebHooksSendMessageReply", "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" }, - "RegisterDMSPluginReply": { + "WebHookSendMessageReq": { + "type": "object", + "properties": { + "webhook_message": { + "$ref": "#/definitions/WebHooksMessage" + } + }, "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" }, - "RegisterDMSProxyTargetReply": { + "WebHooksMessage": { + "type": "object", + "properties": { + "message": { + "type": "string", + "x-go-name": "Message" + }, + "trigger_event_type": { + "$ref": "#/definitions/TriggerEventType" + } + }, "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" }, - "TestFeishuConfigurationReply": { + "WorkflowRecord": { + "type": "object", + "properties": { + "current_step_number": { + "type": "integer", + "format": "uint64", + "x-go-name": "CurrentStepNumber" + }, + "status": { + "type": "string", + "enum": [ + "wait_for_approve", + "wait_for_export", + "exporting", + "rejected", + "cancel", + "failed", + "finish" + ], + "x-go-enum-desc": "wait_for_approve DataExportWorkflowStatusWaitForApprove\nwait_for_export DataExportWorkflowStatusWaitForExport\nexporting DataExportWorkflowStatusWaitForExporting\nrejected DataExportWorkflowStatusRejected\ncancel DataExportWorkflowStatusCancel\nfailed DataExportWorkflowStatusFailed\nfinish DataExportWorkflowStatusFinish", + "x-go-name": "Status" + }, + "tasks": { + "type": "array", + "items": { + "$ref": "#/definitions/Task" + }, + "x-go-name": "Tasks" + }, + "workflow_step_list": { + "type": "array", + "items": { + "$ref": "#/definitions/WorkflowStep" + }, + "x-go-name": "Steps" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" }, - "TestSMTPConfigurationReply": { + "WorkflowStep": { + "type": "object", + "properties": { + "assignee_user_list": { + "type": "array", + "items": { + "$ref": "#/definitions/UidWithName" + }, + "x-go-name": "Users" + }, + "desc": { + "type": "string", + "x-go-name": "Desc" + }, + "number": { + "type": "integer", + "format": "uint64", + "x-go-name": "Number" + }, + "operation_time": { + "type": "string", + "format": "date-time", + "x-go-name": "OperationTime" + }, + "operation_user": { + "$ref": "#/definitions/UidWithName" + }, + "reason": { + "type": "string", + "x-go-name": "Reason" + }, + "state": { + "type": "string", + "enum": [ + "init", + "rejected", + "finish" + ], + "x-go-enum-desc": "init WorkflowStepStatusWaitForExporting\nrejected WorkflowStepStatusRejected\nfinish WorkflowStepStatusFinish", + "x-go-name": "State" + }, + "type": { + "type": "string", + "x-go-name": "Type" + } + }, "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + } + }, + "responses": { + "DownloadDataExportTaskReply": { + "description": "", + "schema": { + "type": "file" + } }, - "TestWeChatConfigurationReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + "DownloadDataExportTaskSQLsReply": { + "description": "", + "schema": { + "type": "file" + } }, - "TestWebHookConfigurationReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + "DownloadResourceOverviewListRes": { + "description": "", + "schema": { + "type": "file" + } }, - "UpdateDBServiceReply": { - "x-go-package": "github.com/actiontech/dms/api/dms/service/v1" + "ExportCBOperationLogsReply": { + "description": "", + "schema": { + "type": "file" + } + }, + "ExportOperationRecordListReply": { + "description": "", + "schema": { + "type": "file" + } + }, + "ExportProjectsReply": { + "description": "", + "schema": { + "type": "file" + } }, - "WebHookSendMessageReply": { - "x-go-name": "WebHooksSendMessageReply", - "x-go-package": "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - } - }, - "responses": { "GenericResp": { "description": "GenericResp defines the return code and msg", "headers": { @@ -2147,16 +17685,48 @@ "format": "int64", "description": "code" }, - "msg": { + "message": { "type": "string", "description": "message" } } + }, + "GetImportDBServicesTemplateReply": { + "description": "", + "schema": { + "type": "file" + } + }, + "GetImportProjectsTemplateReply": { + "description": "", + "schema": { + "type": "file" + } + }, + "GetLicenseInfoReply": { + "description": "", + "schema": { + "type": "file" + } + }, + "GetStaticLogoReply": { + "description": "", + "schema": { + "type": "file" + } + }, + "ImportDBServicesCheckCsvReply": { + "description": "", + "schema": { + "type": "file" + } } }, "securityDefinitions": { "basic": { - "type": "basic" + "type": "apiKey", + "name": "Authorization", + "in": "header" } } } \ No newline at end of file diff --git a/api/swagger.yaml b/api/swagger.yaml index 8a57118ff..83735307e 100644 --- a/api/swagger.yaml +++ b/api/swagger.yaml @@ -2,121 +2,11207 @@ basePath: / consumes: - application/json definitions: - AddDBServicePreCheckReply: + AccessTokenInfo: + properties: + access_token: + type: string + x-go-name: AccessToken + is_expired: + type: boolean + x-go-name: IsExpired + token_expired_timestamp: + type: string + x-go-name: ExpiredTime + type: object x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 AddDBServiceReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add db service reply + properties: + uid: + description: db service UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddDBServiceReq: + properties: + db_service: + $ref: '#/definitions/DBService' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddDBServiceReqV2: + properties: + db_service: + $ref: '#/definitions/DBServiceV2' + type: object + x-go-name: AddDBServiceReq + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + AddDBServiceSyncTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: add database source service reply + properties: + uid: + description: db service UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddDBServiceSyncTaskReq: + properties: + db_service_sync_task: + $ref: '#/definitions/DBServiceSyncTask' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddDataExportTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: add data export workflow reply + properties: + data_export_task_uids: + description: data export task UIDs + items: + type: string + type: array + x-go-name: Uids + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddDataExportTaskReq: + properties: + data_export_tasks: + items: + $ref: '#/definitions/DataExportTask' + type: array + x-go-name: DataExportTasks + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddDataExportWorkflowReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: add data export workflow reply + properties: + export_data_workflow_uid: + description: data export workflow UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddDataExportWorkflowReq: + properties: + data_export_workflow: + $ref: '#/definitions/DataExportWorkflow' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddGatewayReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddGatewayReq: + properties: + add_gateway: + $ref: '#/definitions/Gateway' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddMaskingTemplate: + properties: + name: + description: masking template name + example: '"New Template"' + type: string + x-go-name: Name + rule_ids: + description: masking rule id list + example: + - 1 + - 2 + - 3 + items: + format: int64 + type: integer + minLength: 1 + type: array + x-go-name: RuleIDs + required: + - name + - rule_ids + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddMaskingTemplateReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddMaskingTemplateReq: + properties: + masking_template: + $ref: '#/definitions/AddMaskingTemplate' + required: + - masking_template + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddMemberGroupReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add member group reply + properties: + id: + description: member group ID + type: string + x-go-name: Id + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddMemberGroupReq: + properties: + member_group: + $ref: '#/definitions/MemberGroup' + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 AddMemberReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add member reply + properties: + uid: + description: member UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddMemberReq: + properties: + member: + $ref: '#/definitions/Member' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddOperationRecordReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddOperationRecordReq: + properties: + operation_record: + $ref: '#/definitions/OperationRecord' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddProjectReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add Project reply + properties: + uid: + description: Project UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - AddNamespaceReply: + AddProjectReplyV2: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add Project reply + properties: + uid: + description: Project UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-name: AddProjectReply + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + AddProjectReq: + properties: + project: + $ref: '#/definitions/ProjectV1' + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddProjectReqV2: + properties: + project: + $ref: '#/definitions/ProjectV2' + type: object + x-go-name: AddProjectReq + x-go-package: github.com/actiontech/dms/api/dms/service/v2 AddRoleReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add role reply + properties: + uid: + description: role UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddRoleReq: + properties: + role: + $ref: '#/definitions/Role' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddSensitiveDataDiscoveryTask: + properties: + cron_expression: + description: cron expression, required when execution_plan is PERIODIC + example: '"0 0 * * *"' + type: string + x-go-name: CronExpression + db_service_uid: + description: database instance id + example: '"1"' + type: string + x-go-name: DBServiceUID + execution_plan: + description: |- + execution plan + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + enum: + - PERIODIC + - ONE_TIME + example: '"ONE_TIME"' + type: string + x-go-enum-desc: |- + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + x-go-name: ExecutionPlan + identification_method: + description: |- + sensitive data identification method + BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName + BY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData + enum: + - BY_FIELD_NAME + - BY_SAMPLE_DATA + example: '"BY_FIELD_NAME"' + type: string + x-go-enum-desc: |- + BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName + BY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData + x-go-name: IdentificationMethod + is_periodic_scan_enabled: + description: whether periodic scanning is enabled, default is true + example: true + type: boolean + x-go-name: IsPeriodicScanEnabled + masking_template_id: + description: masking template id + example: 1 + format: int64 + type: integer + x-go-name: MaskingTemplateID + required: + - db_service_uid + - masking_template_id + - identification_method + - execution_plan + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddSensitiveDataDiscoveryTaskData: + properties: + suspected_sensitive_fields_tree: + $ref: '#/definitions/SuspectedSensitiveFieldsTree' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddSensitiveDataDiscoveryTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/AddSensitiveDataDiscoveryTaskData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddSensitiveDataDiscoveryTaskReq: + properties: + task: + $ref: '#/definitions/AddSensitiveDataDiscoveryTask' + required: + - task + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddSession: + description: Use this struct to add a new session + properties: + password: + description: User password + type: string + x-go-name: Password + username: + description: User name + type: string + x-go-name: UserName + verify_code: + description: VerifyCode + type: string + x-go-name: VerifyCode + required: + - username + - password + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 AddSessionReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add user reply + properties: + message: + description: Message + type: string + x-go-name: Message + token: + description: Session token + type: string + x-go-name: Token + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + AddSessionReq: + properties: + session: + $ref: '#/definitions/AddSession' + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 AddUserGroupReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add user group reply + properties: + uid: + description: user group UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - AddUserReply: + AddUserGroupReq: + properties: + user_group: + $ref: '#/definitions/UserGroup' + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - BindOauth2UserReply: + AddUserReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Add user reply + properties: + uid: + description: user UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - CheckDBServiceIsConnectableReply: + AddUserReq: + properties: + user: + $ref: '#/definitions/User' + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - DelDBServicePreCheckReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - DelUserGroupPreCheckReply: + AdditionalParam: + properties: + description: + type: string + x-go-name: Description + name: + type: string + x-go-name: Name + type: + type: string + x-go-name: Type + value: + type: string + x-go-name: Value + type: object x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - DelUserPreCheckReply: + AuditPlanTypes: + properties: + audit_plan_id: + format: uint64 + type: integer + x-go-name: AuditPlanId + desc: + type: string + x-go-name: AuditPlanTypeDesc + type: + type: string + x-go-name: AuditPlanType + type: object x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - GetFeishuConfigurationReply: + AuditSQLResult: + properties: + db_type: + type: string + x-go-name: DBType + error_info: + type: string + x-go-name: ErrorInfo + execution_failed: + type: boolean + x-go-name: ExecutionFailed + level: + type: string + x-go-name: Level + message: + type: string + x-go-name: Message + rule_name: + type: string + x-go-name: RuleName + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetLDAPConfigurationResDataReply: - x-go-name: GetLDAPConfigurationReply + AuditTaskResult: + description: SQL审核结果 + properties: + audit_level: + type: string + x-go-name: AuditLevel + pass_rate: + format: double + type: number + x-go-name: PassRate + score: + format: int32 + type: integer + x-go-name: Score + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetOauth2ConfigurationResDataReply: - x-go-name: GetOauth2ConfigurationReply + BasicInfo: + properties: + components: + items: + $ref: '#/definitions/ComponentNameWithVersion' + type: array + x-go-name: Components + logo_url: + type: string + x-go-name: LogoUrl + title: + type: string + x-go-name: Title + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetOauth2TipsReply: + BatchGetDataExportTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/GetDataExportTask' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetSMTPConfigurationReply: + BindOauth2UserReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/BindOauth2UserResData' + message: + description: message + type: string + x-go-name: Message + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetSQLQueryConfigurationReply: + BindOauth2UserReq: + properties: + oauth2_token: + type: string + x-go-name: Oauth2Token + pwd: + type: string + x-go-name: Pwd + refresh_token: + type: string + x-go-name: RefreshToken + user_name: + type: string + x-go-name: UserName + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetUserBySessionReply: + BindOauth2UserResData: + properties: + token: + type: string + x-go-name: Token + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetUserOpPermissionReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - GetUserReply: + Business: + properties: + id: + type: string + x-go-name: Id + is_used: + type: boolean + x-go-name: IsUsed + name: + type: string + x-go-name: Name + type: object x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - GetWeChatConfigurationReply: + BusinessForUpdate: + properties: + id: + type: string + x-go-name: ID + name: + type: string + x-go-name: Name + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - GetWebHookConfigurationReply: + BusinessTag: + properties: + name: + description: 业务标签最多50个字符 + type: string + x-go-name: Name + uid: + type: string + x-go-name: UID + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - ListDBServiceReply: + BusinessTagCommon: + properties: + name: + description: 业务标签最多50个字符 + type: string + x-go-name: Name + uid: + type: string + x-go-name: UID + type: object + x-go-name: BusinessTag + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v2 + CBOperationLog: + properties: + audit_result: + items: + $ref: '#/definitions/AuditSQLResult' + type: array + x-go-name: AuditResult + db_service: + $ref: '#/definitions/UidWithDBServiceName' + exec_result: + type: string + x-go-name: ExecResult + exec_time_second: + format: int64 + type: integer + x-go-name: ExecTimeSecond + operation: + $ref: '#/definitions/Operation' + operation_ip: + type: string + x-go-name: OperationIp + operation_person: + $ref: '#/definitions/UidWithName' + operation_time: + format: date-time + type: string + x-go-name: OperationTime + result_set_row_count: + format: int64 + type: integer + x-go-name: ResultSetRowCount + session_id: + type: string + x-go-name: SessionID + uid: + type: string + x-go-name: UID + workflow_id: + type: string + x-go-name: WorkflowID + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - ListMemberReply: + CBOperationLogTips: + properties: + exec_result: + items: + type: string + type: array + x-go-name: ExecResult + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - ListMembersForInternalReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - ListNamespaceReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - ListOpPermissionReply: + CancelDataExportWorkflowPayload: + properties: + data_export_workflow_uids: + items: + type: string + type: array + x-go-name: DataExportWorkflowUids + required: + - data_export_workflow_uids + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - ListRoleReply: + CancelDataExportWorkflowReq: + properties: + payload: + $ref: '#/definitions/CancelDataExportWorkflowPayload' + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - ListUserGroupReply: + CheckDBServiceIsConnectableByIdReq: + properties: + db_service_uid: + type: string + x-go-name: DBServiceUid + project_uid: + type: string + x-go-name: ProjectUid + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - ListUserReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - NotificationReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - OperateDataResourceHandleReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - RegisterDMSPluginReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - RegisterDMSProxyTargetReply: - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 - TestFeishuConfigurationReply: + CheckDBServiceIsConnectableReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/CheckDBServiceIsConnectableReplyItem' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - TestSMTPConfigurationReply: + CheckDBServiceIsConnectableReplyItem: + properties: + component: + type: string + x-go-name: Component + connect_error_message: + type: string + x-go-name: ConnectErrorMessage + is_connectable: + type: boolean + x-go-name: IsConnectable + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - TestWeChatConfigurationReply: + CheckDBServiceIsConnectableReq: + properties: + db_service: + $ref: '#/definitions/CheckDbConnectable' + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - TestWebHookConfigurationReply: + CheckDBServicesIsConnectableReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/DBServiceIsConnectableReply' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - UpdateDBServiceReply: + CheckDBServicesIsConnectableReq: + properties: + db_services: + items: + $ref: '#/definitions/DbServiceConnections' + type: array + x-go-name: DBServices + type: object x-go-package: github.com/actiontech/dms/api/dms/service/v1 - WebHookSendMessageReply: - x-go-name: WebHooksSendMessageReply - x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 -info: - description: Documentation of our dms API. - title: dms api. - version: 0.1.0 -paths: - /v1/dms/configurations/feishu: - get: - operationId: GetFeishuConfiguration - responses: + CheckDBServicesPrivilegesItem: + properties: + CheckDBServicesPrivileges: + items: + $ref: '#/definitions/CheckDBServiceIsConnectableReplyItem' + type: array + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CheckDBServicesPrivilegesReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/CheckDBServicesPrivilegesItem' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CheckDBServicesPrivilegesReq: + properties: + db_services: + items: + $ref: '#/definitions/CheckDbConnectable' + type: array + x-go-name: DBServices + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CheckDbConnectable: + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + db_type: + description: DB Service type + example: MySQL + type: string + x-go-name: DBType + host: + description: DB Service host + example: 127.0.0.1 + type: string + x-go-name: Host + password: + description: DB Service admin password + example: "123456" + type: string + x-go-name: Password + port: + description: DB Service port + example: "3306" + type: string + x-go-name: Port + user: + description: DB Service admin user + example: root + type: string + x-go-name: User + required: + - db_type + - user + - host + - port + - password + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + CheckDbsConnectable: + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + db_type: + description: DB Service type + example: MySQL + type: string + x-go-name: DBType + host: + description: DB Service host + example: 127.0.0.1 + type: string + x-go-name: Host + name: + description: DB Service name + example: mysql_1 + type: string + x-go-name: Name + password: + description: DB Service admin password + example: "123456" + type: string + x-go-name: Password + port: + description: DB Service port + example: "3306" + type: string + x-go-name: Port + user: + description: DB Service admin user + example: root + type: string + x-go-name: User + required: + - name + - db_type + - user + - host + - port + - password + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CheckLicenseReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + content: + type: string + x-go-name: Content + license: + items: + $ref: '#/definitions/LicenseItem' + type: array + x-go-name: License + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CompanyNotice: + description: A companynotice + properties: + create_user_name: + description: companynotice creator name + type: string + x-go-name: CreateUserName + expire_time: + description: notice expire time + format: date-time + type: string + x-go-name: ExpireTime + notice_str: + description: companynotice info + type: string + x-go-name: NoticeStr + read_by_current_user: + description: current user has been read + type: boolean + x-go-name: ReadByCurrentUser + start_time: + description: notice show start time + format: date-time + type: string + x-go-name: StartTime + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ComponentNameWithVersion: + properties: + name: + type: string + x-go-name: Name + version: + type: string + x-go-name: Version + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ConfigureMaskingRulesReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ConfigureMaskingRulesReq: + properties: + masking_rule_configs: + description: masking rule configurations for batch create or update + items: + $ref: '#/definitions/MaskingRuleConfig' + minLength: 1 + type: array + x-go-name: MaskingRuleConfigs + required: + - masking_rule_configs + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CreateBusinessTagReq: + properties: + business_tag: + $ref: '#/definitions/BusinessTag' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CreateEnvironmentTagReq: + properties: + environment_name: + type: string + x-go-name: Name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + CurrentProjectAdmin: + properties: + is_admin: + type: boolean + x-go-name: IsAdmin + member_groups: + items: + type: string + type: array + x-go-name: MemberGroups + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBService: + description: A db service + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + backup_max_rows: + description: backup switch + format: uint64 + type: integer + x-go-name: BackupMaxRows + business: + description: DB Service business name + type: string + x-go-name: Business + db_type: + description: Service DB type + type: string + x-go-name: DBType + desc: + description: Service description + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + host: + description: DB Service Host + type: string + x-go-name: Host + maintenance_times: + description: |- + DB Service maintenance time + empty value means that maintenance time is unlimited + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: Service name + type: string + x-go-name: Name + password: + description: DB Service admin password + type: string + x-go-name: Password + port: + description: DB Service port + type: string + x-go-name: Port + sqle_config: + $ref: '#/definitions/SQLEConfig' + user: + description: DB Service admin user + type: string + x-go-name: User + required: + - name + - db_type + - host + - port + - user + - password + - business + - maintenance_times + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServiceConnectionReq: + properties: + db_services: + items: + $ref: '#/definitions/CheckDbsConnectable' + type: array + x-go-name: DBServices + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServiceIsConnectableReply: + properties: + connect_error_message: + type: string + x-go-name: ConnectErrorMessage + connection_status: + enum: + - connect_success + - connect_failed + type: string + x-go-enum-desc: |- + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + x-go-name: ConnectionStatus + db_service_uid: + type: string + x-go-name: DBServiceUid + test_connection_time: + format: date-time + type: string + x-go-name: TestConnectionTime + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServiceSourceName: + type: string + x-go-package: github.com/actiontech/dms/internal/dms/pkg/constant + DBServiceSyncTask: + properties: + additional_params: + $ref: '#/definitions/Params' + cron_express: + description: cron expression + example: 0 0 * * * + type: string + x-go-name: CronExpress + db_type: + description: database type + example: MySQL + type: string + x-go-name: DbType + name: + description: name + example: dmp + type: string + x-go-name: Name + source: + description: source + example: actiontech-dmp + type: string + x-go-name: Source + sqle_config: + $ref: '#/definitions/SQLEConfig' + url: + description: addr + example: http://10.186.62.56:10000 + type: string + x-go-name: URL + required: + - name + - source + - url + - db_type + - cron_express + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServiceSyncTaskTip: + properties: + db_type: + items: + $ref: '#/definitions/DBType' + type: array + x-go-name: DBType + description: + type: string + x-go-name: Desc + params: + $ref: '#/definitions/Params' + service_source_name: + $ref: '#/definitions/DBServiceSourceName' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServiceUidWithNameInfo: + properties: + DBServiceName: + type: string + DBServiceUid: + type: string + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + DBServiceV2: + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + backup_max_rows: + description: backup switch + format: uint64 + type: integer + x-go-name: BackupMaxRows + db_type: + description: Service DB type + type: string + x-go-name: DBType + desc: + description: Service description + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + environment_tag_uid: + description: DB Service environment tag + type: string + x-go-name: EnvironmentTagUID + host: + description: DB Service Host + type: string + x-go-name: Host + maintenance_times: + description: |- + DB Service maintenance time + empty value means that maintenance time is unlimited + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: Service name + type: string + x-go-name: Name + password: + description: DB Service admin password + type: string + x-go-name: Password + port: + description: DB Service port + type: string + x-go-name: Port + sqle_config: + $ref: '#/definitions/SQLEConfig' + user: + description: DB Service admin user + type: string + x-go-name: User + required: + - name + - db_type + - host + - port + - user + - password + - environment_tag_uid + - maintenance_times + type: object + x-go-name: DBService + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + DBServicesConnectionItem: + properties: + failed_names: + description: Failed DBServices name + items: + type: string + type: array + x-go-name: FailedNames + failed_num: + description: Failed connection num + format: int64 + type: integer + x-go-name: FailedNum + successful_num: + description: Successful connection num + format: int64 + type: integer + x-go-name: SuccessfulNum + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServicesConnectionReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/DBServicesConnectionItem' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServicesConnectionReq: + properties: + db_services: + items: + $ref: '#/definitions/DbServiceConnections' + type: array + x-go-name: DBServices + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBServicesConnectionReqReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/DBServiceIsConnectableReply' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DBType: + type: string + x-go-package: github.com/actiontech/dms/internal/dms/pkg/constant + DMSProxyTarget: + description: A dms proxy target + properties: + addr: + description: 'target addr, eg: http://10.1.2.1:5432' + type: string + x-go-name: Addr + name: + description: target name + type: string + x-go-name: Name + proxy_url_prefixs: + description: 'url prefix that need to be proxy, eg: /v1/user' + items: + type: string + type: array + x-go-name: ProxyUrlPrefixs + scenario: + description: |- + the scenario is used to differentiate scenarios + internal_service ProxyScenarioInternalService + thrid_party_integrate ProxyScenarioThirdPartyIntegrate + enum: + - internal_service + - thrid_party_integrate + type: string + x-go-enum-desc: |- + internal_service ProxyScenarioInternalService + thrid_party_integrate ProxyScenarioThirdPartyIntegrate + x-go-name: Scenario + version: + description: version number + type: string + x-go-name: Version + required: + - name + - addr + - version + - proxy_url_prefixs + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + DataExportTask: + properties: + database_name: + description: DB Service name + type: string + x-go-name: DatabaseName + db_service_uid: + description: DB Service uid + type: string + x-go-name: DBServiceUid + export_sql: + description: |- + The exported SQL statement executed. it's necessary when ExportType is SQL + SELECT * FROM DMS_test LIMIT 20; + type: string + x-go-name: ExportSQL + required: + - db_service_uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DataExportWorkflow: + properties: + desc: + description: desc + example: transaction data export + type: string + x-go-name: Desc + name: + description: name + example: d1 + type: string + x-go-name: Name + tasks: + description: export task info + example: '[export_task_uid1,export_task_uid2]' + items: + $ref: '#/definitions/Task' + type: array + x-go-name: Tasks + required: + - name + - tasks + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DatabaseDriverAdditionalParam: + properties: + description: + type: string + x-go-name: Description + name: + type: string + x-go-name: Name + type: + type: string + x-go-name: Type + value: + type: string + x-go-name: Value + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DatabaseDriverOption: + properties: + db_type: + type: string + x-go-name: DBType + logo_path: + type: string + x-go-name: LogoPath + params: + items: + $ref: '#/definitions/DatabaseDriverAdditionalParam' + type: array + x-go-name: Params + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DateTime: + description: |- + DateTime is a time but it serializes to ISO8601 format with millis + It knows how to read 3 different variations of a RFC3339 date time. + Most APIs we encounter want either millisecond or second precision times. + This just tries to make it worry-free. + format: date-time + type: string + x-go-package: github.com/go-openapi/strfmt + DbServiceConnections: + properties: + db_service_uid: + type: string + x-go-name: DBServiceUid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DelSessionReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Del session reply + properties: + location: + description: Session token + type: string + x-go-name: Location + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DeleteGatewayReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DeleteMaskingTemplateReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + DeleteSensitiveDataDiscoveryTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + EnvironmentTag: + properties: + name: + description: 环境属性标签最多50个字符 + type: string + x-go-name: Name + uid: + type: string + x-go-name: UID + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + FeishuConfigurationResData: + properties: + app_id: + type: string + x-go-name: AppID + is_feishu_notification_enabled: + type: boolean + x-go-name: IsFeishuNotificationEnabled + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + FileHeader: + properties: + Filename: + type: string + Header: + $ref: '#/definitions/MIMEHeader' + Size: + format: int64 + type: integer + title: A FileHeader describes a file part of a multipart request. + type: object + x-go-package: mime/multipart + Gateway: + properties: + gateway_address: + type: string + x-go-name: GatewayAddress + gateway_desc: + type: string + x-go-name: GatewayDesc + gateway_id: + type: string + x-go-name: GatewayID + gateway_name: + type: string + x-go-name: GatewayName + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GenAccessToken: + properties: + expiration_days: + type: string + x-go-name: ExpirationDays + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GenAccessTokenReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/AccessTokenInfo' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GenericResp: + description: GenericResp defines the return code and msg + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/base/v1 + GetBasicInfoReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/BasicInfo' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetCBOperationLogTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/CBOperationLogTips' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetCompanyNoticeReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/CompanyNotice' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetDBServiceSyncTask: + properties: + additional_params: + $ref: '#/definitions/Params' + cron_express: + description: cron expression + example: 0 0 * * * + type: string + x-go-name: CronExpress + db_type: + description: database type + example: MySQL + type: string + x-go-name: DbType + name: + description: name + example: dmp + type: string + x-go-name: Name + source: + description: source + example: actiontech-dmp + type: string + x-go-name: Source + sqle_config: + $ref: '#/definitions/SQLEConfig' + uid: + type: string + x-go-name: UID + url: + description: addr + example: http://10.186.62.56:10000 + type: string + x-go-name: URL + required: + - name + - source + - url + - db_type + - cron_express + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetDBServiceSyncTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetDBServiceSyncTask' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetDataExportTask: + properties: + audit_result: + $ref: '#/definitions/AuditTaskResult' + db_info: + $ref: '#/definitions/TaskDBInfo' + export_end_time: + format: date-time + type: string + x-go-name: ExportEndTime + export_file_type: + type: string + x-go-name: ExportFileType + export_start_time: + format: date-time + type: string + x-go-name: ExportStartTime + export_type: + type: string + x-go-name: ExportType + file_name: + type: string + x-go-name: FileName + status: + enum: + - init + - exporting + - finish + - failed + - file_deleted + type: string + x-go-enum-desc: |- + init StatusInit + exporting StatusExporting + finish StatusFinish + failed StatusFailed + file_deleted StatusFileDeleted + x-go-name: Status + task_uid: + type: string + x-go-name: TaskUid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetDataExportWorkflow: + properties: + create_time: + format: date-time + type: string + x-go-name: CreateTime + create_user: + $ref: '#/definitions/UidWithName' + desc: + type: string + x-go-name: Desc + workflow_name: + type: string + x-go-name: Name + workflow_record: + $ref: '#/definitions/WorkflowRecord' + workflow_record_history: + items: + $ref: '#/definitions/WorkflowRecord' + type: array + x-go-name: WorkflowRecordHistory + workflow_uid: + type: string + x-go-name: WorkflowID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetDataExportWorkflowReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetDataExportWorkflow' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetFeishuConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/FeishuConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetGatewayReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/Gateway' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetGatewayTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: GatewayTips + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetGlobalDataExportWorkflowsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/GlobalDataExportWorkflow' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetLDAPConfigurationResDataReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/LDAPConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-name: GetLDAPConfigurationReply + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetLicenseReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + content: + type: string + x-go-name: Content + license: + items: + $ref: '#/definitions/LicenseItem' + type: array + x-go-name: License + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetLicenseUsageReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/LicenseUsage' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetLoginTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/LoginTipsResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetMaskingOverviewTreeData: + properties: + dashboard: + $ref: '#/definitions/MaskingOverviewDashboard' + databases: + additionalProperties: + $ref: '#/definitions/MaskingOverviewDatabaseNode' + description: database_name -> database node + type: object + x-go-name: Databases + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetMaskingOverviewTreeReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetMaskingOverviewTreeData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetMemberGroup: + properties: + is_project_admin: + description: Whether the member has project admin permission + type: boolean + x-go-name: IsProjectAdmin + name: + type: string + x-go-name: Name + role_with_op_ranges: + description: member op permission + items: + $ref: '#/definitions/ListMemberRoleWithOpRange' + type: array + x-go-name: RoleWithOpRanges + uid: + description: member group uid + type: string + x-go-name: Uid + users: + description: member user + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: Users + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GetMemberGroupReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetMemberGroup' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GetOauth2ConfigurationResData: + properties: + access_token_tag: + type: string + x-go-name: AccessTokenTag + auto_bind_same_name_user: + type: boolean + x-go-name: AutoBindSameNameUser + auto_create_user: + type: boolean + x-go-name: AutoCreateUser + back_channel_logout_uri: + type: string + x-go-name: BackChannelLogoutUri + client_host: + type: string + x-go-name: ClientHost + client_id: + type: string + x-go-name: ClientID + enable_manually_bind: + type: boolean + x-go-name: EnableManuallyBind + enable_oauth2: + type: boolean + x-go-name: EnableOauth2 + login_perm_expr: + type: string + x-go-name: LoginPermExpr + login_tip: + type: string + x-go-name: LoginTip + scopes: + items: + type: string + type: array + x-go-name: Scopes + server_auth_url: + type: string + x-go-name: ServerAuthUrl + server_logout_url: + type: string + x-go-name: ServerLogoutUrl + server_token_url: + type: string + x-go-name: ServerTokenUrl + server_user_id_url: + type: string + x-go-name: ServerUserIdUrl + skip_check_state: + type: boolean + x-go-name: SkipCheckState + user_email_tag: + type: string + x-go-name: UserEmailTag + user_id_tag: + type: string + x-go-name: UserIdTag + user_wechat_tag: + type: string + x-go-name: UserWeChatTag + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetOauth2ConfigurationResDataReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetOauth2ConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-name: GetOauth2ConfigurationReply + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetOauth2TipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetOauth2TipsResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetOauth2TipsResData: + properties: + enable_oauth2: + type: boolean + x-go-name: EnableOauth2 + login_tip: + type: string + x-go-name: LoginTip + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetOperationRecordListReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/OperationRecordListItem' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: uint64 + type: integer + x-go-name: TotalNums + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetPlaintextAccessRequestDetailReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: plaintext access request detail reply + properties: + masking_preview: + $ref: '#/definitions/MaskingPreviewData' + query_sql: + description: query sql statement + example: '"SELECT * FROM users"' + type: string + x-go-name: QuerySQL + reason: + description: application reason + example: '"troubleshooting"' + type: string + x-go-name: Reason + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetProjectTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: project tips + items: + $ref: '#/definitions/ProjectTips' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetSMTPConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/SMTPConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetSQLQueryConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + properties: + enable_odc_query: + type: boolean + x-go-name: EnableOdcQuery + enable_sql_query: + type: boolean + x-go-name: EnableSQLQuery + odc_query_root_uri: + type: string + x-go-name: OdcQueryRootURI + sql_query_root_uri: + type: string + x-go-name: SQLQueryRootURI + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetSmsConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetSmsConfigurationReplyItem' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetSmsConfigurationReplyItem: + properties: + configuration: + additionalProperties: + type: string + type: object + x-go-name: Configuration + enable: + type: boolean + x-go-name: Enable + sms_type: + type: string + x-go-name: SmsType + url: + type: string + x-go-name: Url + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetSystemVariablesReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/SystemVariablesResV1' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GetTableColumnMaskingDetailsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: table column masking details reply + items: + $ref: '#/definitions/TableColumnMaskingDetail' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetUser: + description: A dms user + properties: + access_token_info: + $ref: '#/definitions/AccessTokenInfo' + authentication_type: + description: |- + user authentication type + ldap UserAuthenticationTypeLDAP + dms UserAuthenticationTypeDMS + oauth2 UserAuthenticationTypeOAUTH2 + unknown UserAuthenticationTypeUnknown + enum: + - ldap + - dms + - oauth2 + - unknown + type: string + x-go-enum-desc: |- + ldap UserAuthenticationTypeLDAP + dms UserAuthenticationTypeDMS + oauth2 UserAuthenticationTypeOAUTH2 + unknown UserAuthenticationTypeUnknown + x-go-name: AuthenticationType + email: + description: user email + type: string + x-go-name: Email + is_admin: + description: is admin + type: boolean + x-go-name: IsAdmin + language: + description: user language + type: string + x-go-name: Language + name: + description: user name + type: string + x-go-name: Name + op_permissions: + description: user operation permissions + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: OpPermissions + phone: + description: user phone + type: string + x-go-name: Phone + stat: + description: |- + user stat + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + enum: + - 正常 + - 被禁用 + - 未知 + - Normal + - Disabled + - Unknown + type: string + x-go-enum-desc: |- + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + x-go-name: Stat + system: + description: |- + user system + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + enum: + - WORKBENCH + - MANAGEMENT + type: string + x-go-enum-desc: |- + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + x-go-name: System + third_party_user_info: + type: string + x-go-name: ThirdPartyUserInfo + two_factor_enabled: + description: user two factor enabled + type: boolean + x-go-name: TwoFactorEnabled + uid: + description: user uid + type: string + x-go-name: UserUid + user_bind_projects: + description: user bind name space + items: + $ref: '#/definitions/UserBindProject' + type: array + x-go-name: UserBindProjects + user_groups: + description: user groups + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: UserGroups + wxid: + description: user wxid + type: string + x-go-name: WxID + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GetUserBySessionReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: Get user reply + properties: + name: + description: User name + type: string + x-go-name: Name + user_uid: + description: User UID + type: string + x-go-name: UserUid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetUserOpPermissionReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: |- + user op permission reply + is user admin, admin has all permissions + properties: + is_admin: + type: boolean + x-go-name: IsAdmin + op_permission_list: + description: user op permissions + items: + $ref: '#/definitions/OpPermissionItem' + type: array + x-go-name: OpPermissionList + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GetUserReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetUser' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + GetWeChatConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/WeChatConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetWebHookConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/GetWebHookConfigurationReplyItem' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GetWebHookConfigurationReplyItem: + properties: + enable: + type: boolean + x-go-name: Enable + max_retry_times: + description: minlength(3) maxlength(100) + format: int64 + type: integer + x-go-name: MaxRetryTimes + retry_interval_seconds: + format: int64 + type: integer + x-go-name: RetryIntervalSeconds + token: + type: string + x-go-name: Token + url: + type: string + x-go-name: URL + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + GlobalDataExportWorkflow: + properties: + created_at: + format: date-time + type: string + x-go-name: CreatedAt + creater: + $ref: '#/definitions/UidWithName' + current_step_assignee_user_list: + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: CurrentStepAssigneeUsers + db_service_info: + items: + $ref: '#/definitions/DBServiceUidWithNameInfo' + type: array + x-go-name: DBServiceInfos + desc: + type: string + x-go-name: Description + project_info: + $ref: '#/definitions/ProjectInfo' + status: + enum: + - wait_for_approve + - wait_for_export + - exporting + - rejected + - cancel + - failed + - finish + type: string + x-go-enum-desc: |- + wait_for_approve DataExportWorkflowStatusWaitForApprove + wait_for_export DataExportWorkflowStatusWaitForExport + exporting DataExportWorkflowStatusWaitForExporting + rejected DataExportWorkflowStatusRejected + cancel DataExportWorkflowStatusCancel + failed DataExportWorkflowStatusFailed + finish DataExportWorkflowStatusFinish + x-go-name: Status + workflow_name: + type: string + x-go-name: WorkflowName + workflow_uid: + type: string + x-go-name: WorkflowID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + I18nStr: + x-go-package: github.com/actiontech/dms/pkg/dms-common/i18nPkg + ImportDBService: + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + business: + description: |- + the db service business name + Deprecated: the business field is replaced with the environmentTag of the v2 interface. + type: string + x-go-name: Business + db_type: + description: db service DB type + type: string + x-go-name: DBType + desc: + description: DB desc + type: string + x-go-name: Desc + host: + description: db service host + type: string + x-go-name: Host + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: db service name + type: string + x-go-name: Name + password: + description: db service admin encrypted password + type: string + x-go-name: Password + port: + description: db service port + type: string + x-go-name: Port + project_uid: + description: DB project uid + type: string + x-go-name: ProjectUID + source: + description: DB source + type: string + x-go-name: Source + sqle_config: + $ref: '#/definitions/SQLEConfig' + user: + description: db service admin user + type: string + x-go-name: User + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ImportDBServiceV2: + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + db_type: + description: db service DB type + type: string + x-go-name: DBType + desc: + description: DB desc + type: string + x-go-name: Desc + environment_tag_name: + description: DB Service environment tag uid + type: string + x-go-name: EnvironmentTagName + host: + description: db service host + type: string + x-go-name: Host + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: db service name + type: string + x-go-name: Name + password: + description: db service admin encrypted password + type: string + x-go-name: Password + port: + description: db service port + type: string + x-go-name: Port + project_uid: + description: DB project uid + type: string + x-go-name: ProjectUID + source: + description: DB source + type: string + x-go-name: Source + sqle_config: + $ref: '#/definitions/SQLEConfig' + user: + description: db service admin user + type: string + x-go-name: User + required: + - environment_tag_name + type: object + x-go-name: ImportDBService + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ImportDBServicesCheckReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: db services + items: + $ref: '#/definitions/ImportDBService' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ImportDBServicesCheckReplyV2: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: db services + items: + $ref: '#/definitions/ImportDBServiceV2' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-name: ImportDBServicesCheckReply + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ImportDBServicesOfOneProjectReq: + properties: + db_services: + items: + $ref: '#/definitions/ImportDBService' + type: array + x-go-name: DBServices + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ImportDBServicesOfOneProjectReqV2: + properties: + db_services: + items: + $ref: '#/definitions/ImportDBServiceV2' + type: array + x-go-name: DBServices + type: object + x-go-name: ImportDBServicesOfOneProjectReq + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ImportDBServicesOfProjectsReq: + properties: + db_services: + items: + $ref: '#/definitions/ImportDBService' + type: array + x-go-name: DBServices + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ImportDBServicesOfProjectsReqV2: + properties: + db_services: + items: + $ref: '#/definitions/ImportDBServiceV2' + type: array + x-go-name: DBServices + type: object + x-go-name: ImportDBServicesOfProjectsReq + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ImportProjects: + properties: + business: + description: business + items: + type: string + type: array + x-go-name: Business + desc: + description: Project desc + type: string + x-go-name: Desc + name: + description: Project name + type: string + x-go-name: Name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ImportProjectsReq: + properties: + projects: + items: + $ref: '#/definitions/ImportProjects' + type: array + x-go-name: Projects + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ImportProjectsReqV2: + properties: + projects: + items: + $ref: '#/definitions/ImportProjectsV2' + type: array + x-go-name: Projects + type: object + x-go-name: ImportProjectsReq + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ImportProjectsV2: + properties: + business_tag: + $ref: '#/definitions/BusinessTag' + desc: + description: Project desc + type: string + x-go-name: Desc + name: + description: Project name + type: string + x-go-name: Name + type: object + x-go-name: ImportProjects + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + LDAPConfiguration: + properties: + enable_ldap: + type: boolean + x-go-name: EnableLdap + enable_ssl: + type: boolean + x-go-name: EnableSSL + ldap_connect_dn: + type: string + x-go-name: LdapConnectDn + ldap_connect_pwd: + type: string + x-go-name: LdapConnectPwd + ldap_search_base_dn: + type: string + x-go-name: LdapSearchBaseDn + ldap_server_host: + type: string + x-go-name: LdapServerHost + ldap_server_port: + type: string + x-go-name: LdapServerPort + ldap_user_email_rdn_key: + type: string + x-go-name: LdapUserEmailRdnKey + ldap_user_name_rdn_key: + type: string + x-go-name: LdapUserNameRdnKey + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + LDAPConfigurationResData: + properties: + enable_ldap: + type: boolean + x-go-name: EnableLdap + enable_ssl: + type: boolean + x-go-name: EnableSSL + ldap_connect_dn: + type: string + x-go-name: LdapConnectDn + ldap_search_base_dn: + type: string + x-go-name: LdapSearchBaseDn + ldap_server_host: + type: string + x-go-name: LdapServerHost + ldap_server_port: + type: string + x-go-name: LdapServerPort + ldap_user_email_rdn_key: + type: string + x-go-name: LdapUserEmailRdnKey + ldap_user_name_rdn_key: + type: string + x-go-name: LdapUserNameRdnKey + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + LicenseItem: + properties: + description: + type: string + x-go-name: Description + limit: + type: string + x-go-name: Limit + name: + type: string + x-go-name: Name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + LicenseUsage: + properties: + db_services_usage: + items: + $ref: '#/definitions/LicenseUsageItem' + type: array + x-go-name: DbServicesUsage + users_usage: + $ref: '#/definitions/LicenseUsageItem' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + LicenseUsageItem: + properties: + is_limited: + type: boolean + x-go-name: IsLimited + limit: + format: uint64 + type: integer + x-go-name: Limit + resource_type: + type: string + x-go-name: ResourceType + resource_type_desc: + type: string + x-go-name: ResourceTypeDesc + used: + format: uint64 + type: integer + x-go-name: Used + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListBusinessTagsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/BusinessTag' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListCBOperationLogsReply: + properties: + audit_intercepted_sql_count: + description: 审核拦截的异常SQL数量 + format: int64 + type: integer + x-go-name: AuditInterceptedSQLCount + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: list cb operation logs reply + items: + $ref: '#/definitions/CBOperationLog' + type: array + x-go-name: Data + exec_failed_sql_count: + description: 执行失败的SQL + format: int64 + type: integer + x-go-name: ExecFailedSQLCount + exec_sql_total: + description: 执行SQL总量 + format: int64 + type: integer + x-go-name: ExecSQLTotal + exec_success_rate: + description: 执行成功率 + format: double + type: number + x-go-name: ExecSuccessRate + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListCreatableDBServicesForMaskingTaskData: + properties: + db_service_host: + description: database instance host + example: '"10.10.10.10"' + type: string + x-go-name: DBServiceHost + db_service_name: + description: database instance name + example: '"mysql-01"' + type: string + x-go-name: DBServiceName + db_service_port: + description: database instance port + example: '"3306"' + type: string + x-go-name: DBServicePort + db_service_uid: + description: database instance uid + example: '"db_service_uid_1"' + type: string + x-go-name: DBServiceUID + db_type: + description: database type + example: '"MySQL"' + type: string + x-go-name: DBType + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListCreatableDBServicesForMaskingTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: list of db services that can create masking discovery task + items: + $ref: '#/definitions/ListCreatableDBServicesForMaskingTaskData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + description: total count of db services + example: 10 + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDBService: + description: A dms db Service + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + audit_plan_types: + description: audit plan types + items: + $ref: '#/definitions/AuditPlanTypes' + type: array + x-go-name: AuditPlanTypes + backup_max_rows: + description: backup max rows + format: uint64 + type: integer + x-go-name: BackupMaxRows + business: + description: |- + TODO This parameter is deprecated and will be removed soon. + the db service business name + type: string + x-go-name: Business + db_type: + description: db service DB type + type: string + x-go-name: DBType + desc: + description: DB desc + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + host: + description: db service host + type: string + x-go-name: Host + instance_audit_plan_id: + description: instance audit plan id + format: uint64 + type: integer + x-go-name: InstanceAuditPlanID + is_enable_masking: + description: is enable masking + type: boolean + x-go-name: IsEnableMasking + last_connection_test_error_message: + description: DB connect test error message + type: string + x-go-name: LastConnectionTestErrorMessage + last_connection_test_status: + description: |- + DB connect test status + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + enum: + - connect_success + - connect_failed + type: string + x-go-enum-desc: |- + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + x-go-name: LastConnectionTestStatus + last_connection_test_time: + description: DB connection test time + format: date-time + type: string + x-go-name: LastConnectionTestTime + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: db service name + type: string + x-go-name: Name + password: + description: db service admin encrypted password + type: string + x-go-name: Password + port: + description: db service port + type: string + x-go-name: Port + project_uid: + description: DB project uid + type: string + x-go-name: ProjectUID + source: + description: DB source + type: string + x-go-name: Source + sqle_config: + $ref: '#/definitions/SQLEConfig' + uid: + description: db service uid + type: string + x-go-name: DBServiceUid + user: + description: db service admin user + type: string + x-go-name: User + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ListDBServiceDriverOptionReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List db service reply + items: + $ref: '#/definitions/DatabaseDriverOption' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDBServiceReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List db service reply + items: + $ref: '#/definitions/ListDBService' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ListDBServiceReplyV2: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List db service reply + items: + $ref: '#/definitions/ListDBServiceV2' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-name: ListDBServiceReply + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v2 + ListDBServiceSyncTask: + properties: + additional_params: + $ref: '#/definitions/Params' + cron_express: + description: cron expression + example: 0 0 * * * + type: string + x-go-name: CronExpress + db_type: + description: database type + example: MySQL + type: string + x-go-name: DbType + last_sync_err: + description: last sync error message + type: string + x-go-name: LastSyncErr + last_sync_success_time: + format: date-time + type: string + x-go-name: LastSyncSuccessTime + name: + description: name + example: dmp + type: string + x-go-name: Name + source: + description: source + example: actiontech-dmp + type: string + x-go-name: Source + sqle_config: + $ref: '#/definitions/SQLEConfig' + uid: + type: string + x-go-name: UID + url: + description: addr + example: http://10.186.62.56:10000 + type: string + x-go-name: URL + required: + - name + - source + - url + - db_type + - cron_express + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDBServiceSyncTaskTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/DBServiceSyncTaskTip' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDBServiceSyncTasksReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/ListDBServiceSyncTask' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDBServiceTipItem: + properties: + db_type: + type: string + x-go-name: Type + host: + type: string + x-go-name: Host + id: + type: string + x-go-name: Id + name: + type: string + x-go-name: Name + port: + type: string + x-go-name: Port + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDBServiceTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List db service reply + items: + $ref: '#/definitions/ListDBServiceTipItem' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDBServiceV2: + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + audit_plan_types: + description: audit plan types + items: + $ref: '#/definitions/AuditPlanTypes' + type: array + x-go-name: AuditPlanTypes + backup_max_rows: + description: backup max rows + format: uint64 + type: integer + x-go-name: BackupMaxRows + db_type: + description: db service DB type + type: string + x-go-name: DBType + desc: + description: DB desc + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + environment_tag: + $ref: '#/definitions/EnvironmentTag' + host: + description: db service host + type: string + x-go-name: Host + instance_audit_plan_id: + description: instance audit plan id + format: uint64 + type: integer + x-go-name: InstanceAuditPlanID + is_enable_masking: + description: is enable masking + type: boolean + x-go-name: IsEnableMasking + last_connection_test_error_message: + description: DB connect test error message + type: string + x-go-name: LastConnectionTestErrorMessage + last_connection_test_status: + description: |- + DB connect test status + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + enum: + - connect_success + - connect_failed + type: string + x-go-enum-desc: |- + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + x-go-name: LastConnectionTestStatus + last_connection_test_time: + description: DB connection test time + format: date-time + type: string + x-go-name: LastConnectionTestTime + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: db service name + type: string + x-go-name: Name + password: + description: db service admin encrypted password + type: string + x-go-name: Password + port: + description: db service port + type: string + x-go-name: Port + project_uid: + description: DB project uid + type: string + x-go-name: ProjectUID + source: + description: DB source + type: string + x-go-name: Source + sqle_config: + $ref: '#/definitions/SQLEConfig' + uid: + description: db service uid + type: string + x-go-name: DBServiceUid + user: + description: db service admin user + type: string + x-go-name: User + type: object + x-go-name: ListDBService + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v2 + ListDataExportTaskSQL: + properties: + audit_level: + type: string + x-go-name: AuditLevel + audit_sql_result: + items: + $ref: '#/definitions/AuditSQLResult' + type: array + x-go-name: AuditSQLResult + export_result: + type: string + x-go-name: ExportResult + export_sql_type: + type: string + x-go-name: ExportSQLType + sql: + type: string + x-go-name: ExportSQL + uid: + format: uint64 + type: integer + x-go-name: ID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDataExportTaskSQLsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/ListDataExportTaskSQL' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDataExportWorkflow: + properties: + created_at: + format: date-time + type: string + x-go-name: CreatedAt + creater: + $ref: '#/definitions/UidWithName' + current_step_assignee_user_list: + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: CurrentStepAssigneeUsers + db_service_info: + items: + $ref: '#/definitions/DBServiceUidWithNameInfo' + type: array + x-go-name: DBServiceInfos + desc: + type: string + x-go-name: Description + exported_at: + format: date-time + type: string + x-go-name: ExportedAt + project_info: + $ref: '#/definitions/ProjectInfo' + project_name: + type: string + x-go-name: ProjectName + project_uid: + type: string + x-go-name: ProjectUid + status: + enum: + - wait_for_approve + - wait_for_export + - exporting + - rejected + - cancel + - failed + - finish + type: string + x-go-enum-desc: |- + wait_for_approve DataExportWorkflowStatusWaitForApprove + wait_for_export DataExportWorkflowStatusWaitForExport + exporting DataExportWorkflowStatusWaitForExporting + rejected DataExportWorkflowStatusRejected + cancel DataExportWorkflowStatusCancel + failed DataExportWorkflowStatusFailed + finish DataExportWorkflowStatusFinish + x-go-name: Status + workflow_name: + type: string + x-go-name: WorkflowName + workflow_uid: + type: string + x-go-name: WorkflowID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListDataExportWorkflowsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/ListDataExportWorkflow' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListEnvironmentTagsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/EnvironmentTag' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListGatewaysReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/Gateway' + type: array + x-go-name: Gateways + message: + description: message + type: string + x-go-name: Message + total: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListGlobalDBService: + properties: + backup_max_rows: + description: backup switch + format: uint64 + type: integer + x-go-name: BackupMaxRows + business: + description: |- + TODO This parameter is deprecated and will be removed soon. + the db service business name + Deprecated: the business field is replaced with the environmentTag of the v2 interface. + type: string + x-go-name: Business + db_type: + description: db service DB type + type: string + x-go-name: DBType + desc: + description: DB desc + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + host: + description: db service host + type: string + x-go-name: Host + is_enable_audit: + description: is enable audit + type: boolean + x-go-name: IsEnableAudit + is_enable_masking: + description: is enable masking + type: boolean + x-go-name: IsEnableMasking + last_connection_test_error_message: + description: DB connect test error message + type: string + x-go-name: LastConnectionTestErrorMessage + last_connection_test_status: + description: |- + DB connect test status + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + enum: + - connect_success + - connect_failed + type: string + x-go-enum-desc: |- + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + x-go-name: LastConnectionTestStatus + last_connection_test_time: + description: DB connection test time + format: date-time + type: string + x-go-name: LastConnectionTestTime + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: db service name + type: string + x-go-name: Name + port: + description: db service port + type: string + x-go-name: Port + project_name: + description: db service project_name + type: string + x-go-name: ProjectName + project_uid: + description: DB project uid + type: string + x-go-name: ProjectUID + source: + description: DB source + type: string + x-go-name: Source + uid: + description: db service uid + type: string + x-go-name: DBServiceUid + unfinished_workflow_num: + description: db service unfinished workflow num + format: int64 + type: integer + x-go-name: UnfinishedWorkflowNum + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListGlobalDBServiceTips: + properties: + db_type: + description: |- + DBType 数据库类型列表 + 当请求参数 function_support 为空时,返回所有数据库类型 + 当请求参数 function_support 有效时,仅返回支持该功能的数据库类型 + items: + type: string + type: array + x-go-name: DBType + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListGlobalDBServiceV2: + properties: + backup_max_rows: + description: backup switch + format: uint64 + type: integer + x-go-name: BackupMaxRows + db_type: + description: db service DB type + type: string + x-go-name: DBType + desc: + description: DB desc + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + environment_tag: + $ref: '#/definitions/EnvironmentTag' + host: + description: db service host + type: string + x-go-name: Host + is_enable_audit: + description: is enable audit + type: boolean + x-go-name: IsEnableAudit + is_enable_masking: + description: is enable masking + type: boolean + x-go-name: IsEnableMasking + last_connection_test_error_message: + description: DB connect test error message + type: string + x-go-name: LastConnectionTestErrorMessage + last_connection_test_status: + description: |- + DB connect test status + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + enum: + - connect_success + - connect_failed + type: string + x-go-enum-desc: |- + connect_success LastConnectionTestStatusSuccess + connect_failed LastConnectionTestStatusFailed + x-go-name: LastConnectionTestStatus + last_connection_test_time: + description: DB connection test time + format: date-time + type: string + x-go-name: LastConnectionTestTime + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + name: + description: db service name + type: string + x-go-name: Name + port: + description: db service port + type: string + x-go-name: Port + project_name: + description: db service project_name + type: string + x-go-name: ProjectName + project_uid: + description: DB project uid + type: string + x-go-name: ProjectUID + source: + description: DB source + type: string + x-go-name: Source + uid: + description: db service uid + type: string + x-go-name: DBServiceUid + unfinished_workflow_num: + description: db service unfinished workflow num + format: int64 + type: integer + x-go-name: UnfinishedWorkflowNum + workflow_exec_enabled: + description: is enabled workflow exec + type: boolean + x-go-name: WorkflowExecEnabled + required: + - environment_tag + type: object + x-go-name: ListGlobalDBService + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ListGlobalDBServicesReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List global db service reply + items: + $ref: '#/definitions/ListGlobalDBService' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListGlobalDBServicesReplyV2: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List global db service reply + items: + $ref: '#/definitions/ListGlobalDBServiceV2' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-name: ListGlobalDBServicesReply + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ListGlobalDBServicesTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/ListGlobalDBServiceTips' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMaskingRulesData: + properties: + description: + description: description + example: '"mask digits"' + type: string + x-go-name: Description + effect: + description: effect description for users + example: '"保留开头2位和结尾2位,中间字符替换为*"' + type: string + x-go-name: Effect + effect_example_after: + description: effect example after masking + example: '"138******78"' + type: string + x-go-name: EffectExampleAfter + effect_example_before: + description: effect example before masking + example: '"13812345678"' + type: string + x-go-name: EffectExampleBefore + id: + description: masking rule id + example: 1 + format: int64 + type: integer + x-go-name: Id + masking_type: + description: masking type + example: '"MASK_DIGIT"' + type: string + x-go-name: MaskingType + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMaskingRulesReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: list masking rule reply + items: + $ref: '#/definitions/ListMaskingRulesData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMaskingTemplatesData: + properties: + id: + description: masking template id + example: 1 + format: int64 + type: integer + x-go-name: Id + name: + description: masking template name + example: '"Standard Template"' + type: string + x-go-name: Name + rule_count: + description: count of rules in the template + example: 5 + format: int64 + type: integer + x-go-name: RuleCount + rule_names: + description: preview of rule name in the template, up to 3 items + items: + type: string + type: array + x-go-name: RuleNames + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMaskingTemplatesReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: list masking templates reply + items: + $ref: '#/definitions/ListMaskingTemplatesData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + description: total count of masking templates + example: 100 + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMember: + description: A dms member + properties: + current_project_admin: + $ref: '#/definitions/CurrentProjectAdmin' + current_project_manage_permissions: + description: current project manage permissions + items: + $ref: '#/definitions/ProjectManagePermission' + type: array + x-go-name: CurrentProjectManagePermissions + current_project_op_permissions: + description: current project permission + items: + $ref: '#/definitions/ProjectOpPermission' + type: array + x-go-name: CurrentProjectOpPermissions + is_group_member: + description: Whether the member is a group member + type: boolean + x-go-name: IsGroupMember + is_project_admin: + description: Whether the member has project admin permission + type: boolean + x-go-name: IsProjectAdmin + platform_roles: + description: member platform roles + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: PlatformRoles + projects: + description: member projects + items: + type: string + type: array + x-go-name: Projects + role_with_op_ranges: + description: member op permission + items: + $ref: '#/definitions/ListMemberRoleWithOpRange' + type: array + x-go-name: RoleWithOpRanges + uid: + description: member uid + type: string + x-go-name: MemberUid + user: + $ref: '#/definitions/UidWithName' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMemberGroup: + properties: + current_project_manage_permissions: + description: member project manage permissions + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: CurrentProjectManagePermissions + current_project_op_permissions: + description: current project permission + items: + $ref: '#/definitions/ProjectOpPermission' + type: array + x-go-name: CurrentProjectOpPermissions + is_project_admin: + description: Whether the member has project admin permission + type: boolean + x-go-name: IsProjectAdmin + name: + type: string + x-go-name: Name + role_with_op_ranges: + description: member op permission + items: + $ref: '#/definitions/ListMemberRoleWithOpRange' + type: array + x-go-name: RoleWithOpRanges + uid: + description: member uid + type: string + x-go-name: Uid + users: + description: member user + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: Users + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMemberGroupTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List member group tip reply + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMemberGroupsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List member reply + items: + $ref: '#/definitions/ListMemberGroup' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMemberReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List member reply + items: + $ref: '#/definitions/ListMember' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMemberRoleWithOpRange: + properties: + member_group: + $ref: '#/definitions/ProjectMemberGroup' + op_permissions: + description: member op permissions + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: OpPermissions + op_range_type: + description: |- + op permission range type, only support db service now + unknown OpRangeTypeUnknown + global OpRangeTypeGlobal 全局权限: 该权限只能被用户使用 + project OpRangeTypeProject 项目权限: 该权限只能被成员使用 + db_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用 + enum: + - unknown + - global + - project + - db_service + type: string + x-go-enum-desc: |- + unknown OpRangeTypeUnknown + global OpRangeTypeGlobal 全局权限: 该权限只能被用户使用 + project OpRangeTypeProject 项目权限: 该权限只能被成员使用 + db_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用 + x-go-name: OpRangeType + range_uids: + description: op range uids + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: RangeUIDs + role_uid: + $ref: '#/definitions/UidWithName' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMemberTipsItem: + properties: + user_id: + type: string + x-go-name: UserId + user_name: + type: string + x-go-name: UserName + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMemberTipsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List member tip reply + items: + $ref: '#/definitions/ListMemberTipsItem' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListMembersForInternalItem: + description: A dms member for internal + properties: + is_admin: + description: is member project admin, admin has all permissions + type: boolean + x-go-name: IsAdmin + member_op_permission_list: + description: member op permissions + items: + $ref: '#/definitions/OpPermissionItem' + type: array + x-go-name: MemberOpPermissionList + user: + $ref: '#/definitions/UidWithName' + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ListMembersForInternalReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List member reply + items: + $ref: '#/definitions/ListMembersForInternalItem' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ListOpPermission: + description: A dms op permission + properties: + description: + type: string + x-go-name: Description + module: + type: string + x-go-name: Module + op_permission: + $ref: '#/definitions/UidWithName' + range_type: + enum: + - unknown + - global + - project + - db_service + type: string + x-go-enum-desc: |- + unknown OpRangeTypeUnknown + global OpRangeTypeGlobal 全局权限: 该权限只能被用户使用 + project OpRangeTypeProject 项目权限: 该权限只能被成员使用 + db_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用 + x-go-name: RangeType + service: + enum: + - dms + - sqle + type: string + x-go-enum-desc: |- + dms ServiceDMS + sqle ServiceSQLE + x-go-name: Service + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListOpPermissionReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List op_permission reply + items: + $ref: '#/definitions/ListOpPermission' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListPendingApprovalRequestsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: pending approval requests reply + items: + $ref: '#/definitions/PendingApprovalRequestData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + description: total count of pending approval requests + example: 100 + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListProjectReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List project reply + items: + $ref: '#/definitions/ListProjectV1' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ListProjectReplyV2: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List project reply + items: + $ref: '#/definitions/ListProjectV2' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-name: ListProjectReply + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v2 + ListProjectV1: + properties: + archived: + description: Project is archived + type: boolean + x-go-name: Archived + business: + description: Project business + items: + $ref: '#/definitions/Business' + type: array + x-go-name: Business + create_time: + description: create time + format: date-time + type: string + x-go-name: CreateTime + create_user: + $ref: '#/definitions/UidWithName' + desc: + description: Project desc + type: string + x-go-name: Desc + is_fixed_business: + description: is fixed business + type: boolean + x-go-name: IsFixedBusiness + name: + description: Project name + type: string + x-go-name: Name + project_priority: + description: |- + project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: ProjectPriority + uid: + description: Project uid + type: string + x-go-name: ProjectUid + type: object + x-go-name: ListProject + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ListProjectV2: + properties: + archived: + description: Project is archived + type: boolean + x-go-name: Archived + business_tag: + $ref: '#/definitions/BusinessTagCommon' + create_time: + description: create time + format: date-time + type: string + x-go-name: CreateTime + create_user: + $ref: '#/definitions/UidWithName' + desc: + description: Project desc + type: string + x-go-name: Desc + name: + description: Project name + type: string + x-go-name: Name + project_priority: + description: |- + project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: ProjectPriority + uid: + description: Project uid + type: string + x-go-name: ProjectUid + type: object + x-go-name: ListProject + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v2 + ListRole: + description: A dms role + properties: + desc: + description: role desc + type: string + x-go-name: Desc + name: + description: role name + type: string + x-go-name: Name + op_permissions: + description: op permissions + items: + $ref: '#/definitions/ListRoleOpPermission' + type: array + x-go-name: OpPermissions + stat: + description: |- + role stat + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + enum: + - 正常 + - 被禁用 + - 未知 + - Normal + - Disabled + - Unknown + type: string + x-go-enum-desc: |- + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + x-go-name: Stat + uid: + description: role uid + type: string + x-go-name: RoleUid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListRoleOpPermission: + properties: + module: + type: string + x-go-name: Module + name: + type: string + x-go-name: Name + uid: + type: string + x-go-name: Uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListRoleReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List role reply + items: + $ref: '#/definitions/ListRole' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListSensitiveDataDiscoveryTaskHistoriesData: + properties: + executed_at: + description: |- + execution time in RFC3339 format + Format: date-time (RFC3339) + example: '"2024-01-15T10:30:00Z"' + type: string + x-go-name: ExecutedAt + new_sensitive_field_count: + description: newly discovered sensitive field count + example: 10 + format: int64 + type: integer + x-go-name: NewSensitiveFieldCount + remark: + description: remark + example: '"scan completed successfully"' + type: string + x-go-name: Remark + status: + description: |- + execution status + PENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm + NORMAL SensitiveDataDiscoveryTaskStatusNormal + COMPLETED SensitiveDataDiscoveryTaskStatusCompleted + RUNNING SensitiveDataDiscoveryTaskStatusRunning + FAILED SensitiveDataDiscoveryTaskStatusFailed + STOPPED SensitiveDataDiscoveryTaskStatusStopped + enum: + - PENDING_CONFIRM + - NORMAL + - COMPLETED + - RUNNING + - FAILED + - STOPPED + example: '"NORMAL"' + type: string + x-go-enum-desc: |- + PENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm + NORMAL SensitiveDataDiscoveryTaskStatusNormal + COMPLETED SensitiveDataDiscoveryTaskStatusCompleted + RUNNING SensitiveDataDiscoveryTaskStatusRunning + FAILED SensitiveDataDiscoveryTaskStatusFailed + STOPPED SensitiveDataDiscoveryTaskStatusStopped + x-go-name: Status + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListSensitiveDataDiscoveryTaskHistoriesReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: sensitive data discovery task histories reply + items: + $ref: '#/definitions/ListSensitiveDataDiscoveryTaskHistoriesData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + description: total count of sensitive data discovery task histories + example: 100 + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListSensitiveDataDiscoveryTasksData: + properties: + db_service_host: + description: database instance host + example: '"10.10.10.10"' + type: string + x-go-name: DBServiceHost + db_service_name: + description: database instance name + example: '"mysql-01"' + type: string + x-go-name: DBServiceName + db_service_port: + description: database instance port + example: '"3306"' + type: string + x-go-name: DBServicePort + db_service_uid: + description: database instance id + example: '"db_service_uid_1"' + type: string + x-go-name: DBServiceUID + execution_frequency: + description: cron expression of execution frequency, periodic task returns cron, one-time task returns empty + example: '"0 2 * * *"' + type: string + x-go-name: ExecutionFrequency + execution_plan: + description: |- + execution plan + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + enum: + - PERIODIC + - ONE_TIME + example: '"ONE_TIME"' + type: string + x-go-enum-desc: |- + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + x-go-name: ExecutionPlan + id: + description: sensitive data discovery task id + example: 1 + format: int64 + type: integer + x-go-name: ID + identification_method: + description: |- + sensitive data identification method + BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName + BY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData + enum: + - BY_FIELD_NAME + - BY_SAMPLE_DATA + example: '"BY_FIELD_NAME"' + type: string + x-go-enum-desc: |- + BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName + BY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData + x-go-name: IdentificationMethod + is_periodic_scan_enabled: + description: whether periodic scanning is enabled + example: true + type: boolean + x-go-name: IsPeriodicScanEnabled + masking_template_id: + description: related masking template id + example: 1 + format: int64 + type: integer + x-go-name: MaskingTemplateID + masking_template_name: + description: related masking template name + example: '"Standard Template"' + type: string + x-go-name: MaskingTemplateName + next_execution_at: + description: |- + next run time, periodic task returns RFC3339 time, one-time task returns null + Format: date-time (RFC3339) + example: '"2024-01-15T10:30:00Z"' + type: string + x-go-name: NextExecutionAt + status: + description: |- + task status + PENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm + NORMAL SensitiveDataDiscoveryTaskStatusNormal + COMPLETED SensitiveDataDiscoveryTaskStatusCompleted + RUNNING SensitiveDataDiscoveryTaskStatusRunning + FAILED SensitiveDataDiscoveryTaskStatusFailed + STOPPED SensitiveDataDiscoveryTaskStatusStopped + enum: + - PENDING_CONFIRM + - NORMAL + - COMPLETED + - RUNNING + - FAILED + - STOPPED + example: '"NORMAL"' + type: string + x-go-enum-desc: |- + PENDING_CONFIRM SensitiveDataDiscoveryTaskStatusPendingChangeConfirm + NORMAL SensitiveDataDiscoveryTaskStatusNormal + COMPLETED SensitiveDataDiscoveryTaskStatusCompleted + RUNNING SensitiveDataDiscoveryTaskStatusRunning + FAILED SensitiveDataDiscoveryTaskStatusFailed + STOPPED SensitiveDataDiscoveryTaskStatusStopped + x-go-name: Status + task_type: + description: |- + task type + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + enum: + - PERIODIC + - ONE_TIME + example: '"PERIODIC"' + type: string + x-go-enum-desc: |- + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + x-go-name: TaskType + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListSensitiveDataDiscoveryTasksReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: sensitive data discovery tasks list reply + items: + $ref: '#/definitions/ListSensitiveDataDiscoveryTasksData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + description: total count of sensitive data discovery tasks + example: 100 + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListUser: + description: A dms user + properties: + authentication_type: + description: |- + user authentication type + ldap UserAuthenticationTypeLDAP + dms UserAuthenticationTypeDMS + oauth2 UserAuthenticationTypeOAUTH2 + unknown UserAuthenticationTypeUnknown + enum: + - ldap + - dms + - oauth2 + - unknown + type: string + x-go-enum-desc: |- + ldap UserAuthenticationTypeLDAP + dms UserAuthenticationTypeDMS + oauth2 UserAuthenticationTypeOAUTH2 + unknown UserAuthenticationTypeUnknown + x-go-name: AuthenticationType + email: + description: user email + type: string + x-go-name: Email + is_deleted: + description: user is deleted + type: boolean + x-go-name: IsDeleted + name: + description: user name + type: string + x-go-name: Name + op_permissions: + description: user operation permissions + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: OpPermissions + phone: + description: user phone + type: string + x-go-name: Phone + projects: + description: projects + items: + type: string + type: array + x-go-name: Projects + stat: + description: |- + user stat + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + enum: + - 正常 + - 被禁用 + - 未知 + - Normal + - Disabled + - Unknown + type: string + x-go-enum-desc: |- + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + x-go-name: Stat + system: + description: |- + user system + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + enum: + - WORKBENCH + - MANAGEMENT + type: string + x-go-enum-desc: |- + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + x-go-name: System + third_party_user_info: + description: third party user info + type: string + x-go-name: ThirdPartyUserInfo + uid: + description: user uid + type: string + x-go-name: UserUid + user_groups: + description: user groups + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: UserGroups + wxid: + description: user wxid + type: string + x-go-name: WxID + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ListUserGroup: + description: A dms user group + properties: + desc: + description: user group description + type: string + x-go-name: Desc + name: + description: user group name + type: string + x-go-name: Name + stat: + description: |- + user group stat + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + enum: + - 正常 + - 被禁用 + - 未知 + - Normal + - Disabled + - Unknown + type: string + x-go-enum-desc: |- + 正常 StatOK + 被禁用 StatDisable + 未知 StatUnknown + Normal StatOKEn + Disabled StatDisableEn + Unknown StatUnknownEn + x-go-name: Stat + uid: + description: user group uid + type: string + x-go-name: UserGroupUid + users: + description: users + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: Users + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListUserGroupReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List user reply + items: + $ref: '#/definitions/ListUserGroup' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ListUserReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: List user reply + items: + $ref: '#/definitions/ListUser' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + LoginConfiguration: + properties: + disable_user_pwd_login: + type: boolean + x-go-name: DisableUserPwdLogin + login_button_text: + type: string + x-go-name: LoginButtonText + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + LoginTipsResData: + properties: + disable_user_pwd_login: + type: boolean + x-go-name: DisableUserPwdLogin + login_button_text: + type: string + x-go-name: LoginButtonText + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + MIMEHeader: + additionalProperties: + items: + type: string + type: array + description: |- + A MIMEHeader represents a MIME-style header mapping + keys to sets of values. + type: object + x-go-package: net/textproto + MaintenanceTime: + properties: + maintenance_start_time: + $ref: '#/definitions/Time' + maintenance_stop_time: + $ref: '#/definitions/Time' + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + MaskingOverviewDashboard: + properties: + configured_masking_columns: + description: total count of columns with configured masking + example: 120 + format: int64 + type: integer + x-go-name: ConfiguredMaskingColumns + pending_confirm_masking_columns: + description: total count of columns pending masking confirmation + example: 5 + format: int64 + type: integer + x-go-name: PendingConfirmMaskingColumns + total_sensitive_tables: + description: total count of tables that contain sensitive data + example: 50 + format: int64 + type: integer + x-go-name: TotalSensitiveTables + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + MaskingOverviewDatabaseNode: + properties: + tables: + additionalProperties: + $ref: '#/definitions/MaskingOverviewTableData' + description: table_name -> table overview data + type: object + x-go-name: Tables + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + MaskingOverviewTableData: + properties: + configured_masking_columns: + description: configured masking column count for this table + example: 3 + format: int64 + type: integer + x-go-name: ConfiguredMaskingColumns + pending_confirm_masking_columns: + description: pending masking confirmation column count for this table + example: 1 + format: int64 + type: integer + x-go-name: PendingConfirmMaskingColumns + table_id: + description: table id + example: 1 + format: int64 + type: integer + x-go-name: TableID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + MaskingPreviewData: + properties: + columns: + description: preview columns + example: + - id + - name + - email + items: + type: string + type: array + x-go-name: Columns + rows: + description: preview rows + example: + - - "1" + - John + - j***@example.com + - - "2" + - Alice + - a***@example.com + items: + items: + type: string + type: array + type: array + x-go-name: Rows + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + MaskingRuleConfig: + properties: + column_name: + description: column name + example: '"email"' + type: string + x-go-name: ColumnName + db_service_uid: + description: data source id + example: '"1"' + type: string + x-go-name: DBServiceUID + is_masking_enabled: + description: whether to enable masking for this column + example: true + type: boolean + x-go-name: IsMaskingEnabled + masking_rule_id: + description: masking rule id + example: 1 + format: int64 + type: integer + x-go-name: MaskingRuleID + schema_name: + description: schema name + example: '"db1"' + type: string + x-go-name: SchemaName + table_name: + description: table name + example: '"users"' + type: string + x-go-name: TableName + required: + - db_service_uid + - schema_name + - table_name + - column_name + - masking_rule_id + - is_masking_enabled + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Member: + description: A member + properties: + is_project_admin: + description: Whether the member has project admin permission + type: boolean + x-go-name: IsProjectAdmin + project_manage_permissions: + description: member project manage permissions + items: + type: string + type: array + x-go-name: ProjectManagePermissions + role_with_op_ranges: + description: member role with op ranges + items: + $ref: '#/definitions/MemberRoleWithOpRange' + type: array + x-go-name: RoleWithOpRanges + user_uid: + description: member user uid + type: string + x-go-name: UserUid + required: + - user_uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + MemberGroup: + properties: + is_project_admin: + description: Whether the member has project admin permission + type: boolean + x-go-name: IsProjectAdmin + name: + description: member group name + type: string + x-go-name: Name + project_manage_permissions: + description: member project manage permissions + items: + type: string + type: array + x-go-name: ProjectManagePermissions + role_with_op_ranges: + description: member role with op ranges + items: + $ref: '#/definitions/MemberRoleWithOpRange' + type: array + x-go-name: RoleWithOpRanges + user_uids: + description: member user uid + items: + type: string + type: array + x-go-name: UserUids + required: + - name + - user_uids + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + MemberRoleWithOpRange: + properties: + op_range_type: + description: |- + op permission range type, only support db service now + unknown OpRangeTypeUnknown + global OpRangeTypeGlobal 全局权限: 该权限只能被用户使用 + project OpRangeTypeProject 项目权限: 该权限只能被成员使用 + db_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用 + enum: + - unknown + - global + - project + - db_service + type: string + x-go-enum-desc: |- + unknown OpRangeTypeUnknown + global OpRangeTypeGlobal 全局权限: 该权限只能被用户使用 + project OpRangeTypeProject 项目权限: 该权限只能被成员使用 + db_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用 + x-go-name: OpRangeType + range_uids: + description: op range uids + items: + type: string + type: array + x-go-name: RangeUIDs + role_uid: + description: role uid + type: string + x-go-name: RoleUID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Notification: + properties: + notification_body: + $ref: '#/definitions/I18nStr' + notification_subject: + $ref: '#/definitions/I18nStr' + user_uids: + items: + type: string + type: array + x-go-name: UserUids + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + NotificationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + Oauth2Configuration: + properties: + access_token_tag: + type: string + x-go-name: AccessTokenTag + auto_bind_same_name_user: + type: boolean + x-go-name: AutoBindSameNameUser + auto_create_user: + type: boolean + x-go-name: AutoCreateUser + auto_create_user_pwd: + type: string + x-go-name: AutoCreateUserPWD + client_host: + type: string + x-go-name: ClientHost + client_id: + type: string + x-go-name: ClientID + client_key: + type: string + x-go-name: ClientKey + enable_manually_bind: + type: boolean + x-go-name: EnableManuallyBind + enable_oauth2: + type: boolean + x-go-name: EnableOauth2 + login_perm_expr: + type: string + x-go-name: LoginPermExpr + login_tip: + maximum: 28 + type: string + x-go-name: LoginTip + scopes: + items: + type: string + type: array + x-go-name: Scopes + server_auth_url: + type: string + x-go-name: ServerAuthUrl + server_logout_url: + type: string + x-go-name: ServerLogoutUrl + server_token_url: + type: string + x-go-name: ServerTokenUrl + server_user_id_url: + type: string + x-go-name: ServerUserIdUrl + skip_check_state: + type: boolean + x-go-name: SkipCheckState + user_email_tag: + type: string + x-go-name: UserEmailTag + user_id_tag: + type: string + x-go-name: UserIdTag + user_wechat_tag: + type: string + x-go-name: UserWeChatTag + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Oauth2ConfigurationReq: + properties: + oauth2: + $ref: '#/definitions/Oauth2Configuration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + OpPermissionItem: + properties: + op_permission_type: + description: |- + op permission type + unknown OpPermissionTypeUnknown + create_project OpPermissionTypeCreateProject 创建项目;创建项目的用户自动拥有该项目管理权限 + global_view OpPermissionTypeGlobalView 项目管理;拥有该权限的用户可以管理项目下的所有资源 + global_management OpPermissionTypeGlobalManagement 全局浏览;拥有该权限的用户可以浏览全局的资源 + project_admin OpPermissionTypeProjectAdmin 全局管理;拥有该权限的用户可以浏览和管理全局的资源 + create_workflow OpPermissionTypeCreateWorkflow 创建/编辑工单;拥有该权限的用户可以创建/编辑工单 + audit_workflow OpPermissionTypeAuditWorkflow 审核/驳回工单;拥有该权限的用户可以审核/驳回工单 + auth_db_service_data OpPermissionTypeAuthDBServiceData 账号管理;拥有该权限的用户可以授权数据源数据权限 + view_others_workflow OpPermissionTypeViewOthersWorkflow 查看其他工单权限 + execute_workflow OpPermissionTypeExecuteWorkflow 上线工单;拥有该权限的用户可以上线工单 + view_other_audit_plan OpPermissionTypeViewOtherAuditPlan 查看其他扫描任务权限 + view_sql_insight OpPermissionTypeViewSQLInsight 查看SQL洞察权限 + save_audit_plan OpPermissionTypeSaveAuditPlan 创建扫描任务权限;拥有该权限的用户可以创建/更新扫描任务 + sql_query OpPermissionTypeSQLQuery SQL查询;SQL查询权限 + create_export_task OpPermissionTypeExportCreate 创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单 + audit_export_workflow OpPermissionTypeAuditExportWorkflow 审核/驳回数据导出工单;拥有该权限的用户可以审核/驳回数据导出工单 + create_optimization OpPermissionTypeCreateOptimization 创建智能调优;拥有该权限的用户可以创建智能调优 + view_others_optimization OpPermissionTypeViewOthersOptimization 查看他人创建的智能调优 + create_pipeline OpPermissionTypeCreatePipeline 配置流水线 + view_operation_record OpPermissionViewOperationRecord SQL工作台;查看所有操作记录 + view_export_task OpPermissionViewExportTask 数据导出;查看所有导出任务 + view_quick_audit_record OpPermissionViewQuickAuditRecord 快捷审核;查看所有快捷审核记录 + view_ide_audit_record OpPermissionViewIDEAuditRecord IDE审核;查看所有IDE审核记录 + view_optimization_record OpPermissionViewOptimizationRecord SQL优化;查看所有优化记录 + view_version_manage OpPermissionViewVersionManage 版本管理;查看他人创建的版本记录 + version_manage OpPermissionVersionManage 版本管理;配置版本 + view_pipeline OpPermissionViewPipeline CI/CD集成;查看所有流水线 + manage_project_data_source OpPermissionManageProjectDataSource 数据源管理;管理项目数据源管理 + manage_audit_rule_template OpPermissionManageAuditRuleTemplate 审核规则模版;管理审核规则模版 + manage_approval_template OpPermissionManageApprovalTemplate 审批流程模版;管理审批流程模版 + manage_member OpPermissionManageMember 成员与权限;管理成员与权限 + manage_push_rule OpPermissionPushRule 推送规则;管理推送规则 + manage_audit_sql_white_list OpPermissionMangeAuditSQLWhiteList 审核SQL例外;管理审核SQL例外 + manage_sql_mange_white_list OpPermissionManageSQLMangeWhiteList 管控SQL例外;管理管控SQL例外 + manage_role_mange OpPermissionManageRoleMange 角色管理;角色管理权限 + desensitization OpPermissionDesensitization 脱敏规则;脱敏规则配置权限 + masking_audit OpPermissionMaskingAudit 脱敏审核;拥有该权限的用户可以查看和处理脱敏审批请求 + none OpPermissionTypeNone 无任何权限 + enum: + - unknown + - create_project + - global_view + - global_management + - project_admin + - create_workflow + - audit_workflow + - auth_db_service_data + - view_others_workflow + - execute_workflow + - view_other_audit_plan + - view_sql_insight + - save_audit_plan + - sql_query + - create_export_task + - audit_export_workflow + - create_optimization + - view_others_optimization + - create_pipeline + - view_operation_record + - view_export_task + - view_quick_audit_record + - view_ide_audit_record + - view_optimization_record + - view_version_manage + - version_manage + - view_pipeline + - manage_project_data_source + - manage_audit_rule_template + - manage_approval_template + - manage_member + - manage_push_rule + - manage_audit_sql_white_list + - manage_sql_mange_white_list + - manage_role_mange + - desensitization + - masking_audit + - none + type: string + x-go-enum-desc: |- + unknown OpPermissionTypeUnknown + create_project OpPermissionTypeCreateProject 创建项目;创建项目的用户自动拥有该项目管理权限 + global_view OpPermissionTypeGlobalView 项目管理;拥有该权限的用户可以管理项目下的所有资源 + global_management OpPermissionTypeGlobalManagement 全局浏览;拥有该权限的用户可以浏览全局的资源 + project_admin OpPermissionTypeProjectAdmin 全局管理;拥有该权限的用户可以浏览和管理全局的资源 + create_workflow OpPermissionTypeCreateWorkflow 创建/编辑工单;拥有该权限的用户可以创建/编辑工单 + audit_workflow OpPermissionTypeAuditWorkflow 审核/驳回工单;拥有该权限的用户可以审核/驳回工单 + auth_db_service_data OpPermissionTypeAuthDBServiceData 账号管理;拥有该权限的用户可以授权数据源数据权限 + view_others_workflow OpPermissionTypeViewOthersWorkflow 查看其他工单权限 + execute_workflow OpPermissionTypeExecuteWorkflow 上线工单;拥有该权限的用户可以上线工单 + view_other_audit_plan OpPermissionTypeViewOtherAuditPlan 查看其他扫描任务权限 + view_sql_insight OpPermissionTypeViewSQLInsight 查看SQL洞察权限 + save_audit_plan OpPermissionTypeSaveAuditPlan 创建扫描任务权限;拥有该权限的用户可以创建/更新扫描任务 + sql_query OpPermissionTypeSQLQuery SQL查询;SQL查询权限 + create_export_task OpPermissionTypeExportCreate 创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单 + audit_export_workflow OpPermissionTypeAuditExportWorkflow 审核/驳回数据导出工单;拥有该权限的用户可以审核/驳回数据导出工单 + create_optimization OpPermissionTypeCreateOptimization 创建智能调优;拥有该权限的用户可以创建智能调优 + view_others_optimization OpPermissionTypeViewOthersOptimization 查看他人创建的智能调优 + create_pipeline OpPermissionTypeCreatePipeline 配置流水线 + view_operation_record OpPermissionViewOperationRecord SQL工作台;查看所有操作记录 + view_export_task OpPermissionViewExportTask 数据导出;查看所有导出任务 + view_quick_audit_record OpPermissionViewQuickAuditRecord 快捷审核;查看所有快捷审核记录 + view_ide_audit_record OpPermissionViewIDEAuditRecord IDE审核;查看所有IDE审核记录 + view_optimization_record OpPermissionViewOptimizationRecord SQL优化;查看所有优化记录 + view_version_manage OpPermissionViewVersionManage 版本管理;查看他人创建的版本记录 + version_manage OpPermissionVersionManage 版本管理;配置版本 + view_pipeline OpPermissionViewPipeline CI/CD集成;查看所有流水线 + manage_project_data_source OpPermissionManageProjectDataSource 数据源管理;管理项目数据源管理 + manage_audit_rule_template OpPermissionManageAuditRuleTemplate 审核规则模版;管理审核规则模版 + manage_approval_template OpPermissionManageApprovalTemplate 审批流程模版;管理审批流程模版 + manage_member OpPermissionManageMember 成员与权限;管理成员与权限 + manage_push_rule OpPermissionPushRule 推送规则;管理推送规则 + manage_audit_sql_white_list OpPermissionMangeAuditSQLWhiteList 审核SQL例外;管理审核SQL例外 + manage_sql_mange_white_list OpPermissionManageSQLMangeWhiteList 管控SQL例外;管理管控SQL例外 + manage_role_mange OpPermissionManageRoleMange 角色管理;角色管理权限 + desensitization OpPermissionDesensitization 脱敏规则;脱敏规则配置权限 + masking_audit OpPermissionMaskingAudit 脱敏审核;拥有该权限的用户可以查看和处理脱敏审批请求 + none OpPermissionTypeNone 无任何权限 + x-go-name: OpPermissionType + range_type: + description: |- + object type of RangeUids + unknown OpRangeTypeUnknown + global OpRangeTypeGlobal 全局权限: 该权限只能被用户使用 + project OpRangeTypeProject 项目权限: 该权限只能被成员使用 + db_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用 + enum: + - unknown + - global + - project + - db_service + type: string + x-go-enum-desc: |- + unknown OpRangeTypeUnknown + global OpRangeTypeGlobal 全局权限: 该权限只能被用户使用 + project OpRangeTypeProject 项目权限: 该权限只能被成员使用 + db_service OpRangeTypeDBService 项目内的数据源权限: 该权限只能被成员使用 + x-go-name: RangeType + range_uids: + description: object uids, object type is defined by RangeType + items: + type: string + type: array + x-go-name: RangeUids + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + OperateDataResourceHandleReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + Operation: + properties: + operation_detail: + type: string + x-go-name: OperationDetail + operation_type: + enum: + - SQL + type: string + x-go-enum-desc: SQL CbOperationTypeSQL + x-go-name: OperationType + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + OperationRecord: + properties: + operation_action: + type: string + x-go-name: OperationAction + operation_i18n_content: + $ref: '#/definitions/I18nStr' + operation_project_name: + type: string + x-go-name: OperationProjectName + operation_req_ip: + type: string + x-go-name: OperationReqIP + operation_status: + type: string + x-go-name: OperationStatus + operation_time: + format: date-time + type: string + x-go-name: OperationTime + operation_type_name: + type: string + x-go-name: OperationTypeName + operation_user_agent: + type: string + x-go-name: OperationUserAgent + operation_user_name: + type: string + x-go-name: OperationUserName + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + OperationRecordListItem: + properties: + id: + format: uint64 + type: integer + x-go-name: ID + operation_action: + type: string + x-go-name: OperationAction + operation_content: + type: string + x-go-name: OperationContent + operation_time: + format: date-time + type: string + x-go-name: OperationTime + operation_type_name: + type: string + x-go-name: OperationTypeName + operation_user: + $ref: '#/definitions/OperationUser' + operation_user_agent: + type: string + x-go-name: OperationUserAgent + project_name: + type: string + x-go-name: ProjectName + status: + enum: + - succeeded + - failed + type: string + x-go-name: Status + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + OperationUser: + properties: + ip: + type: string + x-go-name: IP + user_name: + type: string + x-go-name: UserName + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Param: + properties: + desc: + type: string + x-go-name: Desc + key: + type: string + x-go-name: Key + type: + $ref: '#/definitions/ParamType' + value: + type: string + x-go-name: Value + type: object + x-go-package: github.com/actiontech/dms/pkg/params + ParamType: + type: string + x-go-package: github.com/actiontech/dms/pkg/params + Params: + items: + $ref: '#/definitions/Param' + type: array + x-go-package: github.com/actiontech/dms/pkg/params + PendingApprovalRequestData: + properties: + applicant_name: + description: applicant name + example: '"admin"' + type: string + x-go-name: ApplicantName + applied_at: + description: |- + application time in RFC3339 format + Format: date-time (RFC3339) + example: '"2024-01-15T10:30:00Z"' + type: string + x-go-name: AppliedAt + data_scope: + description: data scope + example: '"database ''db1'', table ''users''"' + type: string + x-go-name: DataScope + id: + description: approval request id + example: 1 + format: int64 + type: integer + x-go-name: ID + reason: + description: application reason + example: '"data analysis"' + type: string + x-go-name: Reason + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + PersonalizationReq: + properties: + file: + $ref: '#/definitions/FileHeader' + title: + type: string + x-go-name: Title + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Plugin: + properties: + get_database_driver_logos_url: + type: string + x-go-name: GetDatabaseDriverLogosUrl + get_database_driver_options_url: + type: string + x-go-name: GetDatabaseDriverOptionsUrl + name: + description: 插件名称 + type: string + x-go-name: Name + operate_data_resource_handle_url: + description: |- + 操作资源处理接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/data_resource_operate/handle + 该地址目的是统一调用其他服务 数据资源变更前后校验/更新数据的 接口 + eg: 删除数据源前: + 需要sqle服务中实现接口逻辑,判断该数据源上已经没有进行中的工单 + type: string + x-go-name: OperateDataResourceHandleUrl + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + PreviewImportProjects: + properties: + business: + description: business + items: + type: string + type: array + x-go-name: Business + desc: + description: Project desc + type: string + x-go-name: Desc + name: + description: Project name + type: string + x-go-name: Name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + PreviewImportProjectsReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: list preview import projects + items: + $ref: '#/definitions/PreviewImportProjects' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + PreviewImportProjectsReplyV2: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: list preview import projects + items: + $ref: '#/definitions/PreviewImportProjectsV2' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-name: PreviewImportProjectsReply + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + PreviewImportProjectsV2: + properties: + business_tag: + $ref: '#/definitions/BusinessTag' + desc: + description: Project desc + type: string + x-go-name: Desc + name: + description: Project name + type: string + x-go-name: Name + type: object + x-go-name: PreviewImportProjects + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + ProcessApprovalRequestReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProcessApprovalRequestReq: + properties: + action: + description: |- + process action + APPROVE ApprovalActionApprove + REJECT ApprovalActionReject + enum: + - APPROVE + - REJECT + example: '"APPROVE"' + type: string + x-go-enum-desc: |- + APPROVE ApprovalActionApprove + REJECT ApprovalActionReject + x-go-name: Action + approve_remark: + description: approval remark, optional when action is APPROVE + example: '"approved for one-time access"' + type: string + x-go-name: ApproveRemark + reject_reason: + description: reject reason, required when action is REJECT + example: '"insufficient reason"' + type: string + x-go-name: RejectReason + required: + - action + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProjectInfo: + properties: + project_name: + type: string + x-go-name: ProjectName + project_priority: + enum: + - high + - medium + - low + - unknown + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: ProjectPriority + project_uid: + type: string + x-go-name: ProjectUid + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + ProjectManagePermission: + properties: + member_group: + type: string + x-go-name: MemberGroup + name: + type: string + x-go-name: Name + uid: + type: string + x-go-name: Uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProjectMemberGroup: + properties: + name: + type: string + x-go-name: Name + op_permissions: + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: OpPermissions + uid: + type: string + x-go-name: Uid + users: + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: Users + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProjectOpPermission: + properties: + data_source: + type: string + x-go-name: DataSource + roles: + items: + $ref: '#/definitions/ProjectRole' + type: array + x-go-name: Roles + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProjectRole: + properties: + member_group: + $ref: '#/definitions/ProjectMemberGroup' + name: + type: string + x-go-name: Name + op_permissions: + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: OpPermissions + uid: + type: string + x-go-name: Uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProjectTips: + properties: + business: + items: + type: string + type: array + x-go-name: Business + is_fixed_business: + type: boolean + x-go-name: IsFixedBusiness + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProjectV1: + properties: + business: + description: project business + items: + type: string + type: array + x-go-name: Business + desc: + description: project desc + type: string + x-go-name: Desc + is_fixed_business: + description: is fixed business + type: boolean + x-go-name: IsFixedBusiness + name: + description: project name + type: string + x-go-name: Name + project_priority: + description: |- + project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: ProjectPriority + type: object + x-go-name: Project + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ProjectV2: + properties: + business_tag: + $ref: '#/definitions/BusinessTag' + desc: + description: project desc + type: string + x-go-name: Desc + name: + description: project name + type: string + x-go-name: Name + project_priority: + description: |- + project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: ProjectPriority + type: object + x-go-name: Project + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + RegisterDMSPluginReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + RegisterDMSPluginReq: + properties: + plugin: + $ref: '#/definitions/Plugin' + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + RegisterDMSProxyTargetReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + RegisterDMSProxyTargetReq: + properties: + dms_proxy_target: + $ref: '#/definitions/DMSProxyTarget' + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + RejectDataExportWorkflowPayload: + properties: + reason: + type: string + x-go-name: Reason + required: + - reason + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + RejectDataExportWorkflowReq: + properties: + payload: + $ref: '#/definitions/RejectDataExportWorkflowPayload' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceBusiness: + properties: + business_tag: + $ref: '#/definitions/BusinessTag' + project: + items: + $ref: '#/definitions/ResourceProject' + type: array + x-go-name: Project + type: object + x-go-name: Business + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceDBService: + properties: + db_service_name: + type: string + x-go-name: DBServiceName + db_service_uid: + type: string + x-go-name: DBServiceUID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceListData: + properties: + audit_score: + description: 审核评分 + format: float + type: number + x-go-name: AuditScore + business_tag: + $ref: '#/definitions/BusinessTag' + environment_tag: + $ref: '#/definitions/EnvironmentTag' + high_priority_sql_count: + description: 高优先级SQL数 + format: int32 + type: integer + x-go-name: HighPrioritySQLCount + pending_workflow_count: + description: 待处理工单数 + format: int32 + type: integer + x-go-name: PendingWorkflowCount + project: + $ref: '#/definitions/ResourceProject' + resource_name: + description: 资源名称 + type: string + x-go-name: ResourceName + resource_type: + description: 资源类型 + type: string + x-go-name: ResourceType + resource_uid: + description: 资源UID + type: string + x-go-name: ResourceUID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceOverviewResourceListResV1: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/ResourceListData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-name: ResourceOverviewResourceListRes + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceOverviewResourceTypeDistributionResV1: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + items: + $ref: '#/definitions/ResourceTypeDistributionData' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-name: ResourceOverviewResourceTypeDistributionRes + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceOverviewStatisticsResV1: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + properties: + business_total_number: + description: 业务总数 + format: int64 + type: integer + x-go-name: BusinessTotalNumber + db_service_total_number: + description: 数据源总数 + format: int64 + type: integer + x-go-name: DBServiceTotalNumber + project_total_number: + description: 项目总数 + format: int64 + type: integer + x-go-name: ProjectTotalNumber + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-name: ResourceOverviewStatisticsRes + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceOverviewTopologyResV1: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: business:project = 1:n project:db_service = 1:n + items: + $ref: '#/definitions/ResourceBusiness' + type: array + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + total_nums: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-name: ResourceOverviewTopologyRes + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceProject: + properties: + db_service: + items: + $ref: '#/definitions/ResourceDBService' + type: array + x-go-name: DBService + project_name: + type: string + x-go-name: ProjectName + project_uid: + type: string + x-go-name: ProjectUID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + ResourceTypeDistributionData: + properties: + count: + description: 数量 + format: int64 + type: integer + x-go-name: Count + resource_type: + description: 资源类型 + type: string + x-go-name: ResourceType + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Role: + description: A role + properties: + desc: + description: role description + type: string + x-go-name: Desc + name: + description: role name + type: string + x-go-name: Name + op_permission_uids: + description: op permission uid + items: + type: string + type: array + x-go-name: OpPermissionUids + required: + - name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SMTPConfigurationResData: + properties: + enable_smtp_notify: + type: boolean + x-go-name: EnableSMTPNotify + is_skip_verify: + type: boolean + x-go-name: IsSkipVerify + smtp_host: + type: string + x-go-name: Host + smtp_port: + type: string + x-go-name: Port + smtp_username: + type: string + x-go-name: Username + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SQLEConfig: + properties: + audit_enabled: + description: DB Service audit enabled + type: boolean + x-go-name: AuditEnabled + data_export_rule_template_id: + description: DB Service data export rule template id + type: string + x-go-name: DataExportRuleTemplateID + data_export_rule_template_name: + description: DB Service data export rule template name + type: string + x-go-name: DataExportRuleTemplateName + rule_template_id: + description: DB Service rule template id + type: string + x-go-name: RuleTemplateID + rule_template_name: + description: DB Service rule template name + type: string + x-go-name: RuleTemplateName + sql_query_config: + $ref: '#/definitions/SQLQueryConfig' + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + SQLQueryConfig: + properties: + allow_query_when_less_than_audit_level: + enum: + - normal + - notice + - warn + - error + type: string + x-go-enum-desc: |- + normal AuditLevelNormal + notice AuditLevelNotice + warn AuditLevelWarn + error AuditLevelError + x-go-name: AllowQueryWhenLessThanAuditLevel + audit_enabled: + type: boolean + x-go-name: AuditEnabled + maintenance_times: + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + max_pre_query_rows: + format: int64 + type: integer + x-go-name: MaxPreQueryRows + query_timeout_second: + format: int64 + type: integer + x-go-name: QueryTimeoutSecond + rule_template_id: + type: string + x-go-name: RuleTemplateID + rule_template_name: + type: string + x-go-name: RuleTemplateName + workflow_exec_enabled: + type: boolean + x-go-name: WorkflowExecEnabled + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + SendSmsCodeReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/SendSmsCodeReplyData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SendSmsCodeReplyData: + properties: + is_sms_code_sent_normally: + type: boolean + x-go-name: IsSmsCodeSentNormally + send_error_message: + type: string + x-go-name: SendErrorMessage + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SendSmsCodeReq: + properties: + username: + type: string + x-go-name: Username + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SensitiveFieldScanResult: + properties: + confidence: + description: |- + confidence level + HIGH ConfidenceHigh + MEDIUM ConfidenceMedium + LOW ConfidenceLow + enum: + - HIGH + - MEDIUM + - LOW + example: '"High"' + type: string + x-go-enum-desc: |- + HIGH ConfidenceHigh + MEDIUM ConfidenceMedium + LOW ConfidenceLow + x-go-name: Confidence + recommended_masking_rule_id: + description: recommended masking rule id + example: 1 + format: int64 + type: integer + x-go-name: RecommendedMaskingRuleID + recommended_masking_rule_name: + description: recommended masking rule name + example: '"Email Masking"' + type: string + x-go-name: RecommendedMaskingRuleName + scan_info: + description: scan information for the field + example: '"matched by field name ''email''"' + type: string + x-go-name: ScanInfo + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SuspectedSensitiveDatabaseNode: + properties: + tables: + additionalProperties: + $ref: '#/definitions/SuspectedSensitiveTableNode' + description: table_name -> table node + type: object + x-go-name: Tables + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SuspectedSensitiveFieldsTree: + properties: + databases: + additionalProperties: + $ref: '#/definitions/SuspectedSensitiveDatabaseNode' + description: database_name -> database node + type: object + x-go-name: Databases + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SuspectedSensitiveTableNode: + properties: + fields: + additionalProperties: + $ref: '#/definitions/SensitiveFieldScanResult' + description: field_name -> scan result + type: object + x-go-name: Fields + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SyncGatewayReq: + properties: + gateways: + items: + $ref: '#/definitions/Gateway' + type: array + x-go-name: Gateways + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + SystemVariablesResV1: + properties: + cb_operation_logs_expired_hours: + format: int64 + type: integer + x-go-name: CbOperationLogsExpiredHours + operation_record_expired_hours: + format: int64 + type: integer + x-go-name: OperationRecordExpiredHours + system_variable_sql_manage_raw_expired_hours: + format: int64 + type: integer + x-go-name: SystemVariableSqlManageRawExpiredHours + system_variable_ssh_primary_key: + type: string + x-go-name: SystemVariableSSHPrimaryKey + system_variable_workflow_expired_hours: + format: int64 + type: integer + x-go-name: SystemVariableWorkflowExpiredHours + url: + type: string + x-go-name: Url + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + TableColumnMaskingDetail: + properties: + column_name: + description: column name + example: '"email"' + type: string + x-go-name: ColumnName + confidence: + description: |- + confidence level of masking recommendation,null if no masking rule is applied + HIGH ConfidenceHigh + MEDIUM ConfidenceMedium + LOW ConfidenceLow + enum: + - HIGH + - MEDIUM + - LOW + example: "2" + type: string + x-go-enum-desc: |- + HIGH ConfidenceHigh + MEDIUM ConfidenceMedium + LOW ConfidenceLow + x-go-name: Confidence + masking_rule_id: + description: current masking rule id, null if no masking rule is applied + example: 1 + format: int64 + type: integer + x-go-name: MaskingRuleID + masking_rule_name: + description: current masking rule name, null if no masking rule is applied + example: '"Email Masking"' + type: string + x-go-name: MaskingRuleName + status: + description: |- + current masking config status + CONFIGURED MaskingConfigStatusConfigured + PENDING_CONFIRM MaskingConfigStatusPendingConfirm + SYSTEM_CONFIRMED MaskingConfigStatusSystemConfirmed + enum: + - CONFIGURED + - PENDING_CONFIRM + - SYSTEM_CONFIRMED + type: string + x-go-enum-desc: |- + CONFIGURED MaskingConfigStatusConfigured + PENDING_CONFIRM MaskingConfigStatusPendingConfirm + SYSTEM_CONFIRMED MaskingConfigStatusSystemConfirmed + x-go-name: Status + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Task: + properties: + task_uid: + type: string + x-go-name: Uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TaskDBInfo: + properties: + database_name: + type: string + x-go-name: DatabaseName + db_type: + type: string + x-go-name: DBType + name: + type: string + x-go-name: Name + uid: + type: string + x-go-name: Uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestFeishuConfiguration: + properties: + account: + type: string + x-go-name: Account + account_type: + enum: + - email + - phone + type: string + x-go-enum-desc: |- + email FeishuAccountTypeEmail + phone FeishuAccountTypePhone + x-go-name: AccountType + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestFeishuConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/TestFeishuConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestFeishuConfigurationReq: + properties: + test_feishu_configuration: + $ref: '#/definitions/TestFeishuConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestFeishuConfigurationResData: + properties: + error_message: + type: string + x-go-name: ErrorMessage + is_message_sent_normally: + type: boolean + x-go-name: IsMessageSentNormally + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSMTPConfiguration: + properties: + recipient_addr: + type: string + x-go-name: RecipientAddr + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSMTPConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/TestSMTPConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSMTPConfigurationReq: + properties: + test_smtp_configuration: + $ref: '#/definitions/TestSMTPConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSMTPConfigurationResData: + properties: + is_smtp_send_normal: + type: boolean + x-go-name: IsSMTPSendNormal + send_error_message: + type: string + x-go-name: SendErrorMessage + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSmsConfiguration: + properties: + recipient_phone: + type: string + x-go-name: RecipientPhone + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSmsConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/TestSmsConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSmsConfigurationReq: + properties: + test_sms_configuration: + $ref: '#/definitions/TestSmsConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestSmsConfigurationResData: + properties: + is_smtp_send_normal: + type: boolean + x-go-name: IsSmsSendNormal + send_error_message: + type: string + x-go-name: SendErrorMessage + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestWeChatConfiguration: + properties: + recipient_id: + type: string + x-go-name: RecipientID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestWeChatConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/TestWeChatConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestWeChatConfigurationReq: + properties: + test_wechat_configuration: + $ref: '#/definitions/TestWeChatConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestWeChatConfigurationResData: + properties: + is_wechat_send_normal: + type: boolean + x-go-name: IsWeChatSendNormal + send_error_message: + type: string + x-go-name: SendErrorMessage + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestWebHookConfigurationReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/TestWebHookConfigurationResData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + TestWebHookConfigurationResData: + properties: + is_message_sent_normally: + type: boolean + x-go-name: IsMessageSentNormally + send_error_message: + type: string + x-go-name: SendErrorMessage + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + Time: + properties: + hour: + format: int64 + type: integer + x-go-name: Hour + minute: + format: int64 + type: integer + x-go-name: Minute + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + TriggerEventType: + type: string + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + UidWithDBServiceName: + properties: + name: + type: string + x-go-name: Name + uid: + type: string + x-go-name: Uid + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UidWithName: + properties: + name: + type: string + x-go-name: Name + uid: + type: string + x-go-name: Uid + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + UpdateBusinessTagReq: + properties: + business_tag: + $ref: '#/definitions/BusinessTag' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateCompanyNotice: + description: A companynotice + properties: + end_time: + description: notice show end time + format: date-time + type: string + x-go-name: EndTime + notice_str: + description: companynotice info + type: string + x-go-name: NoticeStr + start_time: + description: notice show start time + format: date-time + type: string + x-go-name: StartTime + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateCompanyNoticeReq: + properties: + company_notice: + $ref: '#/definitions/UpdateCompanyNotice' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateCurrentUser: + properties: + email: + description: User email + type: string + x-go-name: Email + language: + description: User language + type: string + x-go-name: Language + old_password: + description: User old password + type: string + x-go-name: OldPassword + password: + description: User new password + type: string + x-go-name: Password + phone: + description: User phone + type: string + x-go-name: Phone + system: + description: |- + User system + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + enum: + - WORKBENCH + - MANAGEMENT + type: string + x-go-enum-desc: |- + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + x-go-name: System + two_factor_enabled: + description: User two factor enabled + type: boolean + x-go-name: TwoFactorEnabled + wxid: + description: User wxid + type: string + x-go-name: WxID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateCurrentUserReq: + properties: + current_user: + $ref: '#/definitions/UpdateCurrentUser' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateDBService: + description: update db service + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + backup_max_rows: + description: backup switch + format: uint64 + type: integer + x-go-name: BackupMaxRows + business: + description: DB Service business name + type: string + x-go-name: Business + db_type: + description: Service DB type + type: string + x-go-name: DBType + desc: + description: Service description + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + host: + description: DB Service Host + type: string + x-go-name: Host + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + password: + description: DB Service admin password + type: string + x-go-name: Password + port: + description: DB Service port + type: string + x-go-name: Port + sqle_config: + $ref: '#/definitions/SQLEConfig' + user: + description: DB Service admin user + type: string + x-go-name: User + required: + - db_type + - host + - port + - user + - business + - maintenance_times + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateDBServiceReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + description: update db service reply + properties: + uid: + description: db service UID + type: string + x-go-name: Uid + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateDBServiceReq: + properties: + db_service: + $ref: '#/definitions/UpdateDBService' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateDBServiceReqV2: + properties: + db_service: + $ref: '#/definitions/UpdateDBServiceV2' + type: object + x-go-name: UpdateDBServiceReq + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + UpdateDBServiceSyncTaskReq: + properties: + db_service_sync_task: + $ref: '#/definitions/DBServiceSyncTask' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateDBServiceV2: + properties: + additional_params: + description: DB Service Custom connection parameters + items: + $ref: '#/definitions/AdditionalParam' + type: array + x-go-name: AdditionalParams + backup_max_rows: + description: backup switch + format: uint64 + type: integer + x-go-name: BackupMaxRows + db_type: + description: Service DB type + type: string + x-go-name: DBType + desc: + description: Service description + type: string + x-go-name: Desc + enable_backup: + description: backup switch + type: boolean + x-go-name: EnableBackup + environment_tag_uid: + description: DB Service environment tag + type: string + x-go-name: EnvironmentTagUID + host: + description: DB Service Host + type: string + x-go-name: Host + maintenance_times: + description: DB Service maintenance time + items: + $ref: '#/definitions/MaintenanceTime' + type: array + x-go-name: MaintenanceTimes + password: + description: DB Service admin password + type: string + x-go-name: Password + port: + description: DB Service port + type: string + x-go-name: Port + sqle_config: + $ref: '#/definitions/SQLEConfig' + user: + description: DB Service admin user + type: string + x-go-name: User + required: + - db_type + - host + - port + - user + - environment_tag_uid + - maintenance_times + type: object + x-go-name: UpdateDBService + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + UpdateEnvironmentTagReq: + properties: + environment_name: + type: string + x-go-name: Name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateFeishuConfiguration: + properties: + app_id: + type: string + x-go-name: AppID + app_secret: + type: string + x-go-name: AppSecret + is_feishu_notification_enabled: + type: boolean + x-go-name: IsFeishuNotificationEnabled + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateFeishuConfigurationReq: + properties: + update_feishu_configuration: + $ref: '#/definitions/UpdateFeishuConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateGateway: + properties: + gateway_address: + type: string + x-go-name: GatewayAddress + gateway_desc: + type: string + x-go-name: GatewayDesc + gateway_name: + type: string + x-go-name: GatewayName + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateGatewayReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateGatewayReq: + properties: + update_gateway: + $ref: '#/definitions/UpdateGateway' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateLDAPConfigurationReq: + properties: + ldap: + $ref: '#/definitions/LDAPConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateLoginConfigurationReq: + properties: + login: + $ref: '#/definitions/LoginConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateMaskingTemplate: + properties: + rule_ids: + description: masking rule id list + example: + - 1 + - 2 + items: + format: int64 + type: integer + minLength: 1 + type: array + x-go-name: RuleIDs + required: + - rule_ids + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateMaskingTemplateReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateMaskingTemplateReq: + properties: + masking_template: + $ref: '#/definitions/UpdateMaskingTemplate' + required: + - masking_template + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateMember: + properties: + is_project_admin: + description: Whether the member has project admin permission + type: boolean + x-go-name: IsProjectAdmin + project_manage_permissions: + description: member project manage permissions + items: + type: string + type: array + x-go-name: ProjectManagePermissions + role_with_op_ranges: + description: member role with op ranges + items: + $ref: '#/definitions/MemberRoleWithOpRange' + type: array + x-go-name: RoleWithOpRanges + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateMemberGroup: + properties: + is_project_admin: + description: Whether the member has project admin permission + type: boolean + x-go-name: IsProjectAdmin + project_manage_permissions: + description: member project manage permissions + items: + type: string + type: array + x-go-name: ProjectManagePermissions + role_with_op_ranges: + description: member role with op ranges + items: + $ref: '#/definitions/MemberRoleWithOpRange' + type: array + x-go-name: RoleWithOpRanges + user_uids: + description: member user uid + items: + type: string + type: array + x-go-name: UserUids + required: + - user_uids + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateMemberGroupReq: + properties: + member_group: + $ref: '#/definitions/UpdateMemberGroup' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateMemberReq: + properties: + member: + $ref: '#/definitions/UpdateMember' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateProject: + properties: + business: + description: Project business + items: + $ref: '#/definitions/BusinessForUpdate' + type: array + x-go-name: Business + desc: + description: Project desc + type: string + x-go-name: Desc + is_fixed_business: + description: is fixed business + type: boolean + x-go-name: IsFixedBusiness + project_priority: + description: |- + project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: ProjectPriority + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateProjectReq: + properties: + project: + $ref: '#/definitions/UpdateProject' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateProjectReqV2: + properties: + project: + $ref: '#/definitions/UpdateProjectV2' + type: object + x-go-name: UpdateProjectReq + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + UpdateProjectV2: + properties: + business_tag: + $ref: '#/definitions/BusinessTag' + desc: + description: Project desc + type: string + x-go-name: Desc + project_priority: + description: |- + project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: ProjectPriority + type: object + x-go-name: UpdateProject + x-go-package: github.com/actiontech/dms/api/dms/service/v2 + UpdateRole: + properties: + desc: + description: Role desc + type: string + x-go-name: Desc + is_disabled: + description: Whether the role is disabled or not + type: boolean + x-go-name: IsDisabled + op_permission_uids: + description: Op permission uids + items: + type: string + type: array + x-go-name: OpPermissionUids + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateRoleReq: + properties: + role: + $ref: '#/definitions/UpdateRole' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSMTPConfiguration: + properties: + enable_smtp_notify: + type: boolean + x-go-name: EnableSMTPNotify + is_skip_verify: + type: boolean + x-go-name: IsSkipVerify + smtp_host: + type: string + x-go-name: Host + smtp_password: + type: string + x-go-name: Password + smtp_port: + type: string + x-go-name: Port + smtp_username: + type: string + x-go-name: Username + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSMTPConfigurationReq: + properties: + smtp_configuration: + $ref: '#/definitions/UpdateSMTPConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSensitiveDataDiscoveryTask: + properties: + cron_expression: + description: cron expression, only used when execution_plan is PERIODIC + example: '"0 0 * * *"' + type: string + x-go-name: CronExpression + execution_plan: + description: |- + execution plan + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + enum: + - PERIODIC + - ONE_TIME + example: '"PERIODIC"' + type: string + x-go-enum-desc: |- + PERIODIC SensitiveDataDiscoveryTaskTypePeriodic + ONE_TIME SensitiveDataDiscoveryTaskTypeOneTime + x-go-name: ExecutionPlan + identification_method: + description: |- + sensitive data identification method + BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName + BY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData + enum: + - BY_FIELD_NAME + - BY_SAMPLE_DATA + example: '"BY_FIELD_NAME"' + type: string + x-go-enum-desc: |- + BY_FIELD_NAME SensitiveDataIdentificationMethodByFieldName + BY_SAMPLE_DATA SensitiveDataIdentificationMethodBySampleData + x-go-name: IdentificationMethod + masking_template_id: + description: masking template id + example: 1 + format: int64 + type: integer + x-go-name: MaskingTemplateID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSensitiveDataDiscoveryTaskData: + properties: + suspected_sensitive_fields_tree: + $ref: '#/definitions/SuspectedSensitiveFieldsTree' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSensitiveDataDiscoveryTaskReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/UpdateSensitiveDataDiscoveryTaskData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSensitiveDataDiscoveryTaskReq: + properties: + action: + description: |- + action type: ENABLE(启用周期扫描), TERMINATE(终止周期扫描), UPDATE(更新配置) + ENABLE SensitiveDataDiscoveryTaskActionEnable + TERMINATE SensitiveDataDiscoveryTaskActionTerminate + UPDATE SensitiveDataDiscoveryTaskActionUpdate + enum: + - ENABLE + - TERMINATE + - UPDATE + example: '"ENABLE"' + type: string + x-go-enum-desc: |- + ENABLE SensitiveDataDiscoveryTaskActionEnable + TERMINATE SensitiveDataDiscoveryTaskActionTerminate + UPDATE SensitiveDataDiscoveryTaskActionUpdate + x-go-name: Action + task: + $ref: '#/definitions/UpdateSensitiveDataDiscoveryTask' + required: + - action + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSmsConfiguration: + properties: + configuration: + additionalProperties: + type: string + type: object + x-go-name: Configuration + enable_sms: + type: boolean + x-go-name: EnableSms + sms_type: + type: string + x-go-name: SmsType + url: + type: string + x-go-name: Url + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSmsConfigurationReq: + properties: + update_sms_configuration: + $ref: '#/definitions/UpdateSmsConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateSystemVariablesReqV1: + properties: + cb_operation_logs_expired_hours: + format: int64 + type: integer + x-go-name: CbOperationLogsExpiredHours + operation_record_expired_hours: + format: int64 + type: integer + x-go-name: OperationRecordExpiredHours + system_variable_sql_manage_raw_expired_hours: + format: int64 + type: integer + x-go-name: SystemVariableSqlManageRawExpiredHours + system_variable_ssh_primary_key: + type: string + x-go-name: SystemVariableSSHPrimaryKey + system_variable_workflow_expired_hours: + format: int64 + type: integer + x-go-name: SystemVariableWorkflowExpiredHours + url: + type: string + x-go-name: Url + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + UpdateUser: + properties: + email: + description: User email + type: string + x-go-name: Email + is_disabled: + description: Whether the user is disabled or not + type: boolean + x-go-name: IsDisabled + language: + description: User language + type: string + x-go-name: Language + op_permission_uids: + description: User operation permission uids + items: + type: string + type: array + x-go-name: OpPermissionUids + password: + description: User password, User can login with this password + type: string + x-go-name: Password + phone: + description: User phone + type: string + x-go-name: Phone + system: + description: |- + User system + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + enum: + - WORKBENCH + - MANAGEMENT + type: string + x-go-enum-desc: |- + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + x-go-name: System + third_party_user_id: + description: 对接登录的参数 + type: string + x-go-name: ThirdPartyUserID + third_party_user_info: + type: string + x-go-name: ThirdPartyUserInfo + user_authentication_type: + type: string + x-go-name: UserAuthenticationType + user_group_uids: + description: User group uids + items: + type: string + type: array + x-go-name: UserGroupUids + wxid: + description: User wxid + type: string + x-go-name: WxID + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateUserGroup: + properties: + desc: + description: UserGroup description + type: string + x-go-name: Desc + is_disabled: + description: Whether the user group is disabled or not + type: boolean + x-go-name: IsDisabled + user_uids: + description: User uids + items: + type: string + type: array + x-go-name: UserUids + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateUserGroupReq: + properties: + user_group: + $ref: '#/definitions/UpdateUserGroup' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateUserReq: + properties: + user: + $ref: '#/definitions/UpdateUser' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateWeChatConfiguration: + properties: + agent_id: + format: int64 + type: integer + x-go-name: AgentID + corp_id: + type: string + x-go-name: CorpID + corp_secret: + type: string + x-go-name: CorpSecret + enable_wechat_notify: + type: boolean + x-go-name: EnableWeChatNotify + proxy_ip: + type: string + x-go-name: ProxyIP + safe_enabled: + type: boolean + x-go-name: SafeEnabled + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateWeChatConfigurationReq: + properties: + update_wechat_configuration: + $ref: '#/definitions/UpdateWeChatConfiguration' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UpdateWebHookConfigurationReq: + properties: + webhook_config: + $ref: '#/definitions/WebHookConfigurationData' + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + User: + description: A user + properties: + desc: + description: user description + type: string + x-go-name: Desc + email: + description: user email + type: string + x-go-name: Email + name: + description: user name + type: string + x-go-name: Name + op_permission_uids: + description: user op permission uid + items: + type: string + type: array + x-go-name: OpPermissionUids + password: + description: user password + type: string + x-go-name: Password + phone: + description: user phone + type: string + x-go-name: Phone + third_party_user_id: + description: 对接登录的参数 + type: string + x-go-name: ThirdPartyUserID + third_party_user_info: + type: string + x-go-name: ThirdPartyUserInfo + uid: + type: string + x-go-name: UID + user_authentication_type: + type: string + x-go-name: UserAuthenticationType + user_group_uids: + description: user group uid + items: + type: string + type: array + x-go-name: UserGroupUids + wxid: + description: user wxid + type: string + x-go-name: WxID + required: + - name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UserBindProject: + properties: + is_manager: + type: boolean + x-go-name: IsManager + project_id: + type: string + x-go-name: ProjectID + project_name: + type: string + x-go-name: ProjectName + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + UserGroup: + description: A user group + properties: + desc: + description: user group description + type: string + x-go-name: Desc + name: + description: user group name + type: string + x-go-name: Name + user_uids: + description: user uids + items: + type: string + type: array + x-go-name: UserUids + required: + - name + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + UserOpPermission: + properties: + project_uid: + description: uesr project uid + type: string + x-go-name: ProjectUid + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + VerifySmsCodeReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + $ref: '#/definitions/VerifySmsCodeReplyData' + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + VerifySmsCodeReplyData: + properties: + is_verify_sent_normally: + type: boolean + x-go-name: IsVerifyNormally + verify_error_message: + type: string + x-go-name: VerifyErrorMessage + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + VerifySmsCodeReq: + properties: + code: + type: string + x-go-name: Code + username: + type: string + x-go-name: Username + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + VerifyUserLoginReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + data: + properties: + phone: + type: string + x-go-name: Phone + two_factor_enabled: + type: boolean + x-go-name: TwoFactorEnabled + user_uid: + description: If verify Successful, return user uid + type: string + x-go-name: UserUid + verify_failed_msg: + description: If verify Successful, return empty string, otherwise return error message + type: string + x-go-name: VerifyFailedMsg + type: object + x-go-name: Data + message: + description: message + type: string + x-go-name: Message + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + WeChatConfigurationResData: + properties: + agent_id: + format: int64 + type: integer + x-go-name: AgentID + corp_id: + type: string + x-go-name: CorpID + enable_wechat_notify: + type: boolean + x-go-name: EnableWeChatNotify + proxy_ip: + type: string + x-go-name: ProxyIP + safe_enabled: + type: boolean + x-go-name: SafeEnabled + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + WebHookConfigurationData: + properties: + enable: + type: boolean + x-go-name: Enable + max_retry_times: + description: minlength(3) maxlength(100) + format: int64 + type: integer + x-go-name: MaxRetryTimes + retry_interval_seconds: + format: int64 + type: integer + x-go-name: RetryIntervalSeconds + token: + type: string + x-go-name: Token + url: + type: string + x-go-name: URL + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + WebHookSendMessageReply: + properties: + code: + description: code + format: int64 + type: integer + x-go-name: Code + message: + description: message + type: string + x-go-name: Message + type: object + x-go-name: WebHooksSendMessageReply + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + WebHookSendMessageReq: + properties: + webhook_message: + $ref: '#/definitions/WebHooksMessage' + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + WebHooksMessage: + properties: + message: + type: string + x-go-name: Message + trigger_event_type: + $ref: '#/definitions/TriggerEventType' + type: object + x-go-package: github.com/actiontech/dms/pkg/dms-common/api/dms/v1 + WorkflowRecord: + properties: + current_step_number: + format: uint64 + type: integer + x-go-name: CurrentStepNumber + status: + enum: + - wait_for_approve + - wait_for_export + - exporting + - rejected + - cancel + - failed + - finish + type: string + x-go-enum-desc: |- + wait_for_approve DataExportWorkflowStatusWaitForApprove + wait_for_export DataExportWorkflowStatusWaitForExport + exporting DataExportWorkflowStatusWaitForExporting + rejected DataExportWorkflowStatusRejected + cancel DataExportWorkflowStatusCancel + failed DataExportWorkflowStatusFailed + finish DataExportWorkflowStatusFinish + x-go-name: Status + tasks: + items: + $ref: '#/definitions/Task' + type: array + x-go-name: Tasks + workflow_step_list: + items: + $ref: '#/definitions/WorkflowStep' + type: array + x-go-name: Steps + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 + WorkflowStep: + properties: + assignee_user_list: + items: + $ref: '#/definitions/UidWithName' + type: array + x-go-name: Users + desc: + type: string + x-go-name: Desc + number: + format: uint64 + type: integer + x-go-name: Number + operation_time: + format: date-time + type: string + x-go-name: OperationTime + operation_user: + $ref: '#/definitions/UidWithName' + reason: + type: string + x-go-name: Reason + state: + enum: + - init + - rejected + - finish + type: string + x-go-enum-desc: |- + init WorkflowStepStatusWaitForExporting + rejected WorkflowStepStatusRejected + finish WorkflowStepStatusFinish + x-go-name: State + type: + type: string + x-go-name: Type + type: object + x-go-package: github.com/actiontech/dms/api/dms/service/v1 +info: + description: Documentation of our dms API. + title: dms api. + version: 0.1.0 +paths: + /v1/dms/basic_info: + get: + operationId: GetBasicInfo + responses: + "200": + description: GetBasicInfoReply + schema: + $ref: '#/definitions/GetBasicInfoReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get basic info. + tags: + - BasicInfo + /v1/dms/company_notice: + get: + description: get company notice info + operationId: GetCompanyNotice + parameters: + - description: when true, return the latest notice regardless of display window (for admin edit) + in: query + name: include_latest_outside_period + type: boolean + x-go-name: IncludeLatestOutsidePeriod + responses: + "200": + description: GetCompanyNoticeReply + schema: + $ref: '#/definitions/GetCompanyNoticeReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - CompanyNotice + patch: + description: update company notice info + operationId: UpdateCompanyNotice + parameters: + - description: Update a companynotice + in: body + name: company_notice + required: true + schema: + $ref: '#/definitions/UpdateCompanyNoticeReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - CompanyNotice + /v1/dms/configurations/feishu: + get: + operationId: GetFeishuConfiguration + responses: + "200": + description: GetFeishuConfigurationReply + schema: + $ref: '#/definitions/GetFeishuConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get feishu configuration. + tags: + - Configuration + patch: + operationId: UpdateFeishuConfiguration + parameters: + - description: update feishu configuration + in: body + name: update_feishu_configuration + schema: + $ref: '#/definitions/UpdateFeishuConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update feishu configuration. + tags: + - Configuration + /v1/dms/configurations/feishu/test: + post: + operationId: TestFeishuConfiguration + parameters: + - description: test feishu configuration + in: body + name: test_feishu_configuration + required: true + schema: + $ref: '#/definitions/TestFeishuConfigurationReq' + responses: + "200": + description: TestFeishuConfigurationReply + schema: + $ref: '#/definitions/TestFeishuConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: test feishu configuration. + tags: + - Configuration + /v1/dms/configurations/ldap: + get: + operationId: GetLDAPConfiguration + responses: + "200": + description: GetLDAPConfigurationResDataReply + schema: + $ref: '#/definitions/GetLDAPConfigurationResDataReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get ldap configuration. + tags: + - Configuration + patch: + operationId: UpdateLDAPConfiguration + parameters: + - description: update ldap configuration + in: body + name: ldap + required: true + schema: + $ref: '#/definitions/UpdateLDAPConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Update ldap configuration. + tags: + - Configuration + /v1/dms/configurations/license: + get: + operationId: GetLicense + responses: + "200": + description: GetLicenseReply + schema: + $ref: '#/definitions/GetLicenseReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get license. + tags: + - Configuration + post: + consumes: + - multipart/form-data + operationId: SetLicense + parameters: + - description: license file. + in: formData + name: license_file + type: file + x-go-name: LicenseFile + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: import license. + tags: + - Configuration + /v1/dms/configurations/license/check: + post: + consumes: + - multipart/form-data + operationId: CheckLicense + parameters: + - description: license file. + in: formData + name: license_file + type: file + x-go-name: LicenseFile + responses: + "200": + description: CheckLicenseReply + schema: + $ref: '#/definitions/CheckLicenseReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: notify message. + tags: + - Configuration + /v1/dms/configurations/license/info: + get: + operationId: GetLicenseInfo + responses: + "200": + $ref: '#/responses/GetLicenseInfoReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get generate license info. + tags: + - Configuration + /v1/dms/configurations/license/usage: + get: + operationId: GetLicenseUsage + responses: + "200": + description: GetLicenseUsageReply + schema: + $ref: '#/definitions/GetLicenseUsageReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get license usage. + tags: + - Configuration + /v1/dms/configurations/login: + patch: + operationId: UpdateLoginConfiguration + parameters: + - description: update login configuration + in: body + name: login + required: true + schema: + $ref: '#/definitions/UpdateLoginConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Update login configuration. + tags: + - Configuration + /v1/dms/configurations/login/tips: + get: + operationId: GetLoginTips + responses: + "200": + description: GetLoginTipsReply + schema: + $ref: '#/definitions/GetLoginTipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get login configuration. + tags: + - Configuration + /v1/dms/configurations/oauth2: + get: + operationId: GetOauth2Configuration + responses: + "200": + description: GetOauth2ConfigurationResDataReply + schema: + $ref: '#/definitions/GetOauth2ConfigurationResDataReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get Oauth2 configuration. + tags: + - Configuration + patch: + operationId: UpdateOauth2Configuration + parameters: + - description: update oauth2 configuration + in: body + name: oauth2 + required: true + schema: + $ref: '#/definitions/Oauth2ConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Update Oauth2 configuration.. + tags: + - Configuration + /v1/dms/configurations/sms: + get: + operationId: GetSmsConfiguration + responses: + "200": + description: GetSmsConfigurationReply + schema: + $ref: '#/definitions/GetSmsConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get sms configuration. + tags: + - Configuration + patch: + operationId: UpdateSmsConfiguration + parameters: + - description: update sms configuration + in: body + name: update_sms_configuration + required: true + schema: + $ref: '#/definitions/UpdateSmsConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update sms configuration. + tags: + - Configuration + /v1/dms/configurations/sms/send_code: + post: + operationId: SendSmsCode + parameters: + - description: user name + in: body + name: username + required: true + schema: + $ref: '#/definitions/SendSmsCodeReq' + responses: + "200": + description: SendSmsCodeReply + schema: + $ref: '#/definitions/SendSmsCodeReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: send sms code. + tags: + - SMS + /v1/dms/configurations/sms/test: + post: + operationId: TestSmsConfiguration + parameters: + - description: test sms configuration + in: body + name: test_sms_configuration + required: true + schema: + $ref: '#/definitions/TestSmsConfigurationReq' + responses: + "200": + description: TestSmsConfigurationReply + schema: + $ref: '#/definitions/TestSmsConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: test smtp configuration. + tags: + - Configuration + /v1/dms/configurations/sms/verify_code: + post: + operationId: VerifySmsCode + parameters: + - description: verify sms code + in: body + name: code + required: true + schema: + $ref: '#/definitions/VerifySmsCodeReq' + - description: user name + in: body + name: username + required: true + schema: + $ref: '#/definitions/VerifySmsCodeReq' + responses: + "200": + description: VerifySmsCodeReply + schema: + $ref: '#/definitions/VerifySmsCodeReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: verify sms code. + tags: + - SMS + /v1/dms/configurations/smtp: + get: + operationId: GetSMTPConfiguration + responses: + "200": + description: GetSMTPConfigurationReply + schema: + $ref: '#/definitions/GetSMTPConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get smtp configuration. + tags: + - Configuration + patch: + operationId: UpdateSMTPConfiguration + parameters: + - description: update smtp configuration + in: body + name: smtp_configuration + required: true + schema: + $ref: '#/definitions/UpdateSMTPConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Update smtp configuration. + tags: + - Configuration + /v1/dms/configurations/smtp/test: + post: + operationId: TestSMTPConfiguration + parameters: + - description: test smtp configuration + in: body + name: test_smtp_configuration + required: true + schema: + $ref: '#/definitions/TestSMTPConfigurationReq' + responses: + "200": + description: TestSMTPConfigurationReply + schema: + $ref: '#/definitions/TestSMTPConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: test smtp configuration. + tags: + - Configuration + /v1/dms/configurations/sql_query: + get: + operationId: GetSQLQueryConfiguration + responses: + "200": + description: GetSQLQueryConfigurationReply + schema: + $ref: '#/definitions/GetSQLQueryConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get sql_query configuration. + tags: + - CloudBeaver + /v1/dms/configurations/system_variables: + get: + description: 获取系统变量配置 + operationId: GetSystemVariables + responses: + "200": + description: GetSystemVariablesReply + schema: + $ref: '#/definitions/GetSystemVariablesReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - Configuration + patch: + description: 更新系统变量配置 + operationId: UpdateSystemVariables + parameters: + - description: 更新系统变量配置 + in: body + name: system_variables + required: true + schema: + $ref: '#/definitions/UpdateSystemVariablesReqV1' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - Configuration + /v1/dms/configurations/webhook: + get: + operationId: GetWebHookConfiguration + responses: + "200": + description: GetWebHookConfigurationReply + schema: + $ref: '#/definitions/GetWebHookConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get webhook configuration. + tags: + - Configuration + patch: + operationId: UpdateWebHookConfiguration + parameters: + - description: webhook configuration + in: body + name: webhook_config + schema: + $ref: '#/definitions/UpdateWebHookConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update webhook configuration. + tags: + - Configuration + /v1/dms/configurations/webhook/test: + post: + operationId: TestWebHookConfiguration + responses: + "200": + description: TestWebHookConfigurationReply + schema: + $ref: '#/definitions/TestWebHookConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: test webhook configuration. + tags: + - Configuration + /v1/dms/configurations/wechat: + get: + operationId: GetWeChatConfiguration + responses: + "200": + description: GetWeChatConfigurationReply + schema: + $ref: '#/definitions/GetWeChatConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: get wechat configuration. + tags: + - Configuration + patch: + operationId: UpdateWeChatConfiguration + parameters: + - description: update wechat configuration + in: body + name: update_wechat_configuration + schema: + $ref: '#/definitions/UpdateWeChatConfigurationReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update wechat configuration. + tags: + - Configuration + /v1/dms/configurations/wechat/test: + post: + operationId: TestWeChatConfiguration + parameters: + - description: test wechat configuration + in: body + name: test_wechat_configuration + schema: + $ref: '#/definitions/TestWeChatConfigurationReq' + responses: + "200": + description: TestWeChatConfigurationReply + schema: + $ref: '#/definitions/TestWeChatConfigurationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: test wechat configuration. + tags: + - Configuration + /v1/dms/dashboard/data_export_workflows: + get: + operationId: GetGlobalDataExportWorkflows + responses: + "200": + description: GetGlobalDataExportWorkflowsReply + schema: + $ref: '#/definitions/GetGlobalDataExportWorkflowsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get global data export workflows. + tags: + - DataExportWorkflows + /v1/dms/db_service_sync_tasks: + get: + operationId: ListDBServiceSyncTasks + responses: + "200": + description: ListDBServiceSyncTasksReply + schema: + $ref: '#/definitions/ListDBServiceSyncTasksReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List database synchronization tasks. + tags: + - DBServiceSyncTask + post: + operationId: AddDBServiceSyncTask + parameters: + - description: Add new db service sync task + in: body + name: db_service_sync_task + required: true + schema: + $ref: '#/definitions/AddDBServiceSyncTaskReq' + responses: + "200": + description: AddDBServiceReply + schema: + $ref: '#/definitions/AddDBServiceReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add database synchronization task. + tags: + - DBServiceSyncTask + /v1/dms/db_service_sync_tasks/{db_service_sync_task_uid}: + delete: + operationId: DeleteDBServiceSyncTask + parameters: + - description: db service sync task uid + in: path + name: db_service_sync_task_uid + required: true + type: string + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Delete database synchronization task. + tags: + - DBServiceSyncTask + get: + operationId: GetDBServiceSyncTask + parameters: + - description: db service sync task uid + in: path + name: db_service_sync_task_uid + required: true + type: string + responses: + "200": + description: GetDBServiceSyncTaskReply + schema: + $ref: '#/definitions/GetDBServiceSyncTaskReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get database synchronization task. + tags: + - DBServiceSyncTask + put: + operationId: UpdateDBServiceSyncTask + parameters: + - description: db service sync task uid + in: path + name: db_service_sync_task_uid + required: true + type: string + - description: update db service sync task + in: body + name: db_service_sync_task + required: true + schema: + $ref: '#/definitions/UpdateDBServiceSyncTaskReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update database synchronization task. + tags: + - DBServiceSyncTask + /v1/dms/db_service_sync_tasks/{db_service_sync_task_uid}/sync: + post: + operationId: SyncDBServices + parameters: + - description: db service sync task uid + in: path + name: db_service_sync_task_uid + required: true + type: string + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Sync db service. + tags: + - DBServiceSyncTask + /v1/dms/db_service_sync_tasks/tips: + get: + operationId: ListDBServiceSyncTaskTips + responses: + "200": + description: ListDBServiceSyncTaskTipsReply + schema: + $ref: '#/definitions/ListDBServiceSyncTaskTipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List database synchronization task tips. + tags: + - DBServiceSyncTask + /v1/dms/db_services: + get: + deprecated: true + description: list global DBServices + operationId: ListGlobalDBServices + parameters: + - description: the maximum count of db service to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of users to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + Multiple of ["name"], default is ["name"] + name DBServiceOrderByName + enum: + - name + in: query + name: order_by + type: string + x-go-enum-desc: name DBServiceOrderByName + x-go-name: OrderBy + - description: the db service connection + enum: + - connect_success + - connect_failed + in: query + name: filter_last_connection_test_status + type: string + x-go-name: FilterLastConnectionTestStatus + - description: |- + TODO This parameter is deprecated and will be removed soon. + the db service business name + in: query + name: filter_by_business + type: string + x-go-name: FilterByBusiness + - description: filter db services by environment tag + in: query + name: filter_by_environment_tag + type: string + x-go-name: FilterByEnvironmentTag + - description: the db service host + in: query + name: filter_by_host + type: string + x-go-name: FilterByHost + - description: the db service uid + in: query + name: filter_by_uid + type: string + x-go-name: FilterByUID + - description: the db service name + in: query + name: filter_by_name + type: string + x-go-name: FilterByName + - description: the db service port + in: query + name: filter_by_port + type: string + x-go-name: FilterByPort + - description: the db service db type + in: query + name: filter_by_db_type + type: string + x-go-name: FilterByDBType + - description: the db service project id + in: query + name: filter_by_project_uid + type: string + x-go-name: FilterByProjectUid + - description: is masking + in: query + name: filter_by_is_enable_masking + type: boolean + x-go-name: FilterByIsEnableMasking + - description: the db service fuzzy keyword + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword + responses: + "200": + description: ListGlobalDBServicesReply + schema: + $ref: '#/definitions/ListGlobalDBServicesReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - DBService + /v1/dms/db_services/driver_options: + get: + operationId: ListDBServiceDriverOption + responses: + "200": + description: ListDBServiceDriverOptionReply + schema: + $ref: '#/definitions/ListDBServiceDriverOptionReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List db service driver option. + tags: + - DBService + /v1/dms/db_services/tips: + get: + description: list global DBServices tips + operationId: ListGlobalDBServicesTips + parameters: + - description: |- + function support filter, when specified, returns the db types supported by the function + data_masking FunctionSupportTypeDataMasking FunctionSupportTypeDataMasking 数据脱敏功能 + enum: + - data_masking + example: data_masking + in: query + name: function_support + type: string + x-go-enum-desc: data_masking FunctionSupportTypeDataMasking FunctionSupportTypeDataMasking 数据脱敏功能 + x-go-name: FunctionSupport + responses: + "200": + description: ListGlobalDBServicesTipsReply + schema: + $ref: '#/definitions/ListGlobalDBServicesTipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - DBService + /v1/dms/gateways: + get: + operationId: ListGateways + parameters: + - format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + responses: + "200": + description: ListGatewaysReply + schema: + $ref: '#/definitions/ListGatewaysReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List gateways. + tags: + - Gateway + post: + operationId: AddGateway + parameters: + - description: add gateway + in: body + name: add_gateway + required: true + schema: + $ref: '#/definitions/AddGatewayReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add gateways. + tags: + - Gateway + /v1/dms/gateways/{gateway_id}: + delete: + operationId: DeleteGateway + parameters: + - in: path + name: gateway_id + required: true + type: string + x-go-name: DeleteGatewayID + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Delete gateways. + tags: + - Gateway + get: + operationId: GetGateway + parameters: + - in: path + name: gateway_id + required: true + type: string + x-go-name: GetGatewayID + responses: + "200": + description: GetGatewayReply + schema: + $ref: '#/definitions/GetGatewayReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get gateways. + tags: + - Gateway + put: + operationId: UpdateGateway + parameters: + - description: gateway id + in: path + name: gateway_id + required: true + type: string + - description: update gateway + in: body + name: update_gateway + required: true + schema: + $ref: '#/definitions/UpdateGatewayReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update gateways. + tags: + - Gateway + /v1/dms/gateways/tips: + get: + operationId: GetGatewayTips + responses: + "200": + description: GetGatewayTipsReply + schema: + $ref: '#/definitions/GetGatewayTipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get gateway tips. + tags: + - Gateway + /v1/dms/masking/rules: + get: + operationId: ListMaskingRules + responses: + "200": + description: List masking rules successfully + schema: + $ref: '#/definitions/ListMaskingRulesReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: List masking rules. + tags: + - Masking + /v1/dms/notifications: + post: + operationId: Notification + parameters: + - description: notification + in: body + name: notification + schema: + $ref: '#/definitions/Notification' + x-go-name: Notification + responses: + "200": + description: NotificationReply + schema: + $ref: '#/definitions/NotificationReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: notify message. + tags: + - Notification + /v1/dms/oauth2/link: + get: + operationId: Oauth2LinkOrCallback + summary: Oauth2 Link or Callback. + tags: + - OAuth2 + /v1/dms/oauth2/tips: + get: + operationId: GetOauth2Tips + responses: + "200": + description: GetOauth2TipsReply + schema: + $ref: '#/definitions/GetOauth2TipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get Oauth2 Tips. + tags: + - OAuth2 + /v1/dms/oauth2/user/bind: + post: + operationId: BindOauth2User + parameters: + - in: body + name: BindOauth2UserReq + required: true + schema: + $ref: '#/definitions/BindOauth2UserReq' + responses: + "200": + description: BindOauth2UserReply + schema: + $ref: '#/definitions/BindOauth2UserReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Bind Oauth2 User. + tags: + - OAuth2 + /v1/dms/op_permissions: + get: + operationId: ListOpPermissions + parameters: + - description: the maximum count of op permission to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of op permissions to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + Order by the specified field + name OpPermissionOrderByName + enum: + - name + in: query + name: order_by + type: string + x-go-enum-desc: name OpPermissionOrderByName + x-go-name: OrderBy + - description: |- + filter by op permission target + all OpPermissionTargetAll + user OpPermissionTargetUser + member OpPermissionTargetMember + project OpPermissionTargetProject + enum: + - all + - user + - member + - project + in: query + name: filter_by_target + type: string + x-go-enum-desc: |- + all OpPermissionTargetAll + user OpPermissionTargetUser + member OpPermissionTargetMember + project OpPermissionTargetProject + x-go-name: FilterByTarget + - description: |- + filter by service + dms ServiceDMS + sqle ServiceSQLE + enum: + - dms + - sqle + in: query + name: service + type: string + x-go-enum-desc: |- + dms ServiceDMS + sqle ServiceSQLE + x-go-name: Service + responses: + "200": + description: ListOpPermissionReply + schema: + $ref: '#/definitions/ListOpPermissionReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List op permission. + tags: + - OpPermission + /v1/dms/operation_records: + get: + operationId: GetOperationRecordList + parameters: + - in: query + name: filter_operate_time_from + type: string + x-go-name: FilterOperateTimeFrom + - in: query + name: filter_operate_time_to + type: string + x-go-name: FilterOperateTimeTo + - in: query + name: filter_operate_project_name + type: string + x-go-name: FilterOperateProjectName + - in: query + name: fuzzy_search_operate_user_name + type: string + x-go-name: FuzzySearchOperateUserName + - in: query + name: filter_operate_type_name + type: string + x-go-name: FilterOperateTypeName + - in: query + name: filter_operate_action + type: string + x-go-name: FilterOperateAction + - format: uint32 + in: query + name: page_index + required: true + type: integer + x-go-name: PageIndex + - format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + responses: + "200": + description: GetOperationRecordListReply + schema: + $ref: '#/definitions/GetOperationRecordListReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get operation record list. + tags: + - OperationRecord + post: + operationId: AddOperationRecord + parameters: + - description: Add new operation record + in: body + name: operation_record + required: true + schema: + $ref: '#/definitions/AddOperationRecordReq' + responses: + "200": + description: AddOperationRecordReply + schema: + $ref: '#/definitions/AddOperationRecordReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add operation record. + tags: + - OperationRecord + /v1/dms/operation_records/exports: + get: + operationId: ExportOperationRecordList + parameters: + - in: query + name: filter_operate_time_from + type: string + x-go-name: FilterOperateTimeFrom + - in: query + name: filter_operate_time_to + type: string + x-go-name: FilterOperateTimeTo + - in: query + name: filter_operate_project_name + type: string + x-go-name: FilterOperateProjectName + - in: query + name: fuzzy_search_operate_user_name + type: string + x-go-name: FuzzySearchOperateUserName + - in: query + name: filter_operate_type_name + type: string + x-go-name: FilterOperateTypeName + - in: query + name: filter_operate_action + type: string + x-go-name: FilterOperateAction + responses: + "200": + description: ExportOperationRecordListReply + schema: + type: file + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Export operation record list. + tags: + - OperationRecord + /v1/dms/personalization: + post: + operationId: Personalization + parameters: + - description: title + in: formData + name: title + type: string + - description: file upload + in: formData + name: file + type: file + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: personalize [title, logo]. + tags: + - BasicInfo + /v1/dms/personalization/logo: + get: + description: get logo + operationId: GetStaticLogo + produces: + - application/octet-stream + responses: + "200": + $ref: '#/responses/GetStaticLogoReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - BasicInfo + /v1/dms/plugins: + post: + operationId: RegisterDMSPlugin + parameters: + - description: Register dms plugin + in: body + name: plugin + required: true + schema: + $ref: '#/definitions/RegisterDMSPluginReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Register dms plugin. + tags: + - DMSPlugin + /v1/dms/projects: + get: + deprecated: true + operationId: ListProjects + parameters: + - description: the maximum count of Project to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of Projects to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + Multiple of ["name"], default is ["name"] + name ProjectOrderByName + enum: + - name + in: query + name: order_by + type: string + x-go-enum-desc: name ProjectOrderByName + x-go-name: OrderBy + - description: filter the Project name + in: query + name: filter_by_name + type: string + x-go-name: FilterByName + - description: filter the Project UID + in: query + name: filter_by_uid + type: string + x-go-name: FilterByUID + - description: filter project by project id list, using in condition + in: query + items: + type: string + name: filter_by_project_uids + type: array + x-go-name: FilterByProjectUids + - description: |- + filter project by project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + in: query + name: filter_by_project_priority + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: FilterByProjectPriority + - description: filter the Project By Project description + in: query + name: filter_by_desc + type: string + x-go-name: FilterByDesc + responses: + "200": + description: ListProjectReply + schema: + $ref: '#/definitions/ListProjectReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List projects. + tags: + - Project + post: + deprecated: true + operationId: AddProject + parameters: + - description: Add new Project + in: body + name: project + required: true + schema: + $ref: '#/definitions/AddProjectReq' + responses: + "200": + description: AddProjectReply + schema: + $ref: '#/definitions/AddProjectReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add project. + tags: + - Project + /v1/dms/projects/{project_uid}: + delete: + description: Delete a project + operationId: DelProject + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + tags: + - Project + put: + deprecated: true + operationId: UpdateProject + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: Update a project + in: body + name: project + required: true + schema: + $ref: '#/definitions/UpdateProjectReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update a project. + tags: + - Project + /v1/dms/projects/{project_uid}/archive: + put: + operationId: ArchiveProject + parameters: + - description: Project uid + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Archive a project. + tags: + - Project + /v1/dms/projects/{project_uid}/cb_operation_logs: + get: + operationId: ListCBOperationLogs + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: query + name: filter_operation_person_uid + type: string + x-go-name: FilterOperationPersonUID + - in: query + name: filter_operation_time_from + type: string + x-go-name: FilterOperationTimeFrom + - in: query + name: filter_operation_time_to + type: string + x-go-name: FilterOperationTimeTo + - in: query + name: filter_db_service_uid + type: string + x-go-name: FilterDBServiceUID + - in: query + name: filter_exec_result + type: string + x-go-name: FilterExecResult + - description: filter fuzzy key word for operation_detail/operation_ip + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword + - description: the maximum count of member to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of members to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + responses: + "200": + description: ListCBOperationLogsReply + schema: + $ref: '#/definitions/ListCBOperationLogsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List cb operation logs. + tags: + - CBOperationLogs + /v1/dms/projects/{project_uid}/cb_operation_logs/export: + get: + operationId: ExportCBOperationLogs + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: query + name: filter_operation_person_uid + type: string + x-go-name: FilterOperationPersonUID + - in: query + name: filter_operation_time_from + type: string + x-go-name: FilterOperationTimeFrom + - in: query + name: filter_operation_time_to + type: string + x-go-name: FilterOperationTimeTo + - in: query + name: filter_db_service_uid + type: string + x-go-name: FilterDBServiceUID + - in: query + name: filter_exec_result + type: string + x-go-name: FilterExecResult + - description: filter fuzzy key word for operation_detail/operation_ip + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword + responses: + "200": + $ref: '#/responses/ExportCBOperationLogsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Export cb operation logs. + tags: + - CBOperationLogs + /v1/dms/projects/{project_uid}/cb_operation_logs/tips: + get: + operationId: GetCBOperationLogTips + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: GetCBOperationLogTipsReply + schema: + $ref: '#/definitions/GetCBOperationLogTipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get cb operation log tips. + tags: + - CBOperationLogs + /v1/dms/projects/{project_uid}/data_export_tasks: + get: + operationId: BatchGetDataExportTask + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: query + name: data_export_task_uids + required: true + type: string + x-go-name: TaskUids + responses: + "200": + description: BatchGetDataExportTaskReply + schema: + $ref: '#/definitions/BatchGetDataExportTaskReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Batch get data_export task. + tags: + - DataExportTask + post: + operationId: AddDataExportTask + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: add data export workflow + in: body + name: data_export_tasks + schema: + $ref: '#/definitions/AddDataExportTaskReq' + responses: + "200": + description: AddDataExportTaskReply + schema: + $ref: '#/definitions/AddDataExportTaskReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add data_export task. + tags: + - DataExportTask + /v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/data_export_task_sqls: + get: + operationId: ListDataExportTaskSQLs + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: path + name: data_export_task_uid + required: true + type: string + x-go-name: DataExportTaskUid + - description: the maximum count of member to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of members to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + responses: + "200": + description: ListDataExportTaskSQLsReply + schema: + $ref: '#/definitions/ListDataExportTaskSQLsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List data_export workflow. + tags: + - DataExportTask + /v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/data_export_task_sqls/download: + get: + operationId: DownloadDataExportTaskSQLs + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: path + name: data_export_task_uid + required: true + type: string + x-go-name: DataExportTaskUid + responses: + "200": + $ref: '#/responses/DownloadDataExportTaskSQLsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: dowload data_export sqls. + tags: + - DataExportTask + /v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/download: + get: + operationId: DownloadDataExportTask + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: path + name: data_export_task_uid + required: true + type: string + x-go-name: DataExportTaskUid + responses: + "200": + $ref: '#/responses/DownloadDataExportTaskReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: download task file. + tags: + - DataExportTask + /v1/dms/projects/{project_uid}/data_export_workflows: + get: + operationId: ListDataExportWorkflows + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: the maximum count of member to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of members to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + filter the status + wait_for_approve DataExportWorkflowStatusWaitForApprove + wait_for_export DataExportWorkflowStatusWaitForExport + exporting DataExportWorkflowStatusWaitForExporting + rejected DataExportWorkflowStatusRejected + cancel DataExportWorkflowStatusCancel + failed DataExportWorkflowStatusFailed + finish DataExportWorkflowStatusFinish + enum: + - wait_for_approve + - wait_for_export + - exporting + - rejected + - cancel + - failed + - finish + in: query + name: filter_by_status + type: string + x-go-enum-desc: |- + wait_for_approve DataExportWorkflowStatusWaitForApprove + wait_for_export DataExportWorkflowStatusWaitForExport + exporting DataExportWorkflowStatusWaitForExporting + rejected DataExportWorkflowStatusRejected + cancel DataExportWorkflowStatusCancel + failed DataExportWorkflowStatusFailed + finish DataExportWorkflowStatusFinish + x-go-name: FilterByStatus + - description: filter create user id + in: query + name: filter_by_create_user_uid + type: string + x-go-name: FilterByCreateUserUid + - description: filter current assignee user id + in: query + name: filter_current_step_assignee_user_uid + type: string + x-go-name: FilterCurrentStepAssigneeUserUid + - description: filter db_service id + in: query + name: filter_by_db_service_uid + type: string + x-go-name: FilterByDBServiceUid + - description: filter create time from + in: query + name: filter_create_time_from + type: string + x-go-name: FilterCreateTimeFrom + - description: filter create time end + in: query + name: filter_create_time_to + type: string + x-go-name: FilterCreateTimeTo + - description: filter fuzzy key word for id/name + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword + responses: + "200": + description: ListDataExportWorkflowsReply + schema: + $ref: '#/definitions/ListDataExportWorkflowsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List data_export workflow. + tags: + - DataExportWorkflows + post: + operationId: AddDataExportWorkflow + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: add data export workflow + in: body + name: data_export_workflow + schema: + $ref: '#/definitions/AddDataExportWorkflowReq' + responses: + "200": + description: AddDataExportWorkflowReply + schema: + $ref: '#/definitions/AddDataExportWorkflowReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add data_export workflow. + tags: + - DataExportWorkflows + /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}: + get: + operationId: GetDataExportWorkflow + parameters: + - in: path + name: data_export_workflow_uid + required: true + type: string + x-go-name: DataExportWorkflowUid + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: GetDataExportWorkflowReply + schema: + $ref: '#/definitions/GetDataExportWorkflowReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get data_export workflow. + tags: + - DataExportWorkflows + /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/approve: + post: + operationId: ApproveDataExportWorkflow + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: path + name: data_export_workflow_uid + required: true + type: string + x-go-name: DataExportWorkflowUid + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Approve data_export workflow. + tags: + - DataExportWorkflows + /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/export: + post: + operationId: ExportDataExportWorkflow + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: path + name: data_export_workflow_uid + required: true + type: string + x-go-name: DataExportWorkflowUid + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: exec data_export workflow. + tags: + - DataExportWorkflows + /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/reject: + post: + operationId: RejectDataExportWorkflow + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - in: path + name: data_export_workflow_uid + required: true + type: string + - in: body + name: payload + required: true + schema: + $ref: '#/definitions/RejectDataExportWorkflowReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Reject data_export workflow. + tags: + - DataExportWorkflows + /v1/dms/projects/{project_uid}/data_export_workflows/cancel: + post: + operationId: CancelDataExportWorkflow + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - in: body + name: payload + required: true + schema: + $ref: '#/definitions/CancelDataExportWorkflowReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Cancel data export workflows. + tags: + - DataExportWorkflows + /v1/dms/projects/{project_uid}/db_services: + get: + deprecated: true + operationId: ListDBServices + parameters: + - description: the maximum count of db service to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of users to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + Multiple of ["name"], default is ["name"] + name DBServiceOrderByName + enum: + - name + in: query + name: order_by + type: string + x-go-enum-desc: name DBServiceOrderByName + x-go-name: OrderBy + - description: the db service business name + in: query + name: filter_by_business + type: string + x-go-name: FilterByBusiness + - description: the db service connection + enum: + - connect_success + - connect_failed + in: query + name: filter_last_connection_test_status + type: string + x-go-name: FilterLastConnectionTestStatus + - description: the db service host + in: query + name: filter_by_host + type: string + x-go-name: FilterByHost + - description: the db service uid + in: query + name: filter_by_uid + type: string + x-go-name: FilterByUID + - description: the db service name + in: query + name: filter_by_name + type: string + x-go-name: FilterByName + - description: the db service port + in: query + name: filter_by_port + type: string + x-go-name: FilterByPort + - description: the db service db type + in: query + name: filter_by_db_type + type: string + x-go-name: FilterByDBType + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: filter db services by db service id list using in condition + in: query + items: + type: string + name: filter_by_db_service_ids + type: array + x-go-name: FilterByDBServiceIds + - description: the db service fuzzy keyword,include host/port + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword + - description: is masking + in: query + name: is_enable_masking + type: boolean + x-go-name: IsEnableMasking + responses: + "200": + description: ListDBServiceReply + schema: + $ref: '#/definitions/ListDBServiceReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List db service. + tags: + - DBService + post: + deprecated: true + operationId: AddDBService + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: Add new db service + in: body + name: db_service + required: true + schema: + $ref: '#/definitions/AddDBServiceReq' + responses: + "200": + description: AddDBServiceReply + schema: + $ref: '#/definitions/AddDBServiceReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add DB Service. + tags: + - DBService + /v1/dms/projects/{project_uid}/db_services/{db_service_uid}: + delete: + operationId: DelDBService + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: db service uid + in: path + name: db_service_uid + required: true + type: string + x-go-name: DBServiceUid + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Delete a DB Service. + tags: + - DBService + put: + deprecated: true + operationId: UpdateDBService + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: db_service_uid id + in: path + name: db_service_uid + required: true + type: string + - description: Update a DB service + in: body + name: db_service + schema: + $ref: '#/definitions/UpdateDBServiceReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: update a DB Service. + tags: + - DBService + /v1/dms/projects/{project_uid}/db_services/{db_service_uid}/connection: + post: + operationId: CheckDBServiceIsConnectableById + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: db service uid + in: path + name: db_service_uid + required: true + type: string + responses: + "200": + description: CheckDBServiceIsConnectableReply + schema: + $ref: '#/definitions/CheckDBServiceIsConnectableReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: check if the db_service is connectable. + tags: + - DBService + /v1/dms/projects/{project_uid}/db_services/connection: + post: + operationId: CheckDBServiceIsConnectable + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: check db_service is connectable + in: body + name: db_service + schema: + $ref: '#/definitions/CheckDBServiceIsConnectableReq' + responses: + "200": + description: CheckDBServiceIsConnectableReply + schema: + $ref: '#/definitions/CheckDBServiceIsConnectableReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: check if the db_service is connectable. + tags: + - DBService + /v1/dms/projects/{project_uid}/db_services/connections: + post: + operationId: CheckProjectDBServicesConnections + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: check db_services is connectable + in: body + name: db_services + schema: + $ref: '#/definitions/CheckDBServicesIsConnectableReq' + responses: + "200": + description: CheckDBServicesIsConnectableReply + schema: + $ref: '#/definitions/CheckDBServicesIsConnectableReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: check if the project db_services is connectable. + tags: + - DBService + /v1/dms/projects/{project_uid}/db_services/import: + post: + deprecated: true + operationId: ImportDBServicesOfOneProject + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: new db services + in: body + name: db_services + required: true + schema: + $ref: '#/definitions/ImportDBServicesOfOneProjectReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Import DBServices. + tags: + - DBService + /v1/dms/projects/{project_uid}/db_services/import_check: + post: + consumes: + - multipart/form-data + deprecated: true + operationId: ImportDBServicesOfOneProjectCheck + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: DBServices file. + in: formData + name: db_services_file + type: file + x-go-name: DBServicesFile + produces: + - application/json + - text/csv + responses: + "200": + $ref: '#/responses/ImportDBServicesCheckCsvReply' + default: + description: ImportDBServicesCheckReply + schema: + $ref: '#/definitions/ImportDBServicesCheckReply' + summary: Import DBServices. + tags: + - DBService + /v1/dms/projects/{project_uid}/db_services/tips: + get: + operationId: ListDBServiceTips + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - in: query + name: filter_db_type + type: string + x-go-name: FilterDBType + - enum: + - save_audit_plan + - create_workflow + - create_export_task + in: query + name: functional_module + type: string + x-go-name: FunctionalModule + responses: + "200": + description: ListDBServiceTipsReply + schema: + $ref: '#/definitions/ListDBServiceTipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List db service tip. + tags: + - DBService + /v1/dms/projects/{project_uid}/environment_tags: + get: + operationId: ListEnvironmentTags + parameters: + - in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUID + - format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + responses: + "200": + description: ListEnvironmentTagsReply + schema: + $ref: '#/definitions/ListEnvironmentTagsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List environment tags. + tags: + - Project + post: + operationId: CreateEnvironmentTag + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: the name of environment tag to be created + in: body + name: environment_name + required: true + type: string + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Create a new environment tag. + tags: + - Project + /v1/dms/projects/{project_uid}/environment_tags/{environment_tag_uid}: + delete: + operationId: DeleteEnvironmentTag + parameters: + - in: path + name: environment_tag_uid + required: true + type: string + x-go-name: EnvironmentTagUID + - in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUID + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Delete an existing environment tag. + tags: + - Project + put: + operationId: UpdateEnvironmentTag + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: environment tag id + in: path + name: environment_tag_uid + required: true + type: string + - description: the name of environment tag to be updated + in: body + name: environment_name + required: true + type: string + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Update an existing environment tag. + tags: + - Project + /v1/dms/projects/{project_uid}/masking/approval-requests/{request_id}: + get: + operationId: GetPlaintextAccessRequestDetail + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: approval request id + example: 1 + format: int64 + in: path + name: request_id + required: true + type: integer + x-go-name: RequestID + responses: + "200": + description: Get plaintext access request detail successfully + schema: + $ref: '#/definitions/GetPlaintextAccessRequestDetailReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Get plaintext access request detail. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/approval-requests/{request_id}/decisions: + post: + operationId: ProcessApprovalRequest + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: approval request id + in: path + name: request_id + required: true + type: integer + - description: process action info + in: body + name: action + required: true + schema: + $ref: '#/definitions/ProcessApprovalRequestReq' + responses: + "200": + description: Process approval request successfully + schema: + $ref: '#/definitions/ProcessApprovalRequestReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Process approval request. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/approval-requests/pending: + get: + operationId: ListPendingApprovalRequests + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: the maximum count of requests to be returned, default is 20 + example: "20" + format: uint32 + in: query + name: page_size + type: integer + x-go-name: PageSize + - description: the offset of requests to be returned, default is 0 + example: "0" + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + responses: + "200": + description: List pending approval requests successfully + schema: + $ref: '#/definitions/ListPendingApprovalRequestsReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: List pending approval requests. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/overview: + get: + operationId: GetMaskingOverviewTree + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: data source id + example: '"1"' + in: query + name: db_service_uid + required: true + type: string + x-go-name: DBServiceUID + - description: fuzzy search keyword for database name, table name, and column name + example: '"user"' + in: query + name: keywords + type: string + x-go-name: Keywords + - description: 'masking config status filters, enum: CONFIGURED/PENDING_CONFIRM' + enum: + - CONFIGURED + - PENDING_CONFIRM + - SYSTEM_CONFIRMED + in: query + name: masking_config_statuses + type: string + x-go-enum-desc: |- + CONFIGURED MaskingConfigStatusConfigured + PENDING_CONFIRM MaskingConfigStatusPendingConfirm + SYSTEM_CONFIRMED MaskingConfigStatusSystemConfirmed + x-go-name: MaskingConfigStatus + responses: + "200": + description: Get masking overview tree successfully + schema: + $ref: '#/definitions/GetMaskingOverviewTreeReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Get masking overview tree. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/rule-configs: + put: + operationId: ConfigureMaskingRules + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: masking rule configurations for batch create or update + in: body + name: masking_rule_configs_req + required: true + schema: + $ref: '#/definitions/ConfigureMaskingRulesReq' + responses: + "200": + description: Configure masking rules successfully + schema: + $ref: '#/definitions/ConfigureMaskingRulesReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Configure masking rules in batch. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks: + get: + operationId: ListSensitiveDataDiscoveryTasks + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: the maximum count of tasks to be returned, default is 20 + example: "20" + format: uint32 + in: query + name: page_size + type: integer + x-go-name: PageSize + - description: the offset of tasks to be returned, default is 0 + example: "0" + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + responses: + "200": + description: List sensitive data discovery tasks successfully + schema: + $ref: '#/definitions/ListSensitiveDataDiscoveryTasksReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: List sensitive data discovery tasks. + tags: + - Masking + post: + operationId: AddSensitiveDataDiscoveryTask + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: sensitive data discovery task info + in: body + name: task + required: true + schema: + $ref: '#/definitions/AddSensitiveDataDiscoveryTaskReq' + responses: + "200": + description: Add sensitive data discovery task successfully + schema: + $ref: '#/definitions/AddSensitiveDataDiscoveryTaskReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Add sensitive data discovery task. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/{task_id}: + delete: + operationId: DeleteSensitiveDataDiscoveryTask + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: sensitive data discovery task id + example: 1 + format: int64 + in: path + name: task_id + required: true + type: integer + x-go-name: TaskID + responses: + "200": + description: Delete sensitive data discovery task successfully + schema: + $ref: '#/definitions/DeleteSensitiveDataDiscoveryTaskReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Delete sensitive data discovery task. + tags: + - Masking + put: + operationId: UpdateSensitiveDataDiscoveryTask + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: sensitive data discovery task id + in: path + name: task_id + required: true + type: integer + - description: sensitive data discovery task info + in: body + name: task + required: true + schema: + $ref: '#/definitions/UpdateSensitiveDataDiscoveryTaskReq' + responses: + "200": + description: Update sensitive data discovery task successfully + schema: + $ref: '#/definitions/UpdateSensitiveDataDiscoveryTaskReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Update sensitive data discovery task. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/{task_id}/histories: + get: + operationId: ListSensitiveDataDiscoveryTaskHistories + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: sensitive data discovery task id + example: 1 + format: int64 + in: path + name: task_id + required: true + type: integer + x-go-name: TaskID + - description: the maximum count of histories to be returned, default is 20 + example: "20" + format: uint32 + in: query + name: page_size + type: integer + x-go-name: PageSize + - description: the offset of histories to be returned, default is 0 + example: "0" + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + responses: + "200": + description: List sensitive data discovery task histories successfully + schema: + $ref: '#/definitions/ListSensitiveDataDiscoveryTaskHistoriesReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: List sensitive data discovery task histories. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/creatable-db-services: + get: + operationId: ListCreatableDBServicesForMaskingTask + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: the maximum count of db services to be returned, default is 100 + example: "100" + format: uint32 + in: query + name: page_size + type: integer + x-go-name: PageSize + - description: the offset of db services to be returned, default is 0 + example: "0" + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: fuzzy search keywords for db service name + example: '"mysql"' + in: query + name: keywords + type: string + x-go-name: Keywords + responses: "200": - description: GetFeishuConfigurationReply + description: List creatable db services for masking task successfully schema: - $ref: '#/definitions/GetFeishuConfigurationReply' + $ref: '#/definitions/ListCreatableDBServicesForMaskingTaskReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: List db services that can create sensitive data discovery task. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/tables/{table_id}/column-masking-details: + get: + operationId: GetTableColumnMaskingDetails + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: table id from masking overview tree + example: 1 + format: int64 + in: path + name: table_id + required: true + type: integer + x-go-name: TableID + - description: fuzzy search keyword for column name + example: '"phone"' + in: query + name: keywords + type: string + x-go-name: Keywords + responses: + "200": + description: Get table column masking details successfully + schema: + $ref: '#/definitions/GetTableColumnMaskingDetailsReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Get table column masking details. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/templates: + get: + operationId: ListMaskingTemplates + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: the maximum count of masking templates to be returned, default is 20 + format: uint32 + in: query + name: page_size + type: integer + x-go-name: PageSize + - description: the offset of masking templates to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + responses: + "200": + description: List masking templates successfully + schema: + $ref: '#/definitions/ListMaskingTemplatesReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: List masking templates. + tags: + - Masking + post: + operationId: AddMaskingTemplate + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: masking template info + in: body + name: masking_template + required: true + schema: + $ref: '#/definitions/AddMaskingTemplateReq' + responses: + "200": + description: Add masking template successfully + schema: + $ref: '#/definitions/AddMaskingTemplateReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Add masking template. + tags: + - Masking + /v1/dms/projects/{project_uid}/masking/templates/{template_id}: + delete: + operationId: DeleteMaskingTemplate + parameters: + - description: project uid + example: '"project_uid"' + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: masking template id + example: 1 + format: int64 + in: path + name: template_id + required: true + type: integer + x-go-name: TemplateID + responses: + "200": + description: Delete masking template successfully + schema: + $ref: '#/definitions/DeleteMaskingTemplateReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Delete masking template. + tags: + - Masking + put: + operationId: UpdateMaskingTemplate + parameters: + - description: project uid + in: path + name: project_uid + required: true + type: string + - description: masking template id + in: path + name: template_id + required: true + type: integer + - description: masking template info + in: body + name: masking_template + required: true + schema: + $ref: '#/definitions/UpdateMaskingTemplateReq' + responses: + "200": + description: Update masking template successfully + schema: + $ref: '#/definitions/UpdateMaskingTemplateReply' + default: + description: Generic error response + schema: + $ref: '#/definitions/GenericResp' + summary: Update masking template. + tags: + - Masking + /v1/dms/projects/{project_uid}/member_groups: + get: + operationId: ListMemberGroups + parameters: + - description: the maximum count of member to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of members to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + Multiple of ["name"], default is ["name"] + name MemberGroupOrderByName + enum: + - name + in: query + name: order_by + type: string + x-go-enum-desc: name MemberGroupOrderByName + x-go-name: OrderBy + - description: filter the user group name + in: query + name: filter_by_name + type: string + x-go-name: FilterByName + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: ListMemberGroupsReply + schema: + $ref: '#/definitions/ListMemberGroupsReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: get feishu configuration. + summary: List member group, for front page. tags: - - dms - patch: - operationId: UpdateFeishuConfiguration + - MemberGroup + post: + operationId: AddMemberGroup parameters: - - description: update feishu configuration + - description: project id + in: path + name: project_uid + required: true + type: string + - description: Add new member group in: body - name: update_feishu_configuration - schema: {} - x-go-name: UpdateFeishuConfiguration + name: member_group + required: true + schema: + $ref: '#/definitions/AddMemberGroupReq' + responses: + "200": + description: AddMemberGroupReply + schema: + $ref: '#/definitions/AddMemberGroupReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add member group. + tags: + - MemberGroup + /v1/dms/projects/{project_uid}/member_groups/{member_group_uid}: + delete: + operationId: DeleteMemberGroup + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: member group id + in: path + name: member_group_uid + required: true + type: string + x-go-name: MemberGroupUid responses: "200": description: GenericResp @@ -126,53 +11212,181 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: update feishu configuration. + summary: delete member group, for front page. tags: - - dms - /v1/dms/configurations/feishu/test: - post: - operationId: TestFeishuConfiguration + - MemberGroup + get: + operationId: GetMemberGroup parameters: - - description: test feishu configuration + - description: Member group id + in: path + name: member_group_uid + required: true + type: string + x-go-name: MemberGroupUid + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: GetMemberGroupReply + schema: + $ref: '#/definitions/GetMemberGroupReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get member group, for front page. + tags: + - MemberGroup + put: + operationId: UpdateMemberGroup + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: Member group id + in: path + name: member_group_uid + required: true + type: string + - description: Update a member group in: body - name: test_feishu_configuration - schema: {} - x-go-name: TestFeishuConfiguration + name: member_group + required: true + schema: + $ref: '#/definitions/UpdateMemberGroupReq' responses: "200": - description: TestFeishuConfigurationReply + description: GenericResp schema: - $ref: '#/definitions/TestFeishuConfigurationReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: test feishu configuration. + summary: update member group, for front page. tags: - - dms - /v1/dms/configurations/ldap: + - MemberGroup + /v1/dms/projects/{project_uid}/member_groups/tips: get: - operationId: GetLDAPConfiguration + operationId: ListMemberGroupTips + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: ListMemberGroupTipsReply + schema: + $ref: '#/definitions/ListMemberGroupTipsReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List member group tips. + tags: + - MemberGroup + /v1/dms/projects/{project_uid}/members: + get: + operationId: ListMembers + parameters: + - description: the maximum count of member to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of members to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + Multiple of ["name"], default is ["name"] + user_uid MemberOrderByUserUid + enum: + - user_uid + in: query + name: order_by + type: string + x-go-enum-desc: user_uid MemberOrderByUserUid + x-go-name: OrderBy + - description: filter the member user uid + in: query + name: filter_by_user_uid + type: string + x-go-name: FilterByUserUid + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + responses: + "200": + description: ListMemberReply + schema: + $ref: '#/definitions/ListMemberReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: List member, for front page. + tags: + - Member + post: + operationId: AddMember + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: Add new member + in: body + name: member + required: true + schema: + $ref: '#/definitions/AddMemberReq' responses: "200": - description: GetLDAPConfigurationResDataReply + description: AddMemberReply schema: - $ref: '#/definitions/GetLDAPConfigurationResDataReply' + $ref: '#/definitions/AddMemberReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Get ldap configuration. + summary: Add member. tags: - - dms - patch: - operationId: UpdateLDAPConfiguration + - Member + /v1/dms/projects/{project_uid}/members/{member_uid}: + delete: + operationId: DelMember parameters: - - description: update ldap configuration - in: body - name: ldap - schema: {} - x-go-name: LDAPConfiguration + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: member uid + in: path + name: member_uid + required: true + type: string + x-go-name: MemberUid responses: "200": description: GenericResp @@ -182,67 +11396,107 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Update ldap configuration. + summary: Delete a member. tags: - - dms - /v1/dms/configurations/oauth2: - get: - operationId: GetOauth2Configuration + - Member + put: + operationId: UpdateMember + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + - description: Member uid + in: path + name: member_uid + required: true + type: string + - description: Update a member + in: body + name: member + required: true + schema: + $ref: '#/definitions/UpdateMemberReq' responses: "200": - description: GetOauth2ConfigurationResDataReply + description: GenericResp schema: - $ref: '#/definitions/GetOauth2ConfigurationResDataReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Get Oauth2 configuration. + summary: Update a member. tags: - - dms - patch: - operationId: UpdateOauth2Configuration + - Member + /v1/dms/projects/{project_uid}/members/internal: + get: + operationId: ListMembersForInternal parameters: - - description: update oauth2 configuration - in: body - name: oauth2 - schema: {} - x-go-name: Oauth2Configuration + - description: the maximum count of member to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of members to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid responses: "200": - description: GenericResp + description: ListMembersForInternalReply schema: - $ref: '#/definitions/GenericResp' + $ref: '#/definitions/ListMembersForInternalReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Update Oauth2 configuration.. + summary: List members, for internal backend service. tags: - - dms - /v1/dms/configurations/smtp: + - Member + /v1/dms/projects/{project_uid}/members/tips: get: - operationId: GetSMTPConfiguration + operationId: ListMemberTips + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid responses: "200": - description: GetSMTPConfigurationReply + description: ListMemberTipsReply schema: - $ref: '#/definitions/GetSMTPConfigurationReply' + $ref: '#/definitions/ListMemberTipsReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: get smtp configuration. + summary: List member tips. tags: - - dms - patch: - operationId: UpdateSMTPConfiguration + - Member + /v1/dms/projects/{project_uid}/unarchive: + put: + operationId: UnarchiveProject parameters: - - description: update smtp configuration - in: body - name: smtp_configuration - schema: {} - x-go-name: UpdateSMTPConfiguration + - description: Project uid + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid responses: "200": description: GenericResp @@ -252,68 +11506,96 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Get smtp configuration. + summary: Unarchive a project. tags: - - dms - /v1/dms/configurations/smtp/test: - post: - operationId: TestSMTPConfiguration + - Project + /v1/dms/projects/business_tags: + get: + operationId: ListBusinessTags parameters: - - description: test smtp configuration - in: body - name: test_smtp_configuration - schema: {} - x-go-name: TestSMTPConfiguration + - format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword responses: "200": - description: TestSMTPConfigurationReply + description: ListBusinessTagsReply schema: - $ref: '#/definitions/TestSMTPConfigurationReply' + $ref: '#/definitions/ListBusinessTagsReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: test smtp configuration. + summary: List business tags. tags: - - dms - /v1/dms/configurations/sql_query: - get: - operationId: GetSQLQueryConfiguration + - Project + post: + operationId: CreateBusinessTag + parameters: + - description: business tag to be created + in: body + name: business_tag + required: true + schema: + $ref: '#/definitions/CreateBusinessTagReq' responses: "200": - description: GetSQLQueryConfigurationReply + description: GenericResp schema: - $ref: '#/definitions/GetSQLQueryConfigurationReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: get sql_query configuration. + summary: Create a new business tag. tags: - - cloudbeaver - /v1/dms/configurations/webhook: - get: - operationId: GetWebHookConfiguration + - Project + /v1/dms/projects/business_tags/{business_tag_uid}: + delete: + operationId: DeleteBusinessTag + parameters: + - in: path + name: business_tag_uid + required: true + type: string + x-go-name: BusinessTagUID responses: "200": - description: GetWebHookConfigurationReply + description: GenericResp schema: - $ref: '#/definitions/GetWebHookConfigurationReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: get webhook configuration. + summary: Delete an existing business tag. tags: - - dms - patch: - operationId: UpdateWebHookConfiguration + - Project + put: + operationId: UpdateBusinessTag parameters: - - description: test webhook configuration + - description: business tag id + in: path + name: business_tag_uid + required: true + type: string + - description: the business tag to be updated in: body - name: webhook_config - schema: {} - x-go-name: UpdateWebHookConfiguration + name: business_tag + required: true + schema: + $ref: '#/definitions/UpdateBusinessTagReq' responses: "200": description: GenericResp @@ -323,175 +11605,234 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: update webhook configuration. + summary: Update an existing business tag. tags: - - dms - /v1/dms/configurations/webhook/test: + - Project + /v1/dms/projects/check_db_services_privileges: post: - operationId: TestWebHookConfiguration + operationId: CheckDBServicesPrivileges + parameters: + - description: check db_services have enough privileges + in: body + name: db_services + schema: + $ref: '#/definitions/CheckDBServicesPrivilegesReq' responses: "200": - description: TestWebHookConfigurationReply + description: CheckDBServicesPrivilegesReply schema: - $ref: '#/definitions/TestWebHookConfigurationReply' + $ref: '#/definitions/CheckDBServicesPrivilegesReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: test webhook configuration. + summary: check if the db_services hava enough privileges. tags: - - dms - /v1/dms/configurations/wechat: + - Project + /v1/dms/projects/data_export_workflows: get: - operationId: GetWeChatConfiguration + operationId: ListAllDataExportWorkflows + parameters: + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: the maximum count of member to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of members to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + filter the status + wait_for_approve DataExportWorkflowStatusWaitForApprove + wait_for_export DataExportWorkflowStatusWaitForExport + exporting DataExportWorkflowStatusWaitForExporting + rejected DataExportWorkflowStatusRejected + cancel DataExportWorkflowStatusCancel + failed DataExportWorkflowStatusFailed + finish DataExportWorkflowStatusFinish + enum: + - wait_for_approve + - wait_for_export + - exporting + - rejected + - cancel + - failed + - finish + in: query + name: filter_by_status + type: string + x-go-enum-desc: |- + wait_for_approve DataExportWorkflowStatusWaitForApprove + wait_for_export DataExportWorkflowStatusWaitForExport + exporting DataExportWorkflowStatusWaitForExporting + rejected DataExportWorkflowStatusRejected + cancel DataExportWorkflowStatusCancel + failed DataExportWorkflowStatusFailed + finish DataExportWorkflowStatusFinish + x-go-name: FilterByStatus + - description: filter create user id + in: query + name: filter_by_create_user_uid + type: string + x-go-name: FilterByCreateUserUid + - description: filter current assignee user id + in: query + name: filter_current_step_assignee_user_uid + type: string + x-go-name: FilterCurrentStepAssigneeUserUid + - description: filter db_service id + in: query + name: filter_by_db_service_uid + type: string + x-go-name: FilterByDBServiceUid + - description: filter create time from + in: query + name: filter_create_time_from + type: string + x-go-name: FilterCreateTimeFrom + - description: filter create time end + in: query + name: filter_create_time_to + type: string + x-go-name: FilterCreateTimeTo + - description: filter fuzzy key word for id/name + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword responses: "200": - description: GetWeChatConfigurationReply + description: ListDataExportWorkflowsReply schema: - $ref: '#/definitions/GetWeChatConfigurationReply' + $ref: '#/definitions/ListDataExportWorkflowsReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: get wechat configuration. + summary: List all data_export workflow. tags: - - dms - patch: - operationId: UpdateWeChatConfiguration + - DataExportWorkflows + /v1/dms/projects/db_services_connection: + post: + operationId: DBServicesConnection parameters: - - description: update wechat configuration + - description: check db_service is connectable in: body - name: update_wechat_configuration - schema: {} - x-go-name: UpdateWeChatConfiguration + name: db_services + schema: + $ref: '#/definitions/DBServiceConnectionReq' responses: "200": - description: GenericResp + description: DBServicesConnectionReply schema: - $ref: '#/definitions/GenericResp' + $ref: '#/definitions/DBServicesConnectionReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: update wechat configuration. + summary: DBServices Connection. tags: - - dms - /v1/dms/configurations/wechat/test: + - Project + /v1/dms/projects/db_services_connections: post: - operationId: TestWeChatConfiguration + operationId: CheckGlobalDBServicesConnections parameters: - - description: test wechat configuration + - description: check db_services is connectable in: body - name: test_wechat_configuration - schema: {} - x-go-name: TestWeChatConfiguration + name: db_services + schema: + $ref: '#/definitions/DBServicesConnectionReq' responses: "200": - description: TestWeChatConfigurationReply + description: DBServicesConnectionReqReply schema: - $ref: '#/definitions/TestWeChatConfigurationReply' + $ref: '#/definitions/DBServicesConnectionReqReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: test wechat configuration. + summary: check if the global db_services is connectable. tags: - - dms - /v1/dms/db_services: + - Project + /v1/dms/projects/export: get: - operationId: ListDBServices + operationId: ExportProjects parameters: - - description: the maximum count of db service to be returned - format: uint32 - in: query - name: page_size - required: true - type: integer - x-go-name: PageSize - - description: the offset of users to be returned, default is 0 - format: uint32 - in: query - name: page_index - type: integer - x-go-name: PageIndex - - description: Multiple of ["name"], default is ["name"] + - description: |- + Multiple of ["name"], default is ["name"] + name ProjectOrderByName + enum: + - name in: query name: order_by - x-go-name: OrderBy - - description: the db service business name - in: query - name: filter_by_business type: string - x-go-name: FilterByBusiness - - description: the db service host + x-go-enum-desc: name ProjectOrderByName + x-go-name: OrderBy + - description: filter the Project name in: query - name: filter_by_host + name: filter_by_name type: string - x-go-name: FilterByHost - - description: the db service uid + x-go-name: FilterByName + - description: filter the Project UID in: query name: filter_by_uid type: string x-go-name: FilterByUID - - description: the db service port - in: query - name: filter_by_port - type: string - x-go-name: FilterByPort - - description: the db service db type - in: query - name: filter_by_db_type - type: string - x-go-name: FilterByDBType - - description: |- - filter by db service namespace uid - only the sys user can use an empty namespace value, which means lookup from all namespaces - in: query - name: filter_by_namespace_uid - type: string - x-go-name: FilterByNamespaceUid responses: "200": - description: ListDBServiceReply - schema: - $ref: '#/definitions/ListDBServiceReply' + $ref: '#/responses/ExportProjectsReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List db service. + summary: Export projects file. tags: - - dms + - Project + /v1/dms/projects/import: post: - operationId: AddDBService + deprecated: true + operationId: ImportProjects parameters: - - description: Add new db service + - description: import projects in: body - name: db_service - schema: {} - x-go-name: DBService + name: projects + required: true + schema: + $ref: '#/definitions/ImportProjectsReq' responses: "200": - description: AddDBServiceReply + description: GenericResp schema: - $ref: '#/definitions/AddDBServiceReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Add DB Service. + summary: Import projects. tags: - - dms - /v1/dms/db_services/{db_service_uid}: - delete: - operationId: DelDBService + - Project + /v1/dms/projects/import_db_services: + post: + deprecated: true + operationId: ImportDBServicesOfProjects parameters: - - description: db service uid - in: path - name: db_service_uid + - description: new db services + in: body + name: db_services required: true - type: string - x-go-name: DBServiceUid + schema: + $ref: '#/definitions/ImportDBServicesOfProjectsReq' responses: "200": description: GenericResp @@ -501,276 +11842,369 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Delete a DB Service. + summary: Import DBServices. tags: - - dms - put: - operationId: UpdateDBService + - Project + /v1/dms/projects/import_db_services_check: + post: + consumes: + - multipart/form-data + deprecated: true + operationId: ImportDBServicesOfProjectsCheck parameters: - - description: db_service_uid - in: path - name: db_service_uid - required: true - type: string - x-go-name: DBServiceUid - - description: Update a DB service - in: body - name: db_service - schema: {} - x-go-name: DBService + - description: DBServices file. + in: formData + name: db_services_file + type: file + x-go-name: DBServicesFile + produces: + - application/json + - text/csv + responses: + "200": + $ref: '#/responses/ImportDBServicesCheckCsvReply' + default: + description: ImportDBServicesCheckReply + schema: + $ref: '#/definitions/ImportDBServicesCheckReply' + summary: Import DBServices. + tags: + - Project + /v1/dms/projects/import_db_services_template: + get: + operationId: GetImportDBServicesTemplate responses: "200": + $ref: '#/responses/GetImportDBServicesTemplateReply' + default: description: GenericResp schema: $ref: '#/definitions/GenericResp' + summary: Get import DBServices template. + tags: + - Project + /v1/dms/projects/import_template: + get: + operationId: GetImportProjectsTemplate + responses: + "200": + $ref: '#/responses/GetImportProjectsTemplateReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: update a DB Service. + summary: Get import projects template. tags: - - dms - /v1/dms/db_services/connect: + - Project + /v1/dms/projects/preview_import: post: - operationId: CheckDBServiceIsConnectable + consumes: + - multipart/form-data + deprecated: true + operationId: PreviewImportProjects parameters: - - description: check db_service is connectable - in: body - name: db_service - schema: {} - x-go-name: DBService + - description: projects file. + in: formData + name: projects_file + type: file + x-go-name: ProjectsFile responses: "200": - description: CheckDBServiceIsConnectableReply + description: PreviewImportProjectsReply schema: - $ref: '#/definitions/CheckDBServiceIsConnectableReply' + $ref: '#/definitions/PreviewImportProjectsReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: check if the db_service is connectable. + summary: Preview import projects. tags: - - dms - /v1/dms/members: + - Project + /v1/dms/projects/tips: get: - operationId: ListMembers + deprecated: true + operationId: GetProjectTips parameters: - - description: the maximum count of member to be returned - format: uint32 - in: query - name: page_size - required: true - type: integer - x-go-name: PageSize - - description: the offset of members to be returned, default is 0 - format: uint32 - in: query - name: page_index - type: integer - x-go-name: PageIndex - - description: Multiple of ["name"], default is ["name"] + - description: Project uid in: query - name: order_by - x-go-name: OrderBy - - description: filter the member user uid - in: query - name: filter_by_user_uid - type: string - x-go-name: FilterByUserUid - - description: the member namespace uid - in: query - name: namespace_uid - required: true + name: project_uid type: string - x-go-name: NamespaceUid + x-go-name: ProjectUid responses: "200": - description: ListMemberReply + description: GetProjectTipsReply schema: - $ref: '#/definitions/ListMemberReply' + $ref: '#/definitions/GetProjectTipsReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List member, for front page. + summary: Get project tips. tags: - - dms + - Project + /v1/dms/proxys: post: - operationId: AddMember + operationId: RegisterDMSProxyTarget parameters: - - description: Add new member + - description: register dms proxy in: body - name: member - schema: {} - x-go-name: Member + name: dms_proxy_target + required: true + schema: + $ref: '#/definitions/RegisterDMSProxyTargetReq' responses: "200": - description: AddMemberReply + description: GenericResp schema: - $ref: '#/definitions/AddMemberReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Add member. + summary: Register dms proxy target. tags: - - dms - /v1/dms/members/{member_uid}: - delete: - operationId: DelMember + - DMSProxy + /v1/dms/resource_overview/download: + get: + operationId: DownloadResourceOverviewList parameters: - - description: member uid - in: path - name: member_uid - required: true + - description: 根据数据源类型筛选 + in: query + name: filter_by_db_type type: string - x-go-name: MemberUid + x-go-name: FilterByDBType + - description: 根据所属业务标签筛选 + in: query + name: filter_by_business_tag_uid + type: string + x-go-name: FilterByBusinessTagUID + - description: 根据环境属性标签筛选 + in: query + name: filter_by_environment_tag_uid + type: string + x-go-name: FilterByEnvironmentTagUID + - description: 根据所属项目筛选 + in: query + name: filter_by_project_uid + type: string + x-go-name: FilterByProjectUID + - description: 根据项目或数据源名称模糊搜索 + in: query + name: fuzzy_search_resource_name + type: string + x-go-name: FuzzySearchResourceName responses: "200": + $ref: '#/responses/DownloadResourceOverviewListRes' + default: description: GenericResp schema: $ref: '#/definitions/GenericResp' + summary: download resource overview list csv file. + tags: + - ResourceOverview + /v1/dms/resource_overview/resource_list: + get: + operationId: GetResourceOverviewResourceListV1 + parameters: + - description: 根据数据源类型筛选 + in: query + name: filter_by_db_type + type: string + x-go-name: FilterByDBType + - description: 根据所属业务标签筛选 + in: query + name: filter_by_business_tag_uid + type: string + x-go-name: FilterByBusinessTagUID + - description: 根据环境属性标签筛选 + in: query + name: filter_by_environment_tag_uid + type: string + x-go-name: FilterByEnvironmentTagUID + - description: 根据所属项目筛选 + in: query + name: filter_by_project_uid + type: string + x-go-name: FilterByProjectUID + - description: 根据项目或数据源名称模糊搜索 + in: query + name: fuzzy_search_resource_name + type: string + x-go-name: FuzzySearchResourceName + - format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - format: uint32 + in: query + name: page_size + type: integer + x-go-name: PageSize + responses: + "200": + description: resource overview resource list response body + schema: + $ref: '#/definitions/ResourceOverviewResourceListResV1' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Delete a member. + summary: Get resource overview resource list. tags: - - dms - put: - operationId: UpdateMember - parameters: - - description: Member uid - in: path - name: member_uid - required: true - type: string - x-go-name: MemberUid - - description: Update a member - in: body - name: member - schema: {} - x-go-name: Member + - ResourceOverview + /v1/dms/resource_overview/resource_type_distribution: + get: + operationId: GetResourceOverviewResourceTypeDistributionV1 responses: "200": + description: resource overview resource type distribution response body + schema: + $ref: '#/definitions/ResourceOverviewResourceTypeDistributionResV1' + default: description: GenericResp schema: $ref: '#/definitions/GenericResp' + summary: Get resource overview resource type distribution. + tags: + - ResourceOverview + /v1/dms/resource_overview/statistics: + get: + operationId: GetResourceOverviewStatisticsV1 + responses: + "200": + description: resource overview statistics response body + schema: + $ref: '#/definitions/ResourceOverviewStatisticsResV1' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Update a member. + summary: Get resource overview statistics. tags: - - dms - /v1/dms/members/internal: + - ResourceOverview + /v1/dms/resource_overview/topology: get: - operationId: ListMembersForInternal + operationId: GetResourceOverviewTopologyV1 parameters: - - description: the maximum count of member to be returned - format: uint32 + - description: 根据数据源类型筛选 in: query - name: page_size - required: true - type: integer - x-go-name: PageSize - - description: the offset of members to be returned, default is 0 - format: uint32 + name: filter_by_db_type + type: string + x-go-name: FilterByDBType + - description: 根据所属业务标签筛选 in: query - name: page_index - type: integer - x-go-name: PageIndex - - description: the member namespace uid + name: filter_by_business_tag_uid + type: string + x-go-name: FilterByBusinessTagUID + - description: 根据环境属性标签筛选 + in: query + name: filter_by_environment_tag_uid + type: string + x-go-name: FilterByEnvironmentTagUID + - description: 根据所属项目筛选 + in: query + name: filter_by_project_uid + type: string + x-go-name: FilterByProjectUID + - description: 根据项目或数据源名称模糊搜索 in: query - name: namespace_uid + name: fuzzy_search_resource_name type: string - x-go-name: NamespaceUid + x-go-name: FuzzySearchResourceName responses: "200": - description: ListMembersForInternalReply + description: resource overview topology response body schema: - $ref: '#/definitions/ListMembersForInternalReply' + $ref: '#/definitions/ResourceOverviewTopologyResV1' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List members, for internal backend service. + summary: Get resource overview topology. tags: - - dms - /v1/dms/namespaces: + - ResourceOverview + /v1/dms/roles: get: - operationId: ListNamespaces + operationId: ListRoles parameters: - - description: the maximum count of namespace to be returned + - description: the maximum count of role to be returned format: uint32 in: query name: page_size required: true type: integer x-go-name: PageSize - - description: the offset of namespaces to be returned, default is 0 + - description: the offset of roles to be returned, default is 0 format: uint32 in: query name: page_index type: integer x-go-name: PageIndex - - description: Multiple of ["name"], default is ["name"] + - description: |- + Multiple of ["name"], default is ["name"] + name RoleOrderByName + enum: + - name in: query name: order_by + type: string + x-go-enum-desc: name RoleOrderByName x-go-name: OrderBy - - description: filter the namespace name + - description: filter the role name in: query name: filter_by_name type: string x-go-name: FilterByName - - description: filter the namespace UID + - description: the db service fuzzy keyword,include op_permission in: query - name: filter_by_uid + name: fuzzy_keyword type: string - x-go-name: FilterByUID + x-go-name: FuzzyKeyword responses: "200": - description: ListNamespaceReply + description: ListRoleReply schema: - $ref: '#/definitions/ListNamespaceReply' + $ref: '#/definitions/ListRoleReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List namespaces. + summary: List roles. tags: - - dms + - Role post: - operationId: AddNamespace + operationId: AddRole parameters: - - description: Add new Namespace + - description: Add new role in: body - name: namespace - schema: {} - x-go-name: Namespace + name: role + required: true + schema: + $ref: '#/definitions/AddRoleReq' responses: "200": - description: AddNamespaceReply + description: AddRoleReply schema: - $ref: '#/definitions/AddNamespaceReply' + $ref: '#/definitions/AddRoleReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Add namespaces. + summary: Add role. tags: - - dms - /v1/dms/namespaces/{namespace_uid}: + - Role + /v1/dms/roles/{role_uid}: delete: - description: Delete a Namespace - operationId: DelNamespace + operationId: DelRole parameters: - - description: namespace uid + - description: role uid in: path - name: namespace_uid + name: role_uid required: true type: string - x-go-name: NamespaceUid + x-go-name: RoleUid responses: "200": description: GenericResp @@ -780,44 +12214,23 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' + summary: Delete a role. tags: - - dms + - Role put: - operationId: UpdateNamespace + operationId: UpdateRole parameters: - - description: Namespace uid + - description: Role uid in: path - name: namespace_uid + name: role_uid required: true type: string - x-go-name: NamespaceUid - - description: Update a namespace + - description: Update a role in: body - name: namespace - schema: {} - x-go-name: Namespace - responses: - "200": - description: GenericResp - schema: - $ref: '#/definitions/GenericResp' - default: - description: GenericResp - schema: - $ref: '#/definitions/GenericResp' - summary: update a Namespace. - tags: - - dms - /v1/dms/namespaces/{namespace_uid}/archive: - put: - operationId: ArchiveNamespace - parameters: - - description: Namespace uid - in: path - name: namespace_uid + name: role required: true - type: string - x-go-name: NamespaceUid + schema: + $ref: '#/definitions/UpdateRoleReq' responses: "200": description: GenericResp @@ -827,141 +12240,155 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Archive a Namespace. + summary: Update a role. tags: - - dms - /v1/dms/namespaces/{namespace_uid}/unarchive: - put: - operationId: UnarchiveNamespace - parameters: - - description: Namespace uid - in: path - name: namespace_uid - required: true - type: string - x-go-name: NamespaceUid + - Role + /v1/dms/sessions: + delete: + operationId: DelSession responses: "200": - description: GenericResp + description: DelSessionReply schema: - $ref: '#/definitions/GenericResp' + $ref: '#/definitions/DelSessionReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Unarchive a Namespace. + summary: del a session. tags: - - dms - /v1/dms/notifications: + - Session post: - operationId: Notification + operationId: AddSession parameters: - - description: notification + - description: Add a new session in: body - name: notification - schema: {} - x-go-name: Notification + name: session + required: true + schema: + $ref: '#/definitions/AddSessionReq' responses: "200": - description: NotificationReply + description: AddSessionReply schema: - $ref: '#/definitions/NotificationReply' + $ref: '#/definitions/AddSessionReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: notify message. + summary: Add a session. tags: - - dms - /v1/dms/oauth2/tips: - get: - operationId: GetOauth2Tips + - Session + /v1/dms/sessions/refresh: + post: + operationId: RefreshSession responses: "200": - description: GetOauth2TipsReply + description: RefreshSession reply schema: - $ref: '#/definitions/GetOauth2TipsReply' + $ref: '#/definitions/AddSessionReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Get Oauth2 Tips. + summary: refresh a session. tags: - - dms - /v1/dms/oauth2/user/bind: - post: - operationId: BindOauth2User + - Session + /v1/dms/sessions/user: + get: + operationId: GetUserBySession parameters: - in: query - name: user_name - type: string - x-go-name: UserName - - in: query - name: pwd - type: string - x-go-name: Pwd - - in: query - name: oauth2_token + name: user_uid type: string - x-go-name: Oauth2Token + x-go-name: UserUid responses: "200": - description: BindOauth2UserReply + description: GetUserBySessionReply schema: - $ref: '#/definitions/BindOauth2UserReply' + $ref: '#/definitions/GetUserBySessionReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Bind Oauth2 User. + summary: Get current user. tags: - - dms - /v1/dms/op_permissions: + - Session + /v1/dms/user_groups: get: - operationId: ListOpPermissions + operationId: ListUserGroups parameters: - - description: the maximum count of op permission to be returned + - description: the maximum count of user to be returned format: uint32 in: query name: page_size required: true type: integer x-go-name: PageSize - - description: the offset of op permissions to be returned, default is 0 + - description: the offset of user groups to be returned, default is 0 format: uint32 in: query name: page_index type: integer x-go-name: PageIndex - - description: Order by the specified field + - description: |- + Multiple of ["name"], default is ["name"] + name UserGroupOrderByName + enum: + - name in: query name: order_by + type: string + x-go-enum-desc: name UserGroupOrderByName x-go-name: OrderBy - - description: filter by op permission target + - description: filter the user group name in: query - name: filter_by_target - x-go-name: FilterByTarget + name: filter_by_name + type: string + x-go-name: FilterByName responses: "200": - description: ListOpPermissionReply + description: ListUserGroupReply schema: - $ref: '#/definitions/ListOpPermissionReply' + $ref: '#/definitions/ListUserGroupReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List op permission. + summary: List user groups. tags: - - dms - /v1/dms/plugin: + - UserGroup post: - operationId: RegisterDMSPlugin + operationId: AddUserGroup parameters: - - description: Register dms plugin + - description: Add new user group in: body - name: plugin - schema: {} - x-go-name: Plugin + name: user_group + required: true + schema: + $ref: '#/definitions/AddUserGroupReq' + responses: + "200": + description: AddUserGroupReply + schema: + $ref: '#/definitions/AddUserGroupReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Add user group. + tags: + - UserGroup + /v1/dms/user_groups/{user_group_uid}: + delete: + operationId: DelUserGroup + parameters: + - description: user group uid + in: path + name: user_group_uid + required: true + type: string + x-go-name: UserGroupUid responses: "200": description: GenericResp @@ -971,18 +12398,23 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Register dms plugin. + summary: Delete a user group. tags: - - dms - /v1/dms/proxy: - post: - operationId: RegisterDMSProxyTarget + - UserGroup + put: + operationId: UpdateUserGroup parameters: - - description: register dms proxy + - description: UserGroup uid + in: path + name: user_group_uid + required: true + type: string + - description: Update a user group in: body - name: dms_proxy_target - schema: {} - x-go-name: DMSProxyTarget + name: user_group + required: true + schema: + $ref: '#/definitions/UpdateUserGroupReq' responses: "200": description: GenericResp @@ -992,77 +12424,178 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Register dms proxy target. + summary: Update a user group. tags: - - dms - /v1/dms/roles: + - UserGroup + /v1/dms/users: get: - operationId: ListRoles + operationId: ListUsers parameters: - - description: the maximum count of role to be returned + - description: the maximum count of user to be returned format: uint32 in: query name: page_size required: true type: integer x-go-name: PageSize - - description: the offset of roles to be returned, default is 0 + - description: the offset of users to be returned, default is 0 format: uint32 in: query name: page_index type: integer x-go-name: PageIndex - - description: Multiple of ["name"], default is ["name"] + - description: |- + Multiple of ["name"], default is ["name"] + name UserOrderByName + enum: + - name in: query name: order_by + type: string + x-go-enum-desc: name UserOrderByName x-go-name: OrderBy - - description: filter the role name + - description: filter the user name in: query name: filter_by_name type: string x-go-name: FilterByName + - description: filter the user uids + in: query + name: filter_by_uids + type: string + x-go-name: FilterByUids + - description: filter deleted user to be return ,default is false + in: query + name: filter_del_user + type: boolean + x-go-name: FilterDeletedUser + - description: fuzzy keyword + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword + - description: filter the user email + in: query + name: filter_by_email + type: string + x-go-name: FilterByEmail + - description: filter the user phone + in: query + name: filter_by_phone + type: string + x-go-name: FilterByPhone + - description: |- + filter the user stat (0: normal, 1: disabled) + Normal UserStatFilterNormal + Disabled UserStatFilterDisabled + enum: + - Normal + - Disabled + in: query + name: filter_by_stat + type: string + x-go-enum-desc: |- + Normal UserStatFilterNormal + Disabled UserStatFilterDisabled + x-go-name: FilterByStat + - description: |- + filter the user authentication type (ldap, dms, oauth2) + ldap UserAuthenticationTypeLDAP + dms UserAuthenticationTypeDMS + oauth2 UserAuthenticationTypeOAUTH2 + unknown UserAuthenticationTypeUnknown + enum: + - ldap + - dms + - oauth2 + - unknown + in: query + name: filter_by_authentication_type + type: string + x-go-enum-desc: |- + ldap UserAuthenticationTypeLDAP + dms UserAuthenticationTypeDMS + oauth2 UserAuthenticationTypeOAUTH2 + unknown UserAuthenticationTypeUnknown + x-go-name: FilterByAuthenticationType + - description: |- + filter the user system (WORKBENCH, MANAGEMENT) + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + enum: + - WORKBENCH + - MANAGEMENT + in: query + name: filter_by_system + type: string + x-go-enum-desc: |- + WORKBENCH UserSystemWorkbench + MANAGEMENT UserSystemManagement + x-go-name: FilterBySystem responses: "200": - description: ListRoleReply + description: ListUserReply schema: - $ref: '#/definitions/ListRoleReply' + $ref: '#/definitions/ListUserReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List roles. + summary: List users. tags: - - dms + - User post: - operationId: AddRole + operationId: AddUser parameters: - - description: Add new role + - description: Add new user in: body - name: role - schema: {} - x-go-name: Role + name: user + required: true + schema: + $ref: '#/definitions/AddUserReq' responses: "200": - description: AddRoleReply + description: AddUserReply schema: - $ref: '#/definitions/AddRoleReply' + $ref: '#/definitions/AddUserReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Add role. + summary: Add user. tags: - - dms - /v1/dms/roles/{role_uid}: + - User + put: + operationId: UpdateCurrentUser + parameters: + - description: Update current user + in: body + name: current_user + required: true + schema: + $ref: '#/definitions/UpdateCurrentUserReq' + responses: + "200": + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Update current user. + tags: + - User + /v1/dms/users/{user_uid}: delete: - operationId: DelRole + operationId: DelUser parameters: - - description: role uid + - description: user uid in: path - name: role_uid + name: user_uid required: true type: string - x-go-name: RoleUid + x-go-name: UserUid responses: "200": description: GenericResp @@ -1072,23 +12605,43 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Delete a role. + summary: Delete a user. + tags: + - User + get: + operationId: GetUser + parameters: + - description: user uid + in: path + name: user_uid + required: true + type: string + x-go-name: UserUid + responses: + "200": + description: GetUserReply + schema: + $ref: '#/definitions/GetUserReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get user info, This API is used by other component such as sqle&auth to get user info. tags: - - dms + - User put: - operationId: UpdateRole + operationId: UpdateUser parameters: - - description: Role uid + - description: User uid in: path - name: role_uid + name: user_uid required: true type: string - x-go-name: RoleUid - - description: Update a role + - description: Update a user in: body - name: role - schema: {} - x-go-name: Role + name: user + schema: + $ref: '#/definitions/UpdateUserReq' responses: "200": description: GenericResp @@ -1098,144 +12651,325 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Update a role. + summary: Update a user. tags: - - dms - /v1/dms/sessions: + - User + /v1/dms/users/{user_uid}/op_permission: + get: + operationId: GetUserOpPermission + parameters: + - description: user uid + in: path + name: user_uid + required: true + type: string + x-go-name: UserUid + - in: query + name: project_uid + type: string + x-go-name: ProjectUid + - description: user op permission info + in: body + name: user_op_permission + schema: + $ref: '#/definitions/UserOpPermission' + x-go-name: UserOpPermission + responses: + "200": + description: GetUserOpPermissionReply + schema: + $ref: '#/definitions/GetUserOpPermissionReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Get user op permission info, This API is used by other component such as sqle&auth to check user permissions. + tags: + - User + /v1/dms/users/gen_token: post: - operationId: AddSession + operationId: GenAccessToken + parameters: + - in: body + name: expiration_days + required: true + schema: + $ref: '#/definitions/GenAccessToken' + responses: + "200": + description: GenAccessTokenReply + schema: + $ref: '#/definitions/GenAccessTokenReply' + default: + description: GenericResp + schema: + $ref: '#/definitions/GenericResp' + summary: Gen user access token. + tags: + - User + /v1/dms/users/verify_user_login: + post: + operationId: VerifyUserLogin parameters: - description: Add a new session in: body name: session - schema: {} - x-go-name: Session + required: true + schema: + $ref: '#/definitions/AddSessionReq' responses: "200": - description: AddSessionReply + description: VerifyUserLoginReply schema: - $ref: '#/definitions/AddSessionReply' + $ref: '#/definitions/VerifyUserLoginReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Add a session. + summary: Verify user login. tags: - - dms - /v1/dms/sessions/user: - get: - operationId: GetUserBySession + - User + /v1/dms/webhooks: + post: + operationId: WebHookSendMessage parameters: - - in: query - name: user_uid - type: string - x-go-name: UserUid + - description: webhooks + in: body + name: webhook_message + required: true + schema: + $ref: '#/definitions/WebHookSendMessageReq' responses: "200": - description: GetUserBySessionReply + description: WebHookSendMessageReply schema: - $ref: '#/definitions/GetUserBySessionReply' + $ref: '#/definitions/WebHookSendMessageReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Get current user. + summary: webhook send message. tags: - - dms - /v1/dms/user_groups: + - Webhook + /v2/dms/db_services: get: - operationId: ListUserGroups + description: list global DBServices + operationId: ListGlobalDBServicesV2 parameters: - - description: the maximum count of user to be returned + - description: the maximum count of db service to be returned format: uint32 in: query name: page_size required: true type: integer x-go-name: PageSize - - description: the offset of user groups to be returned, default is 0 + - description: the offset of users to be returned, default is 0 format: uint32 in: query name: page_index type: integer x-go-name: PageIndex - - description: Multiple of ["name"], default is ["name"] + - description: |- + Multiple of ["name"], default is ["name"] + name DBServiceOrderByName + enum: + - name in: query name: order_by + type: string + x-go-enum-desc: name DBServiceOrderByName x-go-name: OrderBy - - description: filter the user group name + - description: the db service connection + enum: + - connect_success + - connect_failed + in: query + name: filter_last_connection_test_status + type: string + x-go-name: FilterLastConnectionTestStatus + - description: filter db services by environment tag + in: query + name: filter_by_environment_tag_uid + type: string + x-go-name: FilterByEnvironmentTagUID + - description: the db service host + in: query + name: filter_by_host + type: string + x-go-name: FilterByHost + - description: the db service uid + in: query + name: filter_by_uid + type: string + x-go-name: FilterByUID + - description: the db service name in: query name: filter_by_name type: string x-go-name: FilterByName + - description: the db service port + in: query + name: filter_by_port + type: string + x-go-name: FilterByPort + - description: the db service db type + in: query + name: filter_by_db_type + type: string + x-go-name: FilterByDBType + - description: the db service project id + in: query + name: filter_by_project_uid + type: string + x-go-name: FilterByProjectUid + - description: is masking + in: query + name: filter_by_is_enable_masking + type: boolean + x-go-name: FilterByIsEnableMasking + - description: the db service fuzzy keyword + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword responses: "200": - description: ListUserGroupReply + description: ListGlobalDBServicesReplyV2 schema: - $ref: '#/definitions/ListUserGroupReply' + $ref: '#/definitions/ListGlobalDBServicesReplyV2' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List user groups. tags: - - dms - post: - operationId: AddUserGroup + - DBService + /v2/dms/projects: + get: + operationId: ListProjectsV2 parameters: - - description: Add new user group - in: body - name: user_group - schema: {} - x-go-name: UserGroup + - description: the maximum count of Project to be returned + format: uint32 + in: query + name: page_size + required: true + type: integer + x-go-name: PageSize + - description: the offset of Projects to be returned, default is 0 + format: uint32 + in: query + name: page_index + type: integer + x-go-name: PageIndex + - description: |- + Multiple of ["name"], default is ["name"] + name ProjectOrderByName + enum: + - name + in: query + name: order_by + type: string + x-go-enum-desc: name ProjectOrderByName + x-go-name: OrderBy + - description: filter the Project name + in: query + name: filter_by_name + type: string + x-go-name: FilterByName + - description: filter the Project UID + in: query + name: filter_by_uid + type: string + x-go-name: FilterByUID + - description: filter project by project id list, using in condition + in: query + items: + type: string + name: filter_by_project_uids + type: array + x-go-name: FilterByProjectUids + - description: |- + filter project by project priority + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + enum: + - high + - medium + - low + - unknown + in: query + name: filter_by_project_priority + type: string + x-go-enum-desc: |- + high ProjectPriorityHigh + medium ProjectPriorityMedium + low ProjectPriorityLow + unknown ProjectPriorityUnknown + x-go-name: FilterByProjectPriority + - description: filter project by business tag + in: query + name: filter_by_business_tag + type: string + x-go-name: FilterByBusinessTag + - description: filter the Project By Project description + in: query + name: filter_by_desc + type: string + x-go-name: FilterByDesc + - description: fuzzy keyword + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword responses: "200": - description: AddUserGroupReply + description: ListProjectReplyV2 schema: - $ref: '#/definitions/AddUserGroupReply' + $ref: '#/definitions/ListProjectReplyV2' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Add user group. + summary: List projects. tags: - - dms - /v1/dms/user_groups/{user_group_uid}: - delete: - operationId: DelUserGroup + - Project + post: + operationId: AddProjectV2 parameters: - - description: user group uid - in: path - name: user_group_uid + - description: Add new Project + in: body + name: project required: true - type: string - x-go-name: UserGroupUid + schema: + $ref: '#/definitions/AddProjectReqV2' responses: "200": - description: GenericResp + description: AddProjectReplyV2 schema: - $ref: '#/definitions/GenericResp' + $ref: '#/definitions/AddProjectReplyV2' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Delete a user group. + summary: Add project. tags: - - dms + - Project + /v2/dms/projects/{project_uid}: put: - operationId: UpdateUserGroup + operationId: UpdateProjectV2 parameters: - - description: UserGroup uid + - description: project id in: path - name: user_group_uid + name: project_uid required: true type: string - x-go-name: UserGroupUid - - description: Update a user group + - description: Update a project in: body - name: user_group - schema: {} - x-go-name: UserGroup + name: project + required: true + schema: + $ref: '#/definitions/UpdateProjectReqV2' responses: "200": description: GenericResp @@ -1245,14 +12979,14 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Update a user group. + summary: update a project. tags: - - dms - /v1/dms/users: + - Project + /v2/dms/projects/{project_uid}/db_services: get: - operationId: ListUsers + operationId: ListDBServicesV2 parameters: - - description: the maximum count of user to be returned + - description: the maximum count of db service to be returned format: uint32 in: query name: page_size @@ -1265,67 +12999,134 @@ paths: name: page_index type: integer x-go-name: PageIndex - - description: Multiple of ["name"], default is ["name"] + - description: |- + Multiple of ["name"], default is ["name"] + name DBServiceOrderByName + enum: + - name in: query name: order_by + type: string + x-go-enum-desc: name DBServiceOrderByName x-go-name: OrderBy - - description: filter the user name + - description: the db service connection + enum: + - connect_success + - connect_failed + in: query + name: filter_last_connection_test_status + type: string + x-go-name: FilterLastConnectionTestStatus + - description: the db service host + in: query + name: filter_by_host + type: string + x-go-name: FilterByHost + - description: the db service uid + in: query + name: filter_by_uid + type: string + x-go-name: FilterByUID + - description: the db service name in: query name: filter_by_name type: string x-go-name: FilterByName - - description: filter the user uids + - description: the db service port in: query - name: filter_by_uids + name: filter_by_port type: string - x-go-name: FilterByUids - - description: filter deleted user to be return ,default is false + x-go-name: FilterByPort + - description: the db service db type in: query - name: filter_del_user + name: filter_by_db_type + type: string + x-go-name: FilterByDBType + - description: project id + in: path + name: project_uid + required: true + type: string + x-go-name: ProjectUid + - description: filter db services by db service id list using in condition + in: query + items: + type: string + name: filter_by_db_service_ids + type: array + x-go-name: FilterByDBServiceIds + - description: filter db services by environment tag + in: query + name: filter_by_environment_tag_uid + type: string + x-go-name: FilterByEnvironmentTagUID + - description: the db service fuzzy keyword,include host/port + in: query + name: fuzzy_keyword + type: string + x-go-name: FuzzyKeyword + - description: is masking + in: query + name: is_enable_masking type: boolean - x-go-name: FilterDeletedUser + x-go-name: IsEnableMasking responses: "200": - description: ListUserReply + description: ListDBServiceReplyV2 schema: - $ref: '#/definitions/ListUserReply' + $ref: '#/definitions/ListDBServiceReplyV2' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: List users. + summary: List db service. tags: - - dms + - DBService post: - operationId: AddUser + operationId: AddDBServiceV2 parameters: - - description: Add new user + - description: project id + in: path + name: project_uid + required: true + type: string + - description: Add new db service in: body - name: user - schema: {} - x-go-name: User + name: db_service + required: true + schema: + $ref: '#/definitions/AddDBServiceReqV2' responses: "200": - description: AddUserReply + description: AddDBServiceReply schema: - $ref: '#/definitions/AddUserReply' + $ref: '#/definitions/AddDBServiceReply' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Add user. + summary: Add DB Service. tags: - - dms - /v1/dms/users/{user_uid}: - delete: - operationId: DelUser + - DBService + /v2/dms/projects/{project_uid}/db_services/{db_service_uid}: + put: + operationId: UpdateDBServiceV2 parameters: - - description: user uid + - description: project id in: path - name: user_uid + name: project_uid required: true type: string - x-go-name: UserUid + - description: db_service_uid id + in: path + name: db_service_uid + required: true + type: string + - description: Update a DB service + in: body + name: db_service + schema: + $ref: '#/definitions/UpdateDBServiceReqV2' responses: "200": description: GenericResp @@ -1335,44 +13136,76 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Delete a user. + summary: update a DB Service. tags: - - dms - get: - operationId: GetUser + - DBService + /v2/dms/projects/{project_uid}/db_services/import: + post: + operationId: ImportDBServicesOfOneProjectV2 parameters: - - description: user uid + - description: project id in: path - name: user_uid + name: project_uid required: true type: string - x-go-name: UserUid + - description: new db services + in: body + name: db_services + required: true + schema: + $ref: '#/definitions/ImportDBServicesOfOneProjectReqV2' responses: "200": - description: GetUserReply + description: GenericResp schema: - $ref: '#/definitions/GetUserReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Get user info, This API is used by other component such as sqle&auth to get user info. + summary: Import DBServices. tags: - - dms - put: - operationId: UpdateUser + - DBService + /v2/dms/projects/{project_uid}/db_services/import_check: + post: + consumes: + - multipart/form-data + operationId: ImportDBServicesOfOneProjectCheckV2 parameters: - - description: User uid + - description: project id in: path - name: user_uid + name: project_uid required: true type: string - x-go-name: UserUid - - description: Update a user + x-go-name: ProjectUid + - description: DBServices file. + in: formData + name: db_services_file + type: file + x-go-name: DBServicesFile + produces: + - application/json + - text/csv + responses: + "200": + $ref: '#/responses/ImportDBServicesCheckCsvReply' + default: + description: ImportDBServicesCheckReply + schema: + $ref: '#/definitions/ImportDBServicesCheckReply' + summary: Import DBServices. + tags: + - DBService + /v2/dms/projects/import: + post: + operationId: ImportProjectsV2 + parameters: + - description: import projects in: body - name: user - schema: {} - x-go-name: User + name: projects + required: true + schema: + $ref: '#/definitions/ImportProjectsReqV2' responses: "200": description: GenericResp @@ -1382,60 +13215,105 @@ paths: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Update a user. + summary: Import projects. tags: - - dms - /v1/dms/users/{user_uid}/op_permission: - get: - operationId: GetUserOpPermission + - Project + /v2/dms/projects/import_db_services: + post: + operationId: ImportDBServicesOfProjectsV2 parameters: - - description: user uid - in: path - name: user_uid - required: true - type: string - x-go-name: UserUid - - description: user op permission info + - description: new db services in: body - name: user_op_permission - schema: {} - x-go-name: UserOpPermission + name: db_services + required: true + schema: + $ref: '#/definitions/ImportDBServicesOfProjectsReqV2' responses: "200": - description: GetUserOpPermissionReply + description: GenericResp schema: - $ref: '#/definitions/GetUserOpPermissionReply' + $ref: '#/definitions/GenericResp' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: Get user op permission info, This API is used by other component such as sqle&auth to check user permissions. + summary: Import DBServices. tags: - - dms - /v1/dms/webhooks: + - Project + /v2/dms/projects/import_db_services_check: post: - operationId: WebHookSendMessage + consumes: + - multipart/form-data + operationId: ImportDBServicesOfProjectsCheckV2 parameters: - - description: webhooks - in: body - name: webhook_message - schema: {} - x-go-name: WebHookMessage + - description: DBServices file. + in: formData + name: db_services_file + type: file + x-go-name: DBServicesFile + produces: + - application/json + - text/csv responses: "200": - description: WebHookSendMessageReply + $ref: '#/responses/ImportDBServicesCheckCsvReply' + default: + description: ImportDBServicesCheckReply schema: - $ref: '#/definitions/WebHookSendMessageReply' + $ref: '#/definitions/ImportDBServicesCheckReply' + summary: Import DBServices. + tags: + - Project + /v2/dms/projects/preview_import: + post: + consumes: + - multipart/form-data + operationId: PreviewImportProjectsV2 + parameters: + - description: projects file. + in: formData + name: projects_file + type: file + x-go-name: ProjectsFile + responses: + "200": + description: PreviewImportProjectsReplyV2 + schema: + $ref: '#/definitions/PreviewImportProjectsReplyV2' default: description: GenericResp schema: $ref: '#/definitions/GenericResp' - summary: webhook send message. + summary: Preview import projects. tags: - - dms + - Project produces: - application/json responses: + DownloadDataExportTaskReply: + description: "" + schema: + type: file + DownloadDataExportTaskSQLsReply: + description: "" + schema: + type: file + DownloadResourceOverviewListRes: + description: "" + schema: + type: file + ExportCBOperationLogsReply: + description: "" + schema: + type: file + ExportOperationRecordListReply: + description: "" + schema: + type: file + ExportProjectsReply: + description: "" + schema: + type: file GenericResp: description: GenericResp defines the return code and msg headers: @@ -1443,13 +13321,35 @@ responses: description: code format: int64 type: integer - msg: + message: description: message type: string + GetImportDBServicesTemplateReply: + description: "" + schema: + type: file + GetImportProjectsTemplateReply: + description: "" + schema: + type: file + GetLicenseInfoReply: + description: "" + schema: + type: file + GetStaticLogoReply: + description: "" + schema: + type: file + ImportDBServicesCheckCsvReply: + description: "" + schema: + type: file schemes: - http - https securityDefinitions: basic: - type: basic + in: header + name: Authorization + type: apiKey swagger: "2.0" diff --git a/build/dms.spec b/build/dms.spec index d4409c19a..b55757b26 100644 --- a/build/dms.spec +++ b/build/dms.spec @@ -1,6 +1,6 @@ -Name: %{project_name} -Version: 99.99.99 -Release: %{release}%{?dist} +Name: dms +Version: %{commit} +Release: %{os_version} Summary: Actiontech %{name} Source0: %{name}.tar.gz License: Enterprise @@ -16,23 +16,19 @@ Acitontech %{name} %setup -q %build - - -# e.g: %{release} = qa.el7, RELEASE need qa/alpha -make build_dms RELEASE=$(echo %{release} | tr '.' '\n' | head -n1) - +# build is done in outside, please see Makefile. %install rm -rf $RPM_BUILD_ROOT/usr/local/%{name} mkdir -p $RPM_BUILD_ROOT/usr/local/%{name} mkdir -p $RPM_BUILD_ROOT/usr/local/%{name}/service-file-template -mkdir -p $RPM_BUILD_ROOT/usr/local/%{name}/static -cp %{_builddir}/%{buildsubdir}/bin/dms $RPM_BUILD_ROOT/usr/local/%{name}/dms -cp %{_builddir}/%{buildsubdir}/build/service-file-template/* $RPM_BUILD_ROOT/usr/local/%{name}/service-file-template/ -cp %{_builddir}/%{buildsubdir}/config.yaml $RPM_BUILD_ROOT/usr/local/%{name}/config.yaml -cp -r %{_builddir}/%{buildsubdir}/build/static/* $RPM_BUILD_ROOT/usr/local/%{name}/static/ -cp %{_builddir}/%{buildsubdir}/build/scripts/init_start.sh $RPM_BUILD_ROOT/usr/local/%{name}/init_start.sh - +mkdir -p $RPM_BUILD_ROOT/usr/local/%{name}/static/logo +cp %{_builddir}/%{buildsubdir}/%{name}/build/service-file-template/* $RPM_BUILD_ROOT/usr/local/%{name}/service-file-template/ +cp %{_builddir}/%{buildsubdir}/%{name}/build/logo/* $RPM_BUILD_ROOT/usr/local/%{name}/static/logo/ +cp %{_builddir}/%{buildsubdir}/%{name}/config.yaml $RPM_BUILD_ROOT/usr/local/%{name}/config.yaml +cp -r %{_builddir}/%{buildsubdir}/%{name}/build/static/* $RPM_BUILD_ROOT/usr/local/%{name}/static/ +cp %{_builddir}/%{buildsubdir}/%{name}/build/scripts/init_start.sh $RPM_BUILD_ROOT/usr/local/%{name}/init_start.sh +cp %{_builddir}/%{buildsubdir}/%{name}/bin/dms $RPM_BUILD_ROOT/usr/local/%{name}/dms %clean rm -rf %{_builddir}/%{buildsubdir} @@ -67,7 +63,7 @@ chmod 440 /etc/security/limits.d/%{name}.conf grep systemd /proc/1/comm 1>/dev/null 2>&1 if [ $? -eq 0 ]; then - sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/dms.pid|g" -e "s|ExecStart=|ExecStart=$RPM_INSTALL_PREFIX\/dms -conf $RPM_INSTALL_PREFIX/config.yaml|g" -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX|g" $RPM_INSTALL_PREFIX/service-file-template/dms.systemd > /lib/systemd/system/dms.service + sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/dms.pid|g" -e "s|User=|User=actiontech-universe|g" -e "s|ExecStart=|ExecStart=$RPM_INSTALL_PREFIX\/dms -conf $RPM_INSTALL_PREFIX/config.yaml|g" -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX|g" $RPM_INSTALL_PREFIX/service-file-template/dms.systemd > /lib/systemd/system/dms.service systemctl daemon-reload systemctl enable dms.service @@ -200,4 +196,7 @@ fi /usr/local/%{name}/dms /usr/local/%{name}/config.yaml /usr/local/%{name}/init_start.sh -/usr/local/%{name}/static/* +/usr/local/%{name}/static/* + + +%config /usr/local/%{name}/config.yaml diff --git a/build/dms_sqle_provision.spec b/build/dms_sqle_provision.spec new file mode 100644 index 000000000..e9ba990b5 --- /dev/null +++ b/build/dms_sqle_provision.spec @@ -0,0 +1,223 @@ +Summary: Actiontech dms +Name: dms +Version: %{commit} +%if %{?_with_qa:1}%{!?_with_qa:0} +Release: qa.%{os_version} +%else +Release: rel.%{os_version} +%endif +Source0: %{name}.tar.gz +License: Commercial +Group: Actiontech +Prefix: /usr/local/%{name} +AutoReq: no + +%description +Acitontech dms + +%define debug_package %{nil} +%define _source_filedigest_algorithm md5 +%define _binary_filedigest_algorithm md5 +%define _source_payload w0.gzdio +%define _binary_payload w0.gzdio + +########## + +%prep +%setup -q + +########## + +########## + +%build +## build is done in outside, please see Makefile. + +########## + +%install +rm -rf $RPM_BUILD_ROOT +mkdir -p $RPM_BUILD_ROOT/usr/local/%{name}/plugins +cp -R %{_builddir}/%{buildsubdir}/%{name}/builddir/config $RPM_BUILD_ROOT/usr/local/%{name}/etc +cp -R %{_builddir}/%{buildsubdir}/%{name}/builddir/bin $RPM_BUILD_ROOT/usr/local/%{name}/bin +cp -R %{_builddir}/%{buildsubdir}/%{name}/builddir/scripts $RPM_BUILD_ROOT/usr/local/%{name}/scripts +cp -R %{_builddir}/%{buildsubdir}/%{name}/builddir/static $RPM_BUILD_ROOT/usr/local/%{name}/static +cp -R %{_builddir}/%{buildsubdir}/%{name}/builddir/neo4j-community $RPM_BUILD_ROOT/usr/local/%{name}/neo4j-community +cp -R %{_builddir}/%{buildsubdir}/%{name}/builddir/lib $RPM_BUILD_ROOT/usr/local/%{name}/lib +cp -R %{_builddir}/%{buildsubdir}/%{name}/builddir/jdk $RPM_BUILD_ROOT/usr/local/%{name}/jdk + +########## + +%files +%defattr(-,root,root) +/usr/local/%{name}/bin/* +/usr/local/%{name}/plugins +/usr/local/%{name}/scripts/* +/usr/local/%{name}/jdk/* +/usr/local/%{name}/static/* +/usr/local/%{name}/neo4j-community/* +/usr/local/%{name}/lib/* +/usr/local/%{name}/etc/config.yaml +%config /usr/local/%{name}/etc/config.yaml + +########## + +%clean +#rm -rf $RPM_BUILD_ROOT + +########## + +%pre + +#check directory +grep systemd /proc/1/comm 1>/dev/null 2>&1 +if [ $? -eq 0 ]; then + if [ ! -d "/lib/systemd/system" ];then + mkdir -p /lib/systemd/system + chmod 0755 /lib/systemd/system + fi +fi + +#create group & user +(which nologin 1>/dev/null 2>&1) || (echo "require nologin" && exit 11) +(which bash 1>/dev/null 2>&1) || (echo "require bash" && exit 12) +(which pkill 1>/dev/null 2>&1) || (echo "require pkill" && exit 13) +(getent group %{group_name} 1>/dev/null 2>&1) || groupadd -g 5700 %{group_name} +(id %{user_name} 1>/dev/null 2>&1) || (useradd -M -g %{group_name} -s $(which nologin) -u 5700 %{user_name} && chage -M 99999 %{user_name}) + +#create ulimit +if [ ! -d "/etc/security/limits.d" ];then + mkdir /etc/security/limits.d + chmod 0755 /etc/security/limits.d +fi + +cat > /etc/security/limits.d/%{name}.conf <&1 | grep -e 'warning' -e 'error' +if [ $? -eq 0 ]; then + exit 14 +fi + +########## + +%post + +cat >> $RPM_INSTALL_PREFIX/neo4j-community/conf/neo4j.conf </dev/null 2>&1 +if [ $? -eq 0 ]; then + sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/sqled.pid|g" \ + -e "s|User=|User=actiontech-universe|g" \ + -e "s|ExecStart=|ExecStart=/bin/sh -c 'exec $RPM_INSTALL_PREFIX\/bin\/sqled --config $RPM_INSTALL_PREFIX\/etc\/config.yaml --pidfile=$RPM_INSTALL_PREFIX\/sqled.pid >>$RPM_INSTALL_PREFIX\/std.log 2>\&1'|g" \ + -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX|g" \ + $RPM_INSTALL_PREFIX/scripts/sqled.systemd > /lib/systemd/system/sqled.service + sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/dms.pid|g" \ + -e "s|User=|User=actiontech-universe|g" \ + -e "s|ExecStart=|ExecStart=$RPM_INSTALL_PREFIX\/bin\/dms -conf $RPM_INSTALL_PREFIX\/etc\/config.yaml|g" \ + -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX|g" \ + $RPM_INSTALL_PREFIX/scripts/dms.systemd > /lib/systemd/system/dms.service + sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/provision.pid|g" \ + -e "s|ExecStart=|ExecStart=$RPM_INSTALL_PREFIX\/bin\/provision -conf $RPM_INSTALL_PREFIX\/etc\/config.yaml|g" \ + -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX|g" \ + $RPM_INSTALL_PREFIX/scripts/provision.systemd > /lib/systemd/system/provision.service + sed -e "s|PIDFile=|PIDFile=$RPM_INSTALL_PREFIX\/neo4j-community/run/neo4j.pid|g" \ + -e "s|ExecStart=|ExecStart=/bin/bash -c 'export JAVA_HOME=$RPM_INSTALL_PREFIX/jdk\;\ $RPM_INSTALL_PREFIX\/neo4j-community/bin/neo4j start'|g" \ + -e "s|ExecStop=|ExecStop=$RPM_INSTALL_PREFIX\/neo4j-community/bin/neo4j stop|g" \ + -e "s|ExecReload=|ExecReload=$RPM_INSTALL_PREFIX\/neo4j-community/bin/neo4j restart|g" \ + -e "s|WorkingDirectory=|WorkingDirectory=$RPM_INSTALL_PREFIX/neo4j-community|g" \ + $RPM_INSTALL_PREFIX/scripts/neo4j.systemd > /lib/systemd/system/neo4j.service + systemctl daemon-reload + systemctl enable provision.service + systemctl enable neo4j.service + systemctl enable sqled.service + systemctl enable dms.service +fi + +mkdir -p $RPM_INSTALL_PREFIX/logs +# mkdir -p $RPM_INSTALL_PREFIX/etc + +cat > $RPM_INSTALL_PREFIX/etc/gh-ost.ini</dev/null 2>&1 + if [ $? -eq 0 ]; then + systemctl stop sqled.service || true + systemctl stop dms.service || true + systemctl stop neo4j.service || true + systemctl stop provision.service || true + fi +fi + +########## + +%postun + +if [ "$1" = "0" ]; then + grep systemd /proc/1/comm 1>/dev/null 2>&1 + if [ $? -eq 0 ]; then + rm -f /lib/systemd/system/sqled.service || true + rm -f /lib/systemd/system/dms.service || true + rm -f /lib/systemd/system/neo4j.service || true + rm -f /lib/systemd/system/provision.service || true + fi +fi + + diff --git a/build/docker-image/rpm-build/Dockerfile b/build/docker-image/rpm-build/Dockerfile deleted file mode 100644 index b470a669e..000000000 --- a/build/docker-image/rpm-build/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -FROM centos:7 - -# install rpmbuild -RUN yum install -y rpmdevtools yum-utils -ADD docker-rpm-build.sh /usr/local/bin -RUN chmod +x /usr/local/bin/docker-rpm-build.sh -RUN rpmdev-setuptree - -# install golang -ADD https://mirrors.ustc.edu.cn/golang/go1.19.6.linux-amd64.tar.gz /usr/local -RUN cd /usr/local \ - && tar -zxvf /usr/local/go1.19.6.linux-amd64.tar.gz -RUN cp /usr/local/go/bin/* /bin - -# install make -RUN yum install -y epel-release -RUN yum update -y -RUN yum install -y make - -# intall gcc -RUN yum install -y gcc - -# install wget -RUN yum install -y wget - -# install git -RUN yum install -y git - -# clean -RUN yum clean all && \ - rm -r -f /var/cache/* - - -ENTRYPOINT ["/usr/local/bin/docker-rpm-build.sh"] diff --git a/build/docker-image/rpm-build/README.md b/build/docker-image/rpm-build/README.md deleted file mode 100644 index 433a74b77..000000000 --- a/build/docker-image/rpm-build/README.md +++ /dev/null @@ -1,30 +0,0 @@ -## Reference -https://hub.docker.com/r/jitakirin/rpmbuild - -## Usage -Typical usage: -``` -docker run --rm --volume=/path-to-source:/src --volume=/path-to-spec-dir:/spec --volume=/path-to-output:/out \ - rpmbuild-image dms.spec -``` - -You can also specify rpmbuild args: -``` -docker run --rm --volume=/path-to-source:/src --volume=/path-to-spec-dir:/spec --volume=/path-to-output:/out \ - --env=RPM_ARGS="-bb" \ - rpmbuild-image dms.spec -``` - -If your package requires something from a non-core repo to build, you can add that repo using a PRE_BUILDDEP hook. It is an env variable that should contain an inline script or command to add the repo you need. E.g. for EPEL do: -``` -docker run --rm --volume=/path-to-source:/src --volume=/path-to-spec-dir:/spec --volume=/path-to-output:/out \ - --env=PRE_BUILDDEP="yum install -y epel-release" \ - rpmbuild-image dms.spec -``` - -## Debugging -Set VERBOSE option in the environment (with -e VERBOSE=1 option to docker run) which will enable verbose output from the scripts and rpmbuild. -``` -docker run -it -e VERBOSE=1 --volume=/path-to-source:/src --volume=/path-to-spec-dir:/spec --volume=/path-to-output:/out \ - rpmbuild-image dms.spec -``` diff --git a/build/docker-image/rpm-build/docker-rpm-build.sh b/build/docker-image/rpm-build/docker-rpm-build.sh deleted file mode 100644 index bcc3b327b..000000000 --- a/build/docker-image/rpm-build/docker-rpm-build.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash -set -e "${VERBOSE:+-x}" - -SPEC="/spec/$1" -if [[ -z ${SPEC} || ! -e ${SPEC} ]]; then - echo "Usage: docker run [--rm]" \ - "--volume=/path/to/source:/src --volume=/path/to/spec-dir:/spec --workdir=/src" \ - "rpmbuild-image SPEC_FILE_NAME" >&2 - exit 2 -fi - -# pre-builddep hook for adding extra repos -if [[ -n ${PRE_BUILDDEP} ]]; then - bash "${VERBOSE:+-x}" -c "${PRE_BUILDDEP}" -fi - -TOPDIR="${HOME}/rpmbuild" - -cp "${VERBOSE:+-v}" -a --reflink=auto /src/* "${TOPDIR}/SOURCES/" -cp "${VERBOSE:+-v}" -a --reflink=auto "${SPEC}" "${TOPDIR}/SPECS/" - -SPEC="${TOPDIR}/SPECS/${1}" -DEFAULT_RPM_ARGS="-ba" - -if [[ -n ${RPM_ARGS} ]]; then - DEFAULT_RPM_ARGS=${RPM_ARGS} -fi - -CMD="rpmbuild ${VERBOSE:+-v} ${DEFAULT_RPM_ARGS} ${SPEC}" -bash -c "${CMD}" - -OUTDIR="/out" -cp "${VERBOSE:+-v}" -a --reflink=auto \ - ${TOPDIR}/RPMS "${OUTDIR}/" diff --git a/build/logo/mysql.png b/build/logo/mysql.png new file mode 100644 index 000000000..03e234d45 Binary files /dev/null and b/build/logo/mysql.png differ diff --git a/build/scripts/dms_sqle_provision.sh b/build/scripts/dms_sqle_provision.sh new file mode 100644 index 000000000..c3071145b --- /dev/null +++ b/build/scripts/dms_sqle_provision.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +# 本脚本用于在rpm安装完成后,启动dms服务和sqled服务 + +detectSystemServiceStatus() { + detectedRunningTimes=0 + for i in {1..30}; do + sleep 1 + if systemctl status "$1" &>/dev/null; then + ((detectedRunningTimes++)) + if [[ $detectedRunningTimes == 3 ]]; then + echo "init and start $1 success!" + return 0 + fi + else + detectedRunningTimes=0 + fi + done + + echo "duration 30 seconds; start $1 failed" + return 1 +} + +systemctl daemon-reload + +systemctl start dms.service +if ! detectSystemServiceStatus "dms.service"; then + exit 3 +fi + +systemctl start sqled.service +if ! detectSystemServiceStatus "sqled.service"; then + exit 3 +fi + +systemctl start neo4j.service +if ! detectSystemServiceStatus "neo4j.service"; then + exit 3 +fi + +systemctl start provision.service +if ! detectSystemServiceStatus "provision.service"; then + exit 3 +fi \ No newline at end of file diff --git a/build/service-file-template/dms.systemd b/build/service-file-template/dms.systemd index deca2fdb7..7ab0f53cb 100644 --- a/build/service-file-template/dms.systemd +++ b/build/service-file-template/dms.systemd @@ -5,6 +5,7 @@ Description=DMS WantedBy=multi-user.target [Service] +User= LimitNOFILE=65535 LimitNPROC=65535 TasksMax=512 diff --git a/config.yaml b/config.yaml index 4d7b94773..c7ac48cf6 100644 --- a/config.yaml +++ b/config.yaml @@ -1,22 +1,28 @@ -api: - http: - addr: 0.0.0.0 - port: 7601 dms: - data: + id: 1 + api: + addr: 0.0.0.0 + port: 10000 + service: database: username: root - password: pass + password: 123 host: 127.0.0.1 port: 3306 database: dms - debug: true -node: - nodeno: 1 -cloudbeaver: - enable_https: false - host: 127.0.0.1 - port: 8978 - admin_user: admin - admin_password: admin - + auto_migrate: true + log: + level: INFO + path: logs + max_size_mb: 100 + max_backup_number: 10 + cloudbeaver: + enable_https: false + host: 127.0.0.1 + port: 8978 + admin_user: administrator + admin_password: 123456 + secret_key: + server_id: + enable_cluster_mode: false + report_host: # the host name or IP address of the cluster node diff --git a/config_quick_usage.yaml b/config_quick_usage.yaml deleted file mode 100644 index c59bbebbe..000000000 --- a/config_quick_usage.yaml +++ /dev/null @@ -1,15 +0,0 @@ -api: - http: - addr: 0.0.0.0 - port: 7601 -dms: - data: - database: - username: root - password: 123 - host: 172.41.134.4 - port: 3306 - database: dmstest - debug: true -node: - nodeno: 1 diff --git a/go.mod b/go.mod index f9ec5737f..997803096 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,8 @@ module github.com/actiontech/dms -go 1.19 +go 1.24.0 + +toolchain go1.24.1 require ( github.com/bwmarrin/snowflake v0.3.0 @@ -11,37 +13,63 @@ require ( github.com/golang-jwt/jwt v3.2.2+incompatible github.com/labstack/echo/v4 v4.10.2 github.com/mindstand/gogm/v2 v2.3.6 - github.com/urfave/cli/v2 v2.8.1 - golang.org/x/sync v0.1.0 + github.com/urfave/cli/v2 v2.27.7 + golang.org/x/sync v0.17.0 ) require ( - github.com/99designs/gqlgen v0.17.20 + github.com/99designs/gqlgen v0.17.81 + github.com/BurntSushi/toml v1.5.0 github.com/go-ldap/ldap/v3 v3.4.5 github.com/go-sql-driver/mysql v1.7.0 + github.com/iancoleman/strcase v0.3.0 + github.com/json-iterator/go v1.1.12 github.com/labstack/echo-jwt/v4 v4.1.0 - github.com/stretchr/testify v1.8.2 + github.com/nicksnyder/go-i18n/v2 v2.4.0 + github.com/robfig/cron/v3 v3.0.1 + github.com/stretchr/testify v1.11.1 + github.com/swaggo/echo-swagger v1.4.1 + github.com/swaggo/swag v1.16.3 github.com/ungerik/go-dry v0.0.0-20210209114055-a3e162a9e62e - github.com/vektah/gqlparser/v2 v2.5.1 - golang.org/x/oauth2 v0.9.0 + github.com/vektah/gqlparser/v2 v2.5.30 gopkg.in/chanxuehong/wechat.v1 v1.0.0-20171118020122-aad7e298d1e7 gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df + gopkg.in/natefinch/lumberjack.v2 v2.0.0 gorm.io/driver/mysql v1.4.7 gorm.io/gorm v1.24.3 ) require ( - github.com/agnivade/levenshtein v1.1.1 // indirect + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/PuerkitoBio/purell v1.1.1 // indirect + github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect + github.com/agnivade/levenshtein v1.2.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fatih/color v1.10.0 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/ghodss/yaml v1.0.0 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.19.6 // indirect + github.com/go-openapi/spec v0.20.4 // indirect + github.com/go-openapi/swag v0.19.15 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect + github.com/josharian/intern v1.0.0 // indirect github.com/kr/pretty v0.3.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rogpeppe/go-internal v1.8.0 // indirect - golang.org/x/mod v0.8.0 // indirect - golang.org/x/tools v0.6.0 // indirect + github.com/sosodev/duration v1.3.1 // indirect + github.com/swaggo/files/v2 v2.0.0 // indirect + github.com/tidwall/pretty v1.2.0 // indirect + golang.org/x/mod v0.28.0 // indirect + golang.org/x/tools v0.37.0 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) @@ -49,34 +77,29 @@ require ( github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/chanxuehong/util v0.0.0-20200304121633-ca8141845b13 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect - github.com/fatih/color v1.10.0 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect github.com/go-asn1-ber/asn1-ber v1.5.4 // indirect github.com/go-openapi/errors v0.20.3 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/golang-jwt/jwt/v4 v4.5.0 - github.com/golang/protobuf v1.5.2 // indirect github.com/labstack/gommon v0.4.0 // indirect github.com/larksuite/oapi-sdk-go/v3 v3.0.23 github.com/leodido/go-urn v1.2.4 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.17 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/oklog/ulid v1.3.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect - github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect go.mongodb.org/mongo-driver v1.11.3 // indirect - golang.org/x/crypto v0.10.0 // indirect - golang.org/x/net v0.11.0 // indirect - golang.org/x/sys v0.9.0 // indirect - golang.org/x/text v0.10.0 // indirect + golang.org/x/crypto v0.42.0 // indirect + golang.org/x/net v0.44.0 // indirect + golang.org/x/sys v0.36.0 // indirect + golang.org/x/text v0.29.0 golang.org/x/time v0.3.0 // indirect - golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/protobuf v1.28.0 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect ) diff --git a/go.sum b/go.sum index ef7505ad0..eea7d6c62 100644 --- a/go.sum +++ b/go.sum @@ -22,8 +22,8 @@ cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiy cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/99designs/gqlgen v0.17.20 h1:O7WzccIhKB1dm+7g6dhQcULINftfiLSBg2l/mwbpJMw= -github.com/99designs/gqlgen v0.17.20/go.mod h1:Mja2HI23kWT1VRH09hvWshFgOzKswpO20o4ScpJIES4= +github.com/99designs/gqlgen v0.17.81 h1:kCkN/xVyRb5rEQpuwOHRTYq83i0IuTQg9vdIiwEerTs= +github.com/99designs/gqlgen v0.17.81/go.mod h1:vgNcZlLwemsUhYim4dC1pvFP5FX0pr2Y+uYUoHFb1ig= github.com/Azure/azure-sdk-for-go v16.2.1+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= @@ -40,8 +40,11 @@ github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBp github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= +github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= @@ -62,14 +65,15 @@ github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5 github.com/Microsoft/hcsshim/test v0.0.0-20210227013316-43a75bb4edd3/go.mod h1:mw7qgWloBUl75W/gVH3cQszUg1+gUITj7D6NY7ywVnY= github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ= github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8= github.com/adam-hanna/arrayOperations v0.2.6/go.mod h1:iIzkSjP91FnE66cUFNAjjUJVmjyAwCH0SXnWsx2nbdk= -github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM= -github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8= -github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= +github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM= +github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -230,9 +234,8 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc github.com/cornelk/hashmap v1.0.0/go.mod h1:8wbysTUDnwJGrPZ1Iwsou3m+An6sldFrJItjRhfegCw= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo= +github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= @@ -250,8 +253,8 @@ github.com/denverdino/aliyungo v0.0.0-20190125010748-a747050bb1ba/go.mod h1:dV8l github.com/dgrijalva/jwt-go v0.0.0-20170104182250-a601269ab70c/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g= -github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= +github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo= +github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= github.com/dnephin/pflag v1.0.7/go.mod h1:uxE91IoWURlOiTUIA8Mq5ZZkAv3dPUfZNaT80Zm7OQE= github.com/docker/distribution v0.0.0-20190905152932-14b96e55d84c/go.mod h1:0+TTO4EOBfRPhZXAeF1Vu+W3hHZ8eLp8PgKVZlcvtFY= @@ -293,6 +296,7 @@ github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-asn1-ber/asn1-ber v1.5.4 h1:vXT6d/FNDiELJnLb6hGNa309LMsrCoYFvpwHDF0+Y1A= github.com/go-asn1-ber/asn1-ber v1.5.4/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= @@ -319,15 +323,24 @@ github.com/go-openapi/errors v0.20.3 h1:rz6kiC84sqNQoqrtulzaL/VERgkoCyB6WdEkc2uj github.com/go-openapi/errors v0.20.3/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= +github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= github.com/go-openapi/spec v0.19.3/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo= +github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= github.com/go-openapi/strfmt v0.21.7 h1:rspiXgNWgeUzhjo1YU01do6qsahtJNByjLVbPLNHb8k= github.com/go-openapi/strfmt v0.21.7/go.mod h1:adeGTkxE44sPyLk0JV235VQAO/ZXUr8KAzYjclFs3ew= github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/form/v4 v4.2.0/go.mod h1:q1a2BY+AQUUzhl6xA/6hBetay6dEIhMHjgvJiGo6K7U= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= @@ -341,6 +354,8 @@ github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/goccy/go-yaml v1.11.0 h1:n7Z+zx8S9f9KgzG6KtQKf+kwqXZlLNR2F6018Dgau54= github.com/goccy/go-yaml v1.11.0/go.mod h1:H+mJrWtjPTJAHvRbV09MCK9xYwODM+wRTVFFTWckfng= github.com/godbus/dbus v0.0.0-20151105175453-c7fdd8b5cd55/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= @@ -387,7 +402,6 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= @@ -403,7 +417,8 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= @@ -418,8 +433,9 @@ github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg= @@ -444,11 +460,14 @@ github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brv github.com/hashicorp/go-multierror v0.0.0-20161216184304-ed905158d874/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= -github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= @@ -466,14 +485,17 @@ github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht github.com/jmespath/go-jmespath v0.0.0-20160803190731-bd40a432e4c7/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kevinmbeaulieu/eq-go v1.0.0/go.mod h1:G3S8ajA56gKBZm4UB9AOyoOS37JO3roToPzKNM8dtdM= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= @@ -505,25 +527,25 @@ github.com/larksuite/oapi-sdk-go/v3 v3.0.23 h1:mn4pD4JXgzYbpc9TT0grGHPcYppYEmisK github.com/larksuite/oapi-sdk-go/v3 v3.0.23/go.mod h1:FKi8vBgtkBt/xNRQUwdWvoDmsPh7/wP75Sn5IBIBQLk= github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= -github.com/logrusorgru/aurora/v3 v3.0.0/go.mod h1:vsR12bk5grlLvLXAYrBsb5Oc/N+LxAlxggSjiwMnCUc= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/marstr/guid v1.1.0/go.mod h1:74gB1z2wpxxInTG6yaqA7KrtM0NZ+RbrcqDvYHefzho= -github.com/matryer/moq v0.2.7/go.mod h1:kITsx543GOENm48TUAQyJ9+SAvFSr7iGQXPoth/VUBk= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= -github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= @@ -532,7 +554,6 @@ github.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WT github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.3.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/osext v0.0.0-20151018003038-5e2d6d41470f/go.mod h1:OkQIRizQZAeMln+1tSwduZz7+Af5oFlKirV/MSYes2A= @@ -545,9 +566,12 @@ github.com/moby/sys/symlink v0.1.0/go.mod h1:GGDODQmbFOjFsXvfLVn3+ZRxkch54RkSiGq github.com/moby/term v0.0.0-20200312100748-672ec06f55cd/go.mod h1:DdlQx2hp0Ss5/fLikoLlEeIYiATotOjgB//nb973jeo= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/mrunalp/fileutils v0.5.0/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= @@ -557,6 +581,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= github.com/neo4j/neo4j-go-driver/v4 v4.4.2-0.20220317151800-1a19fb114732/go.mod h1:NexOfrm4c317FVjekrhVV8pHBXgtMG5P6GeweJWCyo4= +github.com/nicksnyder/go-i18n/v2 v2.4.0 h1:3IcvPOAvnCKwNm0TB0dLDTuawWEj+ax/RERNC+diLMM= +github.com/nicksnyder/go-i18n/v2 v2.4.0/go.mod h1:nxYSZE9M0bf3Y70gPQjN9ha7XNHX7gMc814+6wVyEI4= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= @@ -644,6 +670,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= @@ -656,8 +684,8 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= +github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= github.com/shirou/gopsutil/v3 v3.21.8/go.mod h1:YWp/H8Qs5fVmf17v7JNZzA0mPJ+mS2e9JdiUF9LlKzQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.0.4-0.20170822132746-89742aefa4b2/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= @@ -671,6 +699,8 @@ github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/sosodev/duration v1.3.1 h1:qtHBDMQ6lvMQsL15g4aopM4HEfOaYuhWBw3NPTtlqq4= +github.com/sosodev/duration v1.3.1/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= @@ -701,15 +731,23 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/swaggo/echo-swagger v1.4.1 h1:Yf0uPaJWp1uRtDloZALyLnvdBeoEL5Kc7DtnjzO/TUk= +github.com/swaggo/echo-swagger v1.4.1/go.mod h1:C8bSi+9yH2FLZsnhqMZLIZddpUxZdBYuNHbtaS1Hljc= +github.com/swaggo/files/v2 v2.0.0 h1:hmAt8Dkynw7Ssz46F6pn8ok6YmGZqHSVLZ+HQM7i0kw= +github.com/swaggo/files/v2 v2.0.0/go.mod h1:24kk2Y9NYEJ5lHuCra6iVwkMjIekMCaFq/0JQj66kyM= +github.com/swaggo/swag v1.16.3 h1:PnCYjPCah8FK4I26l2F/KQ4yz3sILcVUN3cTlBFA9Pg= +github.com/swaggo/swag v1.16.3/go.mod h1:DImHIuOFXKpMFAQjcC7FG4m3Dg4+QuUgUzJmKjI/gRk= github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/tchap/go-patricia v2.2.6+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= github.com/testcontainers/testcontainers-go v0.13.0/go.mod h1:z1abufU633Eb/FmSBTzV6ntZAC1eZBYPtaFsn4nPuDk= -github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tklauser/go-sysconf v0.3.9/go.mod h1:11DU/5sG7UexIrp/O6g35hrWzu0JxlwQ3LSFUzyeuhs= github.com/tklauser/numcpus v0.3.0/go.mod h1:yFGUr7TUHQRAhyqBcEg0Ge34zDBAsIvJJcyE6boqnA8= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -722,15 +760,15 @@ github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijb github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli/v2 v2.0.0/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= -github.com/urfave/cli/v2 v2.8.1 h1:CGuYNZF9IKZY/rfBe3lJpccSoIY1ytfvmgQT90cNOl4= -github.com/urfave/cli/v2 v2.8.1/go.mod h1:Z41J9TPoffeoqP0Iza0YbAhGvymRdZAd2uPmZ5JxRdY= +github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU= +github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/vektah/gqlparser/v2 v2.5.1 h1:ZGu+bquAY23jsxDRcYpWjttRZrUz07LbiY77gUOHcr4= -github.com/vektah/gqlparser/v2 v2.5.1/go.mod h1:mPgqFBu/woKTVYWyNk8cO3kh4S/f4aRFZrvOnp3hmCs= +github.com/vektah/gqlparser/v2 v2.5.30 h1:EqLwGAFLIzt1wpx1IPpY67DwUujF1OfzgEyDsLrN6kE= +github.com/vektah/gqlparser/v2 v2.5.30/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo= github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= @@ -750,12 +788,11 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1: github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4= +github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs= github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA= @@ -795,8 +832,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= -golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= -golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= +golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI= +golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -827,10 +864,10 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U= +golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -868,23 +905,21 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211108170745-6635138e15ea/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= -golang.org/x/net v0.11.0 h1:Gi2tvZIJyBtO9SDr1q9h5hEQCp/4L2RQ+ar0qjx2oNU= -golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ= +golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= +golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.9.0 h1:BPpt2kU7oMRq3kCHAA1tbSEshXRw1LpG2ztgDwrzuAs= -golang.org/x/oauth2 v0.9.0/go.mod h1:qYgFZaFiu6Wg24azG8bdV52QJXJGbZzIIsRCdVKzbLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -897,8 +932,9 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220513210516-0976fa681c29/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -962,6 +998,7 @@ golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210426230700-d19ff857e887/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -971,18 +1008,16 @@ golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= -golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= +golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -998,8 +1033,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.10.0 h1:UpjohKhiEgNc0CSauXmwYftY1+LlaC75SJwh0SgCX58= -golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1046,10 +1081,10 @@ golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= +golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1071,8 +1106,6 @@ google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7 google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/cloud v0.0.0-20151119220103-975617b05ea8/go.mod h1:0H1ncTHf11KCFhTc/+EFRbzSCOZx+VUbRMk55Yv5MYk= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -1129,7 +1162,6 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= @@ -1151,6 +1183,7 @@ gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKW gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= @@ -1168,6 +1201,7 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/apiserver/cmd/server/main.go b/internal/apiserver/cmd/server/main.go index 81650cb47..29a728ac6 100644 --- a/internal/apiserver/cmd/server/main.go +++ b/internal/apiserver/cmd/server/main.go @@ -5,19 +5,27 @@ import ( "context" "flag" "fmt" + "log" "os" "os/signal" + "path/filepath" "syscall" + "github.com/actiontech/dms/internal/pkg/locale" + "github.com/actiontech/dms/internal/apiserver/conf" "github.com/actiontech/dms/internal/apiserver/service" - pkgLog "github.com/actiontech/dms/internal/pkg/log" + dmsConf "github.com/actiontech/dms/internal/dms/conf" + "github.com/actiontech/dms/pkg/dms-common/pkg/aes" + "github.com/actiontech/dms/pkg/dms-common/pkg/http" + pkgLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" "github.com/actiontech/dms/pkg/rand" utilIo "github.com/actiontech/dms/pkg/dms-common/pkg/io" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" kLog "github.com/go-kratos/kratos/v2/log" "golang.org/x/sync/errgroup" + rotate "gopkg.in/natefinch/lumberjack.v2" ) // go build -ldflags "-X main.Version=x.y.z" @@ -30,24 +38,32 @@ var ( func init() { flag.StringVar(&flagconf, "conf", "config.yaml", "config path, eg: -conf config.yaml") + dmsConf.Version = Version } -func run(logger utilLog.Logger) error { +func run(logger utilLog.Logger, opts *conf.DMSOptions) error { log_ := utilLog.NewHelper(logger, utilLog.WithMessageKey(Name)) + locale.MustInit(log_) gctx, cancel := context.WithCancel(context.Background()) defer cancel() g, errCtx := errgroup.WithContext(gctx) - opts, err := conf.ReadOptions(logger, flagconf) - if nil != err { - return fmt.Errorf("failed to read options: %v", err) - } - err = rand.InitSnowflake(opts.NodeOpts.NodeNo) + err := rand.InitSnowflake(opts.ID) if nil != err { return fmt.Errorf("failed to Init snowflake: %v", err) } + // reset jwt singing key, default dms token + if err = http.ResetJWTSigningKeyAndDefaultToken(opts.SecretKey); err != nil { + return err + } + + // reset aes secret key + if err = aes.ResetAesSecretKey(opts.SecretKey); err != nil { + return err + } + server, err := service.NewAPIServer(logger, opts) if nil != err { return fmt.Errorf("failed to new apiserver: %v", err) @@ -60,6 +76,12 @@ func run(logger utilLog.Logger) error { } return nil }) + log_.Infof("dms server started, version : %s ", Version) + + g.Go(func() error { + service.StartAllCronJob(server, errCtx) + return nil + }) // handle exit signal g.Go(func() error { @@ -71,9 +93,13 @@ func run(logger utilLog.Logger) error { return fmt.Errorf("unexpected shutdown because: %v", errCtx.Err()) case <-exit: log_.Info("shutdown because of signal") + + service.StopAllCronJob() + if err := server.Shutdown(); nil != err { return fmt.Errorf("failed to shutdown: %v", err) } + return nil } }) @@ -98,14 +124,25 @@ func run(logger utilLog.Logger) error { func main() { flag.Parse() - logger := kLog.With(pkgLog.NewStdLogger(os.Stdout, pkgLog.LogTimeLayout), + initLogger := pkgLog.NewUtilLogWrapper(kLog.With(pkgLog.NewStdLogger(os.Stdout, pkgLog.LogTimeLayout), "caller", kLog.DefaultCaller, - ) + )) - if err := run(pkgLog.NewUtilLogWrapper(logger)); nil != err { - kLog.NewHelper(kLog.With(logger, "module", Name)).Fatalf("failed to run: %v", err) + opts, err := conf.ReadOptions(initLogger, flagconf) + if nil != err { + log.Fatal(err) } + logger := kLog.With(kLog.NewFilter(pkgLog.NewStdLogger(&rotate.Logger{ + Filename: filepath.Join(opts.ServiceOpts.Log.Path, "dms.log"), + MaxSize: opts.ServiceOpts.Log.MaxSizeMB, // megabytes + MaxBackups: opts.ServiceOpts.Log.MaxBackupNumber, + LocalTime: true, + }, pkgLog.LogTimeLayout), kLog.FilterLevel(kLog.ParseLevel(opts.ServiceOpts.Log.Level))), "caller", kLog.DefaultCaller) + + if err := run(pkgLog.NewUtilLogWrapper(logger), opts); nil != err { + kLog.NewHelper(kLog.With(logger, "module", Name)).Fatalf("failed to run: %v", err) + } } func startPid(log utilLog.Logger, pidFile string) error { diff --git a/internal/apiserver/cmd/swag/swagger_darwin_arm64 b/internal/apiserver/cmd/swag/swagger_darwin_arm64 new file mode 100755 index 000000000..122203fbd Binary files /dev/null and b/internal/apiserver/cmd/swag/swagger_darwin_arm64 differ diff --git a/internal/apiserver/cmd/swag/swagger_linux_amd64 b/internal/apiserver/cmd/swag/swagger_linux_amd64 index d76a17ac9..9411d7409 100755 Binary files a/internal/apiserver/cmd/swag/swagger_linux_amd64 and b/internal/apiserver/cmd/swag/swagger_linux_amd64 differ diff --git a/internal/apiserver/conf/options.go b/internal/apiserver/conf/options.go index 672274ce9..8ec6eddca 100644 --- a/internal/apiserver/conf/options.go +++ b/internal/apiserver/conf/options.go @@ -1,26 +1,29 @@ package conf import ( - "fmt" - - dmsConf "github.com/actiontech/dms/internal/dms/conf" - + workbench "github.com/actiontech/dms/internal/sql_workbench/config" + dmsCommonConf "github.com/actiontech/dms/pkg/dms-common/conf" utilConf "github.com/actiontech/dms/pkg/dms-common/pkg/config" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" ) type Options struct { - APIServiceOpts *APIServerOpts `yaml:"api"` - DMSServiceOpts *dmsConf.Options `yaml:"dms"` - CloudbeaverOpts *CloudbeaverOpts `yaml:"cloudbeaver"` - NodeOpts *NodeOpts `yaml:"node"` + DMS DMSOptions `yaml:"dms" validate:"required"` + SQLE SQLEOptions `yaml:"sqle"` +} + +type SQLEOptions struct { + OptimizationConfig struct { + OptimizationKey string `yaml:"optimization_key"` + OptimizationUrl string `yaml:"optimization_url"` + } `yaml:"optimization_config"` } -type APIServerOpts struct { - HTTP struct { - Addr string `yaml:"addr" validate:"required"` - Port int `yaml:"port" validate:"required"` - } `yaml:"http"` +type DMSOptions struct { + dmsCommonConf.BaseOptions `yaml:",inline"` + CloudbeaverOpts *CloudbeaverOpts `yaml:"cloudbeaver"` + SqlWorkBenchOpts *workbench.SqlWorkbenchOpts `yaml:"sql_workbench"` + ServiceOpts *ServiceOptions `yaml:"service"` } type CloudbeaverOpts struct { @@ -31,23 +34,35 @@ type CloudbeaverOpts struct { AdminPassword string `yaml:"admin_password"` } -type NodeOpts struct { - NodeNo int64 `yaml:"nodeno" validate:"required"` +type ServiceOptions struct { + Database struct { + UserName string `yaml:"username" ` + Password string `yaml:"password" ` + Host string `yaml:"host" validate:"required"` + Port string `yaml:"port" validate:"required"` + Database string `yaml:"database" validate:"required"` + AutoMigrate bool `yaml:"auto_migrate"` + Debug bool `yaml:"debug"` + } `yaml:"database"` + Log struct { + Level string `yaml:"level"` + Path string `yaml:"path"` + MaxSizeMB int `yaml:"max_size_mb"` + MaxBackupNumber int `yaml:"max_backup_number"` + } `yaml:"log"` +} + +var optimizationEnabled bool + +func IsOptimizationEnabled() bool { + return optimizationEnabled } -func ReadOptions(log utilLog.Logger, path string) (*Options, error) { +func ReadOptions(log utilLog.Logger, path string) (*DMSOptions, error) { var opts Options if err := utilConf.ParseYamlFile(log, path, &opts); err != nil { return nil, err } - - return &opts, nil -} - -func (o *Options) GetAPIServer() *APIServerOpts { - return o.APIServiceOpts -} - -func (api *APIServerOpts) GetHTTPAddr() string { - return fmt.Sprintf("%v:%v", api.HTTP.Addr, api.HTTP.Port) + optimizationEnabled = getOptimizationEnabled(&opts) + return &opts.DMS, nil } diff --git a/internal/apiserver/conf/options_ce.go b/internal/apiserver/conf/options_ce.go new file mode 100644 index 000000000..540b204a8 --- /dev/null +++ b/internal/apiserver/conf/options_ce.go @@ -0,0 +1,7 @@ +//go:build !enterprise + +package conf + +func getOptimizationEnabled(opt *Options) bool { + return false +} diff --git a/internal/apiserver/middleware/jwt.go b/internal/apiserver/middleware/jwt.go new file mode 100644 index 000000000..3118be926 --- /dev/null +++ b/internal/apiserver/middleware/jwt.go @@ -0,0 +1,24 @@ +package middleware + +import ( + "fmt" + "strings" + + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" +) + +// JWTTokenAdapter is a `echo` middleware, by rewriting the header, the jwt token support header +// "Authorization: {token}" and "Authorization: Bearer {token}". +func JWTTokenAdapter() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + auth := c.Request().Header.Get(echo.HeaderAuthorization) + if auth != "" && !strings.HasPrefix(auth, middleware.DefaultJWTConfig.AuthScheme) { + c.Request().Header.Set(echo.HeaderAuthorization, + fmt.Sprintf("%s %s", middleware.DefaultJWTConfig.AuthScheme, auth)) + } + return next(c) + } + } +} diff --git a/internal/apiserver/middleware/license.go b/internal/apiserver/middleware/license.go new file mode 100644 index 000000000..da46f8bc7 --- /dev/null +++ b/internal/apiserver/middleware/license.go @@ -0,0 +1,11 @@ +package middleware + +import ( + "github.com/actiontech/dms/internal/dms/biz" + "github.com/labstack/echo/v4" +) + +func LicenseAdapter(l *biz.LicenseUsecase) echo.MiddlewareFunc { + //nolint:typecheck + return licenseAdapter(l) +} diff --git a/internal/apiserver/middleware/license_qa.go b/internal/apiserver/middleware/license_qa.go new file mode 100644 index 000000000..53b7f4060 --- /dev/null +++ b/internal/apiserver/middleware/license_qa.go @@ -0,0 +1,17 @@ +//go:build !release +// +build !release + +package middleware + +import ( + "github.com/actiontech/dms/internal/dms/biz" + "github.com/labstack/echo/v4" +) + +func licenseAdapter(l *biz.LicenseUsecase) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + return next(c) + } + } +} diff --git a/internal/apiserver/middleware/operation_record.go b/internal/apiserver/middleware/operation_record.go new file mode 100644 index 000000000..f00e8f3bf --- /dev/null +++ b/internal/apiserver/middleware/operation_record.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "strings" + + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + "github.com/labstack/echo/v4" +) + +type ApiInterfaceInfo struct { + RouterPath string + Method string + OperationType string + OperationAction string + GetProjectAndContentFunc func(c echo.Context, dms interface{}) (projectName string, content i18nPkg.I18nStr, err error) +} + +var ApiInterfaceInfoList []ApiInterfaceInfo + +func pathMatch(pattern, path string) bool { + ps := strings.Split(strings.Trim(pattern, "/"), "/") + pathSegs := strings.Split(strings.Trim(path, "/"), "/") + if len(ps) != len(pathSegs) { + return false + } + for i := range ps { + if len(ps[i]) > 0 && ps[i][0] == ':' { + continue + } + if ps[i] != pathSegs[i] { + return false + } + } + return true +} diff --git a/internal/apiserver/middleware/operation_record_ce.go b/internal/apiserver/middleware/operation_record_ce.go new file mode 100644 index 000000000..ae6c1ba3d --- /dev/null +++ b/internal/apiserver/middleware/operation_record_ce.go @@ -0,0 +1,14 @@ +//go:build !enterprise + +package middleware + +import ( + "github.com/actiontech/dms/internal/dms/service" + "github.com/labstack/echo/v4" +) + +func OperationRecordMiddleware(_ *service.DMSService) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return next + } +} diff --git a/internal/apiserver/service/cloudbeaver_controller.go b/internal/apiserver/service/cloudbeaver_controller.go deleted file mode 100644 index bec0c9fc2..000000000 --- a/internal/apiserver/service/cloudbeaver_controller.go +++ /dev/null @@ -1,54 +0,0 @@ -package service - -import ( - "fmt" - - "github.com/actiontech/dms/internal/apiserver/conf" - apiError "github.com/actiontech/dms/internal/apiserver/pkg/error" - "github.com/actiontech/dms/internal/dms/service" - - utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" - "github.com/labstack/echo/v4" -) - -type CloudbeaverController struct { - CloudbeaverService *service.CloudbeaverService - - shutdownCallback func() error -} - -func NewCloudbeaverController(logger utilLog.Logger, opts *conf.Options) (*CloudbeaverController, error) { - cloudbeaverService, err := service.NewAndInitCloudbeaverService(logger, opts) - if nil != err { - return nil, fmt.Errorf("failed to init cloudbeaver service: %v", err) - } - - return &CloudbeaverController{ - CloudbeaverService: cloudbeaverService, - shutdownCallback: func() error { - return nil - }, - }, nil -} - -func (cc *CloudbeaverController) Shutdown() error { - if nil != cc.shutdownCallback { - return cc.shutdownCallback() - } - return nil -} - -// swagger:route GET /v1/dms/configurations/sql_query cloudbeaver GetSQLQueryConfiguration -// -// get sql_query configuration. -// -// responses: -// 200: body:GetSQLQueryConfigurationReply -// default: body:GenericResp -func (cc *CloudbeaverController) GetSQLQueryConfiguration(c echo.Context) error { - reply, err := cc.CloudbeaverService.GetCloudbeaverConfiguration(c.Request().Context()) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) - } - return NewOkRespWithReply(c, reply) -} diff --git a/internal/apiserver/service/cron.go b/internal/apiserver/service/cron.go new file mode 100644 index 000000000..962272943 --- /dev/null +++ b/internal/apiserver/service/cron.go @@ -0,0 +1,86 @@ +package service + +import ( + "context" + "time" + + commonLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +var cronManagerMap = map[string]cronImpl{} + +const ( + DatabaseSourceService = "database_source_service" +) + +type cronImpl interface { + start(server *APIServer, groupCtx context.Context) + stop() +} + +func init() { + ctx, cancel := context.WithCancel(context.Background()) + + cronManagerMap[DatabaseSourceService] = &databaseSourceServiceCronManager{ + ctx: ctx, + cancel: cancel, + } +} + +func StartAllCronJob(server *APIServer, groupCtx context.Context) { + for _, manager := range cronManagerMap { + manager.start(server, groupCtx) + } +} + +func StopAllCronJob() { + for _, manager := range cronManagerMap { + manager.stop() + } +} + +const CronManager = "dms.cronmanager" + +type databaseSourceServiceCronManager struct { + apiServer *APIServer + ctx context.Context + cancel context.CancelFunc +} + +func (c *databaseSourceServiceCronManager) start(server *APIServer, groupCtx context.Context) { + c.apiServer = server + + go func() { + logger := commonLog.NewHelper(c.apiServer.logger, commonLog.WithMessageKey(CronManager)) + logger.Info("cron start") + + ticker := time.NewTicker(5 * time.Second) + for range ticker.C { + // loop, wait apiServer initial + if c.apiServer.DMSController != nil { + break + } + } + + ticker.Stop() + + c.apiServer.DMSController.DMS.DBServiceSyncTaskUsecase.StartSyncDBServiceSyncTask() + + select { + case <-groupCtx.Done(): + logger.Infof("cron terminal, err: %s", groupCtx.Err()) + + c.apiServer.DMSController.DMS.DBServiceSyncTaskUsecase.StopSyncDBServiceSyncTask() + return + case <-c.ctx.Done(): + logger.Infof("cron terminal, err: %s", groupCtx.Err()) + + c.apiServer.DMSController.DMS.DBServiceSyncTaskUsecase.StopSyncDBServiceSyncTask() + return + } + }() +} + +func (c *databaseSourceServiceCronManager) stop() { + c.cancel() +} diff --git a/internal/apiserver/service/data_mask_controller.go b/internal/apiserver/service/data_mask_controller.go new file mode 100644 index 000000000..1a13b3987 --- /dev/null +++ b/internal/apiserver/service/data_mask_controller.go @@ -0,0 +1,739 @@ +package service + +import ( + aV1 "github.com/actiontech/dms/api/dms/service/v1" + apiError "github.com/actiontech/dms/internal/apiserver/pkg/error" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/labstack/echo/v4" +) + +// swagger:operation GET /v1/dms/masking/rules Masking ListMaskingRules +// +// List masking rules. +// +// --- +// responses: +// '200': +// description: List masking rules successfully +// schema: +// "$ref": "#/definitions/ListMaskingRulesReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListMaskingRules(c echo.Context) error { + req := &aV1.ListMaskingRulesReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListMaskingRules(c.Request().Context()) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/templates Masking ListMaskingTemplates +// +// List masking templates. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: page_size +// description: the maximum count of masking templates to be returned, default is 20 +// in: query +// required: false +// type: integer +// format: uint32 +// - name: page_index +// description: the offset of masking templates to be returned, default is 0 +// in: query +// required: false +// type: integer +// format: uint32 +// +// responses: +// '200': +// description: List masking templates successfully +// schema: +// "$ref": "#/definitions/ListMaskingTemplatesReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListMaskingTemplates(c echo.Context) error { + req := &aV1.ListMaskingTemplatesReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListMaskingTemplates(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/masking/templates Masking AddMaskingTemplate +// +// Add masking template. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: masking_template +// description: masking template info +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddMaskingTemplateReq" +// +// responses: +// '200': +// description: Add masking template successfully +// schema: +// "$ref": "#/definitions/AddMaskingTemplateReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddMaskingTemplate(c echo.Context) error { + req := &aV1.AddMaskingTemplateReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + if err := ctl.DMS.AddMaskingTemplate(c.Request().Context(), req); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, &aV1.AddMaskingTemplateReply{}) +} + +// swagger:operation PUT /v1/dms/projects/{project_uid}/masking/templates/{template_id} Masking UpdateMaskingTemplate +// +// Update masking template. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: template_id +// description: masking template id +// in: path +// required: true +// type: integer +// - name: masking_template +// description: masking template info +// in: body +// required: true +// schema: +// "$ref": "#/definitions/UpdateMaskingTemplateReq" +// +// responses: +// '200': +// description: Update masking template successfully +// schema: +// "$ref": "#/definitions/UpdateMaskingTemplateReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateMaskingTemplate(c echo.Context) error { + req := &aV1.UpdateMaskingTemplateReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + if err := ctl.DMS.UpdateMaskingTemplate(c.Request().Context(), req); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, &aV1.UpdateMaskingTemplateReply{}) +} + +// swagger:operation DELETE /v1/dms/projects/{project_uid}/masking/templates/{template_id} Masking DeleteMaskingTemplate +// +// Delete masking template. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: template_id +// description: masking template id +// in: path +// required: true +// type: integer +// +// responses: +// '200': +// description: Delete masking template successfully +// schema: +// "$ref": "#/definitions/DeleteMaskingTemplateReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) DeleteMaskingTemplate(c echo.Context) error { + req := &aV1.DeleteMaskingTemplateReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + if err := ctl.DMS.DeleteMaskingTemplate(c.Request().Context(), req); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, &aV1.DeleteMaskingTemplateReply{}) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/creatable-db-services Masking ListCreatableDBServicesForMaskingTask +// +// List db services that can create sensitive data discovery task. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: page_size +// description: the maximum count of db services to be returned, default is 100 +// in: query +// required: false +// type: integer +// format: uint32 +// - name: page_index +// description: the offset of db services to be returned, default is 0 +// in: query +// required: false +// type: integer +// format: uint32 +// - name: keywords +// description: fuzzy search keywords for db service name +// in: query +// required: false +// type: string +// +// responses: +// '200': +// description: List creatable db services for masking task successfully +// schema: +// "$ref": "#/definitions/ListCreatableDBServicesForMaskingTaskReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListCreatableDBServicesForMaskingTask(c echo.Context) error { + req := &aV1.ListCreatableDBServicesForMaskingTaskReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.ListCreatableDBServicesForMaskingTask(c.Request().Context(), req, currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks Masking ListSensitiveDataDiscoveryTasks +// +// List sensitive data discovery tasks. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: page_size +// description: the maximum count of tasks to be returned, default is 20 +// in: query +// required: false +// type: integer +// format: uint32 +// - name: page_index +// description: the offset of tasks to be returned, default is 0 +// in: query +// required: false +// type: integer +// format: uint32 +// +// responses: +// '200': +// description: List sensitive data discovery tasks successfully +// schema: +// "$ref": "#/definitions/ListSensitiveDataDiscoveryTasksReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListSensitiveDataDiscoveryTasks(c echo.Context) error { + req := &aV1.ListSensitiveDataDiscoveryTasksReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListSensitiveDataDiscoveryTasks(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks Masking AddSensitiveDataDiscoveryTask +// +// Add sensitive data discovery task. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: task +// description: sensitive data discovery task info +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddSensitiveDataDiscoveryTaskReq" +// +// responses: +// '200': +// description: Add sensitive data discovery task successfully +// schema: +// "$ref": "#/definitions/AddSensitiveDataDiscoveryTaskReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddSensitiveDataDiscoveryTask(c echo.Context) error { + req := &aV1.AddSensitiveDataDiscoveryTaskReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.AddSensitiveDataDiscoveryTask(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PUT /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/{task_id} Masking UpdateSensitiveDataDiscoveryTask +// +// Update sensitive data discovery task. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: task_id +// description: sensitive data discovery task id +// in: path +// required: true +// type: integer +// - name: task +// description: sensitive data discovery task info +// in: body +// required: true +// schema: +// "$ref": "#/definitions/UpdateSensitiveDataDiscoveryTaskReq" +// +// responses: +// '200': +// description: Update sensitive data discovery task successfully +// schema: +// "$ref": "#/definitions/UpdateSensitiveDataDiscoveryTaskReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateSensitiveDataDiscoveryTask(c echo.Context) error { + req := &aV1.UpdateSensitiveDataDiscoveryTaskReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.UpdateSensitiveDataDiscoveryTask(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation DELETE /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/{task_id} Masking DeleteSensitiveDataDiscoveryTask +// +// Delete sensitive data discovery task. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: task_id +// description: sensitive data discovery task id +// in: path +// required: true +// type: integer +// +// responses: +// '200': +// description: Delete sensitive data discovery task successfully +// schema: +// "$ref": "#/definitions/DeleteSensitiveDataDiscoveryTaskReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) DeleteSensitiveDataDiscoveryTask(c echo.Context) error { + req := &aV1.DeleteSensitiveDataDiscoveryTaskReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + if err := ctl.DMS.DeleteSensitiveDataDiscoveryTask(c.Request().Context(), req); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, &aV1.DeleteSensitiveDataDiscoveryTaskReply{}) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/sensitive-data-discovery-tasks/{task_id}/histories Masking ListSensitiveDataDiscoveryTaskHistories +// +// List sensitive data discovery task histories. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: task_id +// description: sensitive data discovery task id +// in: path +// required: true +// type: integer +// - name: page_size +// description: the maximum count of histories to be returned, default is 20 +// in: query +// required: false +// type: integer +// format: uint32 +// - name: page_index +// description: the offset of histories to be returned, default is 0 +// in: query +// required: false +// type: integer +// format: uint32 +// +// responses: +// '200': +// description: List sensitive data discovery task histories successfully +// schema: +// "$ref": "#/definitions/ListSensitiveDataDiscoveryTaskHistoriesReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListSensitiveDataDiscoveryTaskHistories(c echo.Context) error { + req := &aV1.ListSensitiveDataDiscoveryTaskHistoriesReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListSensitiveDataDiscoveryTaskHistories(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PUT /v1/dms/projects/{project_uid}/masking/rule-configs Masking ConfigureMaskingRules +// +// Configure masking rules in batch. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: masking_rule_configs_req +// description: masking rule configurations for batch create or update +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ConfigureMaskingRulesReq" +// +// responses: +// '200': +// description: Configure masking rules successfully +// schema: +// "$ref": "#/definitions/ConfigureMaskingRulesReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ConfigureMaskingRules(c echo.Context) error { + req := &aV1.ConfigureMaskingRulesReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + if err := ctl.DMS.ConfigureMaskingRules(c.Request().Context(), req, currentUserUid); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, &aV1.ConfigureMaskingRulesReply{}) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/overview Masking GetMaskingOverviewTree +// +// Get masking overview tree. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: db_service_uid +// description: data source id +// in: query +// required: true +// type: string +// - name: keywords +// description: fuzzy search keyword for database name, table name, and column name +// in: query +// required: false +// type: string +// - name: masking_config_statuses +// description: "masking config status filters, enum: CONFIGURED/PENDING_CONFIRM" +// in: query +// required: false +// type: string +// +// responses: +// '200': +// description: Get masking overview tree successfully +// schema: +// "$ref": "#/definitions/GetMaskingOverviewTreeReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) GetMaskingOverviewTree(c echo.Context) error { + req := &aV1.GetMaskingOverviewTreeReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.UnauthorizedErr) + } + + reply, err := ctl.DMS.GetMaskingOverviewTree(c.Request().Context(), req, currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/tables/{table_id}/column-masking-details Masking GetTableColumnMaskingDetails +// +// Get table column masking details. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: table_id +// description: table id from masking overview tree +// in: path +// required: true +// type: integer +// - name: keywords +// description: fuzzy search keyword for column name +// in: query +// required: false +// type: string +// +// responses: +// '200': +// description: Get table column masking details successfully +// schema: +// "$ref": "#/definitions/GetTableColumnMaskingDetailsReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) GetTableColumnMaskingDetails(c echo.Context) error { + req := &aV1.GetTableColumnMaskingDetailsReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.GetTableColumnMaskingDetails(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/approval-requests/pending Masking ListPendingApprovalRequests +// +// List pending approval requests. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: page_size +// description: the maximum count of requests to be returned, default is 20 +// in: query +// required: false +// type: integer +// format: uint32 +// - name: page_index +// description: the offset of requests to be returned, default is 0 +// in: query +// required: false +// type: integer +// format: uint32 +// +// responses: +// '200': +// description: List pending approval requests successfully +// schema: +// "$ref": "#/definitions/ListPendingApprovalRequestsReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListPendingApprovalRequests(c echo.Context) error { + req := &aV1.ListPendingApprovalRequestsReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + return NewOkRespWithReply(c, &aV1.ListPendingApprovalRequestsReply{}) +} + +// swagger:operation GET /v1/dms/projects/{project_uid}/masking/approval-requests/{request_id} Masking GetPlaintextAccessRequestDetail +// +// Get plaintext access request detail. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: request_id +// description: approval request id +// in: path +// required: true +// type: integer +// +// responses: +// '200': +// description: Get plaintext access request detail successfully +// schema: +// "$ref": "#/definitions/GetPlaintextAccessRequestDetailReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) GetPlaintextAccessRequestDetail(c echo.Context) error { + req := &aV1.GetPlaintextAccessRequestDetailReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + return NewOkRespWithReply(c, &aV1.GetPlaintextAccessRequestDetailReply{}) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/masking/approval-requests/{request_id}/decisions Masking ProcessApprovalRequest +// +// Process approval request. +// +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: request_id +// description: approval request id +// in: path +// required: true +// type: integer +// - name: action +// description: process action info +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ProcessApprovalRequestReq" +// +// responses: +// '200': +// description: Process approval request successfully +// schema: +// "$ref": "#/definitions/ProcessApprovalRequestReply" +// default: +// description: Generic error response +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ProcessApprovalRequest(c echo.Context) error { + req := &aV1.ProcessApprovalRequestReq{} + if err := bindAndValidateReq(c, req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + return NewOkRespWithReply(c, &aV1.ProcessApprovalRequestReply{}) +} diff --git a/internal/apiserver/service/dms_controller.go b/internal/apiserver/service/dms_controller.go index 4d01331fa..5582b58ed 100644 --- a/internal/apiserver/service/dms_controller.go +++ b/internal/apiserver/service/dms_controller.go @@ -1,19 +1,35 @@ package service import ( + "bytes" + "context" + "encoding/json" "errors" "fmt" + "io" + "mime" "net/http" + "net/http/httputil" + "net/url" + "path/filepath" + "strings" "time" + "github.com/actiontech/dms/api" aV1 "github.com/actiontech/dms/api/dms/service/v1" "github.com/actiontech/dms/internal/apiserver/conf" apiError "github.com/actiontech/dms/internal/apiserver/pkg/error" + "github.com/actiontech/dms/internal/dms/biz" "github.com/actiontech/dms/internal/dms/pkg/constant" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" "github.com/actiontech/dms/internal/dms/service" + "github.com/actiontech/dms/internal/pkg/locale" + "github.com/labstack/echo/v4/middleware" + echoSwagger "github.com/swaggo/echo-swagger" dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" "github.com/actiontech/dms/pkg/dms-common/api/jwt" + i18nPkg "github.com/actiontech/dms/pkg/dms-common/i18nPkg" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" @@ -21,19 +37,23 @@ import ( ) type DMSController struct { - DMS *service.DMSService + DMS *service.DMSService + CloudbeaverService *service.CloudbeaverService + log *utilLog.Helper shutdownCallback func() error } -func NewDMSController(logger utilLog.Logger, opts *conf.Options) (*DMSController, error) { +func NewDMSController(logger utilLog.Logger, opts *conf.DMSOptions, cbService *service.CloudbeaverService) (*DMSController, error) { dmsService, err := service.NewAndInitDMSService(logger, opts) if nil != err { return nil, fmt.Errorf("failed to init dms service: %v", err) } return &DMSController{ // log: log.NewHelper(log.With(logger, "module", "controller/DMS")), - DMS: dmsService, + DMS: dmsService, + CloudbeaverService: cbService, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("controller")), shutdownCallback: func() error { if err := dmsService.Shutdown(); err != nil { return err @@ -43,22 +63,41 @@ func NewDMSController(logger utilLog.Logger, opts *conf.Options) (*DMSController }, nil } -func (a *DMSController) Shutdown() error { - if nil != a.shutdownCallback { - return a.shutdownCallback() +func (ctl *DMSController) Shutdown() error { + if nil != ctl.shutdownCallback { + return ctl.shutdownCallback() } return nil } -// swagger:route POST /v1/dms/db_services dms AddDBService + +// swagger:operation POST /v1/dms/projects/{project_uid}/environment_tags Project CreateEnvironmentTag // -// Add DB Service. +// Create a new environment tag. // -// responses: -// 200: body:AddDBServiceReply -// default: body:GenericResp -func (d *DMSController) AddDBService(c echo.Context) error { - req := new(aV1.AddDBServiceReq) +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: environment_name +// description: the name of environment tag to be created +// in: body +// required: true +// type: string +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CreateEnvironmentTag(c echo.Context) error { + req := new(aV1.CreateEnvironmentTagReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) @@ -70,191 +109,140 @@ func (d *DMSController) AddDBService(c echo.Context) error { return NewErrResp(c, err, apiError.DMSServiceErr) } - reply, err := d.DMS.AddDBService(c.Request().Context(), req, currentUserUid) + err = ctl.DMS.CreateEnvironmentTag(c.Request().Context(), req.ProjectUID, currentUserUid, req.Name) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) -} -// swagger:route GET /v1/dms/db_services dms ListDBServices -// -// List db service. -// -// responses: -// 200: body:ListDBServiceReply -// default: body:GenericResp -func (d *DMSController) ListDBServices(c echo.Context) error { - req := new(aV1.ListDBServiceReq) - err := bindAndValidateReq(c, req) - if nil != err { - return NewErrResp(c, err, apiError.BadRequestErr) - } - currentUserUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - reply, err := d.DMS.ListDBServices(c.Request().Context(), req, currentUserUid) - if nil != err { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - return NewOkRespWithReply(c, reply) + return NewOkResp(c) } -// swagger:route DELETE /v1/dms/db_services/{db_service_uid} dms DelDBService +// swagger:operation PUT /v1/dms/projects/{project_uid}/environment_tags/{environment_tag_uid} Project UpdateEnvironmentTag // -// Delete a DB Service. +// Update an existing environment tag. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (a *DMSController) DelDBService(c echo.Context) error { - req := &aV1.DelDBServiceReq{} +// --- +// parameters: +// - name: project_uid +// description: project uid +// in: path +// required: true +// type: string +// - name: environment_tag_uid +// description: environment tag id +// in: path +// required: true +// type: string +// - name: environment_name +// description: the name of environment tag to be updated +// required: true +// in: body +// type: string +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateEnvironmentTag(c echo.Context) error { + req := new(aV1.UpdateEnvironmentTagReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = a.DMS.DelDBService(c.Request().Context(), req, currentUserUid) + + err = ctl.DMS.UpdateEnvironmentTag(c.Request().Context(), req.ProjectUID, currentUserUid, req.EnvironmentTagUID, req.Name) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route PUT /v1/dms/db_services/{db_service_uid} dms UpdateDBService +// swagger:route DELETE /v1/dms/projects/{project_uid}/environment_tags/{environment_tag_uid} Project DeleteEnvironmentTag // -// update a DB Service. +// Delete an existing environment tag. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (a *DMSController) UpdateDBService(c echo.Context) error { - req := &aV1.UpdateDBServiceReq{} +func (ctl *DMSController) DeleteEnvironmentTag(c echo.Context) error { + req := new(aV1.DeleteEnvironmentTagReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = a.DMS.UpdateDBService(c.Request().Context(), req, currentUserUid) - if nil != err { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - return NewOkResp(c) -} - -// swagger:route POST /v1/dms/db_services/connect dms CheckDBServiceIsConnectable -// -// check if the db_service is connectable. -// -// responses: -// 200: body:CheckDBServiceIsConnectableReply -// default: body:GenericResp -func (d *DMSController) CheckDBServiceIsConnectable(c echo.Context) error { - var req aV1.CheckDBServiceIsConnectableReq - err := bindAndValidateReq(c, &req) - if nil != err { - return NewErrResp(c, err, apiError.BadRequestErr) - } - reply, err := d.DMS.CheckDBServiceIsConnectable(c.Request().Context(), &req) + err = ctl.DMS.DeleteEnvironmentTag(c.Request().Context(), req.ProjectUID, currentUserUid, req.EnvironmentTagUID) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) + return NewOkResp(c) } -// swagger:route POST /v1/dms/sessions dms AddSession +// swagger:route GET /v1/dms/projects/{project_uid}/environment_tags Project ListEnvironmentTags // -// Add a session. +// List environment tags. // // responses: -// 200: body:AddSessionReply +// 200: body:ListEnvironmentTagsReply // default: body:GenericResp -func (a *DMSController) AddSession(c echo.Context) error { - req := new(aV1.AddSessionReq) +func (ctl *DMSController) ListEnvironmentTags(c echo.Context) error{ + req := new(aV1.ListEnvironmentTagReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := a.DMS.VerifyUserLogin(c.Request().Context(), &aV1.VerifyUserLoginReq{ - UserName: req.Session.UserName, - Password: req.Session.Password, - }) - if nil != err { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - if reply.Payload.VerifyFailedMsg != "" { - return NewErrResp(c, errors.New(reply.Payload.VerifyFailedMsg), apiError.BadRequestErr) - } - - // Create token with claims - token, err := jwt.GenJwtToken(reply.Payload.UserUid) - if nil != err { - return NewErrResp(c, err, apiError.APIServerErr) - } - - err = a.DMS.AfterUserLogin(c.Request().Context(), &aV1.AfterUserLoginReq{ - UserUid: reply.Payload.UserUid, - }) - if nil != err { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - - c.SetCookie(&http.Cookie{ - Name: constant.DMSToken, - Value: token, - Path: "/", - Expires: time.Now().Add(24 * time.Hour), - }) - - return NewOkRespWithReply(c, &aV1.AddSessionReply{ - Payload: struct { - UserUid string `json:"user_uid"` - Token string `json:"token"` - }{ - UserUid: reply.Payload.UserUid, - Token: token, - }, - }) -} - -// swagger:route GET /v1/dms/sessions/user dms GetUserBySession -// -// Get current user. -// -// responses: -// 200: body:GetUserBySessionReply -// default: body:GenericResp -func (a *DMSController) GetUserBySession(c echo.Context) error { - uid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { - return NewErrResp(c, err, apiError.BadRequestErr) - } - reply, err := a.DMS.GetCurrentUser(c.Request().Context(), &aV1.GetUserBySessionReq{UserUid: uid}) + reply, err := ctl.DMS.ListEnvironmentTags(c.Request().Context(), req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/users dms AddUser +// swagger:operation POST /v1/dms/projects/{project_uid}/db_services DBService AddDBService // -// Add user. +// Add DB Service. // -// responses: -// 200: body:AddUserReply -// default: body:GenericResp -func (d *DMSController) AddUser(c echo.Context) error { - req := new(aV1.AddUserReq) +// --- +// deprecated: true +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_service +// description: Add new db service +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddDBServiceReq" +// responses: +// '200': +// description: AddDBServiceReply +// schema: +// "$ref": "#/definitions/AddDBServiceReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddDBService(c echo.Context) error { + req := new(aV1.AddDBServiceReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) @@ -266,437 +254,844 @@ func (d *DMSController) AddUser(c echo.Context) error { return NewErrResp(c, err, apiError.DMSServiceErr) } - reply, err := d.DMS.AddUser(c.Request().Context(), currentUserUid, req) + reply, err := ctl.DMS.AddDBService(c.Request().Context(), req, currentUserUid) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route PUT /v1/dms/users/{user_uid} dms UpdateUser +// swagger:route GET /v1/dms/projects/{project_uid}/db_services DBService ListDBServices // -// Update a user. +// List db service. // // responses: -// 200: body:GenericResp +// 200: body:ListDBServiceReply // default: body:GenericResp -func (d *DMSController) UpdateUser(c echo.Context) error { - req := new(aV1.UpdateUserReq) - err := bindAndValidateReq(c, req) - if nil != err { - return NewErrResp(c, err, apiError.BadRequestErr) - } - - // get current user id - currentUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - - err = d.DMS.UpdateUser(c.Request().Context(), req, currentUid) - if nil != err { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - return NewOkResp(c) +// deprecated: true +func (ctl *DMSController) ListDBServices(c echo.Context) error { + return NewOkRespWithReply(c, nil) } -// swagger:route DELETE /v1/dms/users/{user_uid} dms DelUser +// swagger:route GET /v1/dms/projects/{project_uid}/db_services/tips DBService ListDBServiceTips // -// Delete a user. +// List db service tip. // // responses: -// 200: body:GenericResp +// 200: body:ListDBServiceTipsReply // default: body:GenericResp -func (a *DMSController) DelUser(c echo.Context) error { - req := &aV1.DelUserReq{} +func (ctl *DMSController) ListDBServiceTips(c echo.Context) error { + req := new(aV1.ListDBServiceTipsReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - - err = a.DMS.DelUser(c.Request().Context(), currentUserUid, req) - if nil != err { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - return NewOkResp(c) -} - -// swagger:route GET /v1/dms/users dms ListUsers -// -// List users. -// -// responses: -// 200: body:ListUserReply -// default: body:GenericResp -func (d *DMSController) ListUsers(c echo.Context) error { - req := new(dmsV1.ListUserReq) - err := bindAndValidateReq(c, req) - if nil != err { - return NewErrResp(c, err, apiError.BadRequestErr) - } - - reply, err := d.DMS.ListUsers(c.Request().Context(), req) + reply, err := ctl.DMS.ListDBServiceTips(c.Request().Context(), req, currentUserUid) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/users/{user_uid}/op_permission dms GetUserOpPermission +// swagger:route GET /v1/dms/db_services/driver_options DBService ListDBServiceDriverOption // -// Get user op permission info, This API is used by other component such as sqle&auth to check user permissions. +// List db service driver option. // // responses: -// 200: body:GetUserOpPermissionReply +// 200: body:ListDBServiceDriverOptionReply // default: body:GenericResp -func (a *DMSController) GetUserOpPermission(c echo.Context) error { - req := new(dmsV1.GetUserOpPermissionReq) - err := bindAndValidateReq(c, req) - if nil != err { - return NewErrResp(c, err, apiError.BadRequestErr) - } - reply, err := a.DMS.GetUserOpPermission(c.Request().Context(), req) +func (ctl *DMSController) ListDBServiceDriverOption(c echo.Context) error { + reply, err := ctl.DMS.ListDBServiceDriverOption(c.Request().Context()) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/users/{user_uid} dms GetUser +// swagger:route GET /v1/dms/db_services DBService ListGlobalDBServices // -// Get user info, This API is used by other component such as sqle&auth to get user info. +// list global DBServices // // responses: -// 200: body:GetUserReply +// 200: body:ListGlobalDBServicesReply // default: body:GenericResp -func (a *DMSController) GetUser(c echo.Context) error { - req := new(dmsV1.GetUserReq) - err := bindAndValidateReq(c, req) - if nil != err { - return NewErrResp(c, err, apiError.BadRequestErr) - } - reply, err := a.DMS.GetUser(c.Request().Context(), req) - if nil != err { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - return NewOkRespWithReply(c, reply) +// deprecated: true +func (ctl *DMSController) ListGlobalDBServices(c echo.Context) error { + return NewOkRespWithReply(c, nil) } -// swagger:route POST /v1/dms/user_groups dms AddUserGroup +// swagger:route GET /v1/dms/db_services/tips DBService ListGlobalDBServicesTips // -// Add user group. +// list global DBServices tips // // responses: -// 200: body:AddUserGroupReply +// 200: body:ListGlobalDBServicesTipsReply // default: body:GenericResp -func (d *DMSController) AddUserGroup(c echo.Context) error { - req := new(aV1.AddUserGroupReq) +func (ctl *DMSController) ListGlobalDBServicesTips(c echo.Context) error { + req := new(aV1.ListGlobalDBServicesTipsReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - - reply, err := d.DMS.AddUserGroup(c.Request().Context(), currentUserUid, req) + reply, err := ctl.DMS.ListGlobalDBServicesTips(c.Request().Context(), req, currentUserUid) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route PUT /v1/dms/user_groups/{user_group_uid} dms UpdateUserGroup +// swagger:route DELETE /v1/dms/projects/{project_uid}/db_services/{db_service_uid} DBService DelDBService // -// Update a user group. +// Delete a DB Service. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (d *DMSController) UpdateUserGroup(c echo.Context) error { - req := new(aV1.UpdateUserGroupReq) +func (ctl *DMSController) DelDBService(c echo.Context) error { + req := &aV1.DelDBServiceReq{} err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - - err = d.DMS.UpdateUserGroup(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.DelDBService(c.Request().Context(), req, currentUserUid) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route DELETE /v1/dms/user_groups/{user_group_uid} dms DelUserGroup +// swagger:operation PUT /v1/dms/projects/{project_uid}/db_services/{db_service_uid} DBService UpdateDBService // -// Delete a user group. +// update a DB Service. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (a *DMSController) DelUserGroup(c echo.Context) error { - req := &aV1.DelUserGroupReq{} - err := bindAndValidateReq(c, req) +// --- +// deprecated: true +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_service_uid +// description: db_service_uid id +// in: path +// required: true +// type: string +// - name: db_service +// description: Update a DB service +// in: body +// schema: +// "$ref": "#/definitions/UpdateDBServiceReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateDBService(c echo.Context) error { + + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/db_services/connection DBService CheckDBServiceIsConnectable +// +// check if the db_service is connectable. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_service +// in: body +// description: check db_service is connectable +// schema: +// "$ref": "#/definitions/CheckDBServiceIsConnectableReq" +// responses: +// '200': +// description: CheckDBServiceIsConnectableReply +// schema: +// "$ref": "#/definitions/CheckDBServiceIsConnectableReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CheckDBServiceIsConnectable(c echo.Context) error { + var req aV1.CheckDBServiceIsConnectableReq + err := bindAndValidateReq(c, &req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - // get current user id - currentUserUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { - return NewErrResp(c, err, apiError.DMSServiceErr) - } - - err = a.DMS.DelUserGroup(c.Request().Context(), currentUserUid, req) + reply, err := ctl.DMS.CheckDBServiceIsConnectable(c.Request().Context(), &req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) + return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/user_groups dms ListUserGroups +// swagger:operation POST /v1/dms/projects/{project_uid}/db_services/{db_service_uid}/connection DBService CheckDBServiceIsConnectableById // -// List user groups. +// check if the db_service is connectable. // -// responses: -// 200: body:ListUserGroupReply -// default: body:GenericResp -func (d *DMSController) ListUserGroups(c echo.Context) error { - req := new(aV1.ListUserGroupReq) - err := bindAndValidateReq(c, req) +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_service_uid +// description: db service uid +// in: path +// required: true +// type: string +// responses: +// '200': +// description: CheckDBServiceIsConnectableReply +// schema: +// "$ref": "#/definitions/CheckDBServiceIsConnectableReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CheckDBServiceIsConnectableById(c echo.Context) error { + var req aV1.CheckDBServiceIsConnectableByIdReq + err := bindAndValidateReq(c, &req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.ListUserGroups(c.Request().Context(), req) + reply, err := ctl.DMS.CheckDBServiceIsConnectableById(c.Request().Context(), &req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/roles dms AddRole +// swagger:operation POST /v1/dms/projects/{project_uid}/db_services/connections DBService CheckProjectDBServicesConnections // -// Add role. +// check if the project db_services is connectable. // -// responses: -// 200: body:AddRoleReply -// default: body:GenericResp -func (d *DMSController) AddRole(c echo.Context) error { - req := new(aV1.AddRoleReq) - err := bindAndValidateReq(c, req) +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_services +// description: check db_services is connectable +// in: body +// schema: +// "$ref": "#/definitions/CheckDBServicesIsConnectableReq" +// responses: +// '200': +// description: CheckDBServicesIsConnectableReply +// schema: +// "$ref": "#/definitions/CheckDBServicesIsConnectableReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CheckProjectDBServicesConnections(c echo.Context) error { + var req aV1.CheckDBServicesIsConnectableReq + err := bindAndValidateReq(c, &req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - reply, err := d.DMS.AddRole(c.Request().Context(), currentUserUid, req) + reply, err := ctl.DMS.CheckDBServiceIsConnectableByIds(c.Request().Context(), req.ProjectUid,currentUserUid,req.DBServices) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } + return NewOkRespWithReply(c, reply) } -// swagger:route PUT /v1/dms/roles/{role_uid} dms UpdateRole + +// swagger:route GET /v1/dms/basic_info BasicInfo GetBasicInfo // -// Update a role. +// get basic info. // // responses: -// 200: body:GenericResp +// 200: body:GetBasicInfoReply // default: body:GenericResp -func (d *DMSController) UpdateRole(c echo.Context) error { - req := new(aV1.UpdateRoleReq) - err := bindAndValidateReq(c, req) +func (ctl *DMSController) GetBasicInfo(c echo.Context) error { + reply, err := ctl.DMS.GetBasicInfo(c.Request().Context()) if nil != err { - return NewErrResp(c, err, apiError.BadRequestErr) - } - - // get current user id - currentUserUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } + return NewOkRespWithReply(c, reply) +} - err = d.DMS.UpdateRole(c.Request().Context(), currentUserUid, req) +// swagger:route GET /v1/dms/personalization/logo BasicInfo GetStaticLogo +// +// get logo +// +// Produces: +// - application/octet-stream +// +// responses: +// 200: GetStaticLogoReply +// default: body:GenericResp +func (ctl *DMSController) GetStaticLogo(c echo.Context) error { + reply, contentType, err := ctl.DMS.GetStaticLogo(c.Request().Context()) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) + + return c.Blob(http.StatusOK, contentType, reply.File) } -// swagger:route DELETE /v1/dms/roles/{role_uid} dms DelRole +// swagger:operation POST /v1/dms/personalization BasicInfo Personalization // -// Delete a role. +// personalize [title, logo]. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (a *DMSController) DelRole(c echo.Context) error { - req := &aV1.DelRoleReq{} - err := bindAndValidateReq(c, req) - if nil != err { +// --- +// parameters: +// - name: title +// description: title +// in: formData +// required: false +// type: string +// - name: file +// description: file upload +// in: formData +// required: false +// type: file +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) Personalization(c echo.Context) error { + req := &aV1.PersonalizationReq{} + + fileHeader, err := c.FormFile("file") + if err != nil && !errors.Is(err, http.ErrMissingFile) { return NewErrResp(c, err, apiError.BadRequestErr) } - // get current user id - currentUserUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { - return NewErrResp(c, err, apiError.DMSServiceErr) + req.File = fileHeader + + err = bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) } - err = a.DMS.DelRole(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.Personalization(c.Request().Context(), req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } + return NewOkResp(c) } -// swagger:route GET /v1/dms/roles dms ListRoles +// swagger:operation POST /v1/dms/users/verify_user_login User VerifyUserLogin // -// List roles. +// Verify user login. // -// responses: -// 200: body:ListRoleReply -// default: body:GenericResp -func (d *DMSController) ListRoles(c echo.Context) error { - req := new(aV1.ListRoleReq) +// --- +// parameters: +// - name: session +// in: body +// required: true +// description: Add a new session +// schema: +// "$ref": "#/definitions/AddSessionReq" +// responses: +// '200': +// description: VerifyUserLoginReply +// schema: +// "$ref": "#/definitions/VerifyUserLoginReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) VerifyUserLogin(c echo.Context) error { + req := new(aV1.AddSessionReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - - reply, err := d.DMS.ListRoles(c.Request().Context(), req) + reply, err := ctl.DMS.VerifyUserLogin(c.Request().Context(), &aV1.VerifyUserLoginReq{ + UserName: req.Session.UserName, + Password: req.Session.Password, + }) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/members dms AddMember +// swagger:operation POST /v1/dms/sessions Session AddSession // -// Add member. +// Add a session. // -// responses: -// 200: body:AddMemberReply -// default: body:GenericResp -func (d *DMSController) AddMember(c echo.Context) error { - req := new(aV1.AddMemberReq) +// --- +// parameters: +// - name: session +// in: body +// required: true +// description: Add a new session +// schema: +// "$ref": "#/definitions/AddSessionReq" +// responses: +// '200': +// description: AddSessionReply +// schema: +// "$ref": "#/definitions/AddSessionReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddSession(c echo.Context) error { + req := new(aV1.AddSessionReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - - // get current user id - currentUserUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { + reply, err := ctl.DMS.VerifyUserLogin(c.Request().Context(), &aV1.VerifyUserLoginReq{ + UserName: req.Session.UserName, + Password: req.Session.Password, + VerifyCode: req.Session.VerifyCode, + }) + if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } + if reply.Data.VerifyFailedMsg != "" { + return NewErrResp(c, errors.New(reply.Data.VerifyFailedMsg), apiError.BadRequestErr) + } + + // Create token with claims + token, err := jwt.GenJwtToken(jwt.WithUserId(reply.Data.UserUid)) + if nil != err { + return NewErrResp(c, err, apiError.APIServerErr) + } + refreshToken, err := jwt.GenRefreshToken(jwt.WithUserId(reply.Data.UserUid)) + if nil != err { + return NewErrResp(c, err, apiError.APIServerErr) + } - reply, err := d.DMS.AddMember(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.AfterUserLogin(c.Request().Context(), &aV1.AfterUserLoginReq{ + UserUid: reply.Data.UserUid, + }) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) + + c.SetCookie(&http.Cookie{ + Name: constant.DMSToken, + Value: token, + Path: "/", + Expires: time.Now().Add(jwt.DefaultDmsTokenExpHours * time.Hour), + }) + c.SetCookie(&http.Cookie{ + Name: constant.DMSRefreshToken, + Value: refreshToken, + Path: "/", + HttpOnly: true, // 增加安全性 + SameSite: http.SameSiteStrictMode, // cookie只会在同站请求中发送。 + Expires: time.Now().Add(jwt.DefaultDmsRefreshTokenExpHours * time.Hour), + }) + + // 记录登入操作 + user, err := ctl.DMS.UserUsecase.GetUser(c.Request().Context(), reply.Data.UserUid) + if err == nil { + recordReq := &aV1.AddOperationRecordReq{ + OperationRecord: &aV1.OperationRecord{ + OperationTime: time.Now(), + OperationUserName: user.Name, + OperationReqIP: c.RealIP(), + OperationUserAgent: c.Request().UserAgent(), + OperationTypeName: "user", + OperationAction: "login", + OperationProjectName: "", + OperationStatus: "succeeded", + OperationI18nContent: i18nPkg.ConvertStr2I18nAsDefaultLang(fmt.Sprintf("用户 %s 登入系统", user.Name)), + }, + } + _, err = ctl.DMS.AddOperationRecord(c.Request().Context(), recordReq) + if err != nil { + ctl.log.Errorf("failed to save login operation record: %v, operation_record: user_name=%s, ip=%s, user_agent=%s, action=login", + err, user.Name, c.RealIP(), c.Request().UserAgent()) + } + } + + return NewOkRespWithReply(c, &aV1.AddSessionReply{ + Data: struct { + Token string `json:"token"` + Message string `json:"message"` + }{ + Token: token, + }, + }) } -// swagger:route GET /v1/dms/members dms ListMembers +// swagger:route DELETE /v1/dms/sessions Session DelSession // -// List member, for front page. +// del a session. // // responses: -// 200: body:ListMemberReply +// 200: body:DelSessionReply // default: body:GenericResp -func (d *DMSController) ListMembers(c echo.Context) error { - req := new(aV1.ListMemberReq) +func (ctl *DMSController) DelSession(c echo.Context) error { + var redirectUri string + + refreshToken, err := c.Cookie(constant.DMSRefreshToken) + if err != nil { + ctl.log.Warnf("DelSession get refresh token cookie failed: %v, will not logout third-party platform session", err) + } else { + _,sub, sid, _, err := jwt.ParseRefreshToken(refreshToken.Value) + if err != nil { + ctl.log.Errorf("DelSession parse refresh token failed: %v, will not logout third-party platform session", err) + } else { + // 包含第三方会话信息,同步注销第三方平台会话 + redirectUri, err = ctl.DMS.Oauth2ConfigurationUsecase.Logout(c.Request().Context(), sub, sid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + } + } + + var userUid string + cookie, err := c.Cookie(constant.DMSToken) + if err != nil { + ctl.log.Warnf("DelSession get dms token cookie failed: %v", err) + } else { + // cookie 未过期 + cookie.MaxAge = -1 // MaxAge<0 means delete cookie now + cookie.Path = "/" + c.SetCookie(cookie) + ctl.CloudbeaverService.Logout(cookie.Value) + + // 从token中获取用户uid + if uid, err := jwt.ParseUidFromJwtTokenStr(cookie.Value); err == nil { + userUid = uid + } + } + + // 记录登出操作 + if userUid != "" { + user, err := ctl.DMS.UserUsecase.GetUser(c.Request().Context(), userUid) + if err == nil { + recordReq := &aV1.AddOperationRecordReq{ + OperationRecord: &aV1.OperationRecord{ + OperationTime: time.Now(), + OperationUserName: user.Name, + OperationReqIP: c.RealIP(), + OperationUserAgent: c.Request().UserAgent(), + OperationTypeName: "user", + OperationAction: "logout", + OperationProjectName: "", + OperationStatus: "succeeded", + OperationI18nContent: i18nPkg.ConvertStr2I18nAsDefaultLang(fmt.Sprintf("用户 %s 登出系统", user.Name)), + }, + } + _, err = ctl.DMS.AddOperationRecord(c.Request().Context(), recordReq) + if err != nil { + ctl.log.Errorf("failed to save logout operation record: %v, operation_record: user_name=%s, ip=%s, user_agent=%s, action=logout", + err, user.Name, c.RealIP(), c.Request().UserAgent()) + } + } + } + + reply := &aV1.DelSessionReply{Data: struct { + Location string `json:"location"` + }{Location: redirectUri}} + buf := &bytes.Buffer{} + enc := json.NewEncoder(buf) + enc.SetEscapeHTML(false) // 避免将location中的 & 编码为 \u0026 + if err = enc.Encode(reply); err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + return c.JSONBlob(http.StatusOK, buf.Bytes()) +} + +// swagger:operation POST /v1/dms/sessions/refresh Session RefreshSession +// +// refresh a session. +// +// --- +// responses: +// '200': +// description: RefreshSession reply +// schema: +// "$ref": "#/definitions/AddSessionReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) RefreshSession(c echo.Context) error { + refreshToken, err := c.Cookie(constant.DMSRefreshToken) + if err != nil { + return c.String(http.StatusUnauthorized, "refresh token not found") + } + + uid, sub, sid, expired, err := jwt.ParseRefreshToken(refreshToken.Value) + if err != nil { + return c.String(http.StatusUnauthorized, err.Error()) + } + if expired { + // 刷新token过期时,且包含第三方平台会话信息,注销第三方平台会话 + err = ctl.DMS.Oauth2ConfigurationUsecase.BackendLogout(c.Request().Context(), sub, sid) + if err != nil { + ctl.log.Errorf("expired refresh token, call BackendLogout err: %v", err) + return NewErrResp(c, err, apiError.APIServerErr) + } + return c.String(http.StatusUnauthorized, "refresh token is expired") + } + + // 签发的token包含第三方平台信息,需要同步刷新第三方平台token + if sub != "" || sid != "" { + claims, err := ctl.DMS.RefreshOauth2Token(c.Request().Context(), uid, sub, sid) + if err != nil { + return c.String(http.StatusUnauthorized, err.Error()) + } + + newDmsToken, dmsCookieExp, err := claims.DmsToken() + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + newRefreshToken, dmsRefreshCookieExp, err := claims.DmsRefreshToken() + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + c.SetCookie(&http.Cookie{ + Name: constant.DMSToken, + Value: newDmsToken, + Path: "/", + Expires: time.Now().Add(dmsCookieExp), + }) + c.SetCookie(&http.Cookie{ + Name: constant.DMSRefreshToken, + Value: newRefreshToken, + Path: "/", + HttpOnly: true, // 增加安全性 + SameSite: http.SameSiteStrictMode, // cookie只会在同站请求中发送。 + Expires: time.Now().Add(dmsRefreshCookieExp), + }) + + return NewOkRespWithReply(c, &aV1.AddSessionReply{ + Data: struct { + Token string `json:"token"` + Message string `json:"message"` + }{ + Token: newDmsToken, + }, + }) + } + + // Create token with claims + token, err := jwt.GenJwtToken(jwt.WithUserId(uid)) + if nil != err { + return NewErrResp(c, err, apiError.APIServerErr) + } + + c.SetCookie(&http.Cookie{ + Name: constant.DMSToken, + Value: token, + Path: "/", + Expires: time.Now().Add(jwt.DefaultDmsTokenExpHours * time.Hour), + }) + + return NewOkRespWithReply(c, &aV1.AddSessionReply{ + Data: struct { + Token string `json:"token"` + Message string `json:"message"` + }{ + Token: token, + }, + }) +} + +// swagger:route GET /v1/dms/sessions/user Session GetUserBySession +// +// Get current user. +// +// responses: +// 200: body:GetUserBySessionReply +// default: body:GenericResp +func (ctl *DMSController) GetUserBySession(c echo.Context) error { + uid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.GetCurrentUser(c.Request().Context(), &aV1.GetUserBySessionReq{UserUid: uid}) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/users User AddUser +// +// Add user. +// +// --- +// parameters: +// - name: user +// in: body +// required: true +// description: Add new user +// schema: +// "$ref": "#/definitions/AddUserReq" +// responses: +// '200': +// description: AddUserReply +// schema: +// "$ref": "#/definitions/AddUserReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddUser(c echo.Context) error { + req := new(aV1.AddUserReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.ListMembers(c.Request().Context(), req) + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.AddUser(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/members/internal dms ListMembersForInternal +// swagger:operation PUT /v1/dms/users/{user_uid} User UpdateUser // -// List members, for internal backend service. +// Update a user. // -// responses: -// 200: body:ListMembersForInternalReply -// default: body:GenericResp -func (d *DMSController) ListMembersForInternal(c echo.Context) error { - req := new(dmsV1.ListMembersForInternalReq) +// --- +// parameters: +// - name: user_uid +// description: User uid +// in: path +// required: true +// type: string +// - name: user +// description: Update a user +// in: body +// schema: +// "$ref": "#/definitions/UpdateUserReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateUser(c echo.Context) error { + req := new(aV1.UpdateUserReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.ListMembersForInternal(c.Request().Context(), req) + // get current user id + currentUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.UpdateUser(c.Request().Context(), req, currentUid) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) + return NewOkResp(c) } -// swagger:route PUT /v1/dms/members/{member_uid} dms UpdateMember +// swagger:operation PUT /v1/dms/users User UpdateCurrentUser // -// Update a member. +// Update current user. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (d *DMSController) UpdateMember(c echo.Context) error { - req := new(aV1.UpdateMemberReq) +// --- +// parameters: +// - name: current_user +// description: Update current user +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateCurrentUserReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateCurrentUser(c echo.Context) error { + req := new(aV1.UpdateCurrentUserReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } // get current user id - currentUserUid, err := jwt.GetUserUidStrFromContext(c) + currentUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = d.DMS.UpdateMember(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.UpdateCurrentUser(c.Request().Context(), req, currentUid) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route DELETE /v1/dms/members/{member_uid} dms DelMember +// swagger:route DELETE /v1/dms/users/{user_uid} User DelUser // -// Delete a member. +// Delete a user. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (a *DMSController) DelMember(c echo.Context) error { - req := &aV1.DelMemberReq{} +func (ctl *DMSController) DelUser(c echo.Context) error { + req := &aV1.DelUserReq{} err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) @@ -708,627 +1103,3975 @@ func (a *DMSController) DelMember(c echo.Context) error { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = a.DMS.DelMember(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.DelUser(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route GET /v1/dms/op_permissions dms ListOpPermissions + +// swagger:route GET /v1/dms/users User ListUsers // -// List op permission. +// List users. // // responses: -// 200: body:ListOpPermissionReply +// 200: body:ListUserReply // default: body:GenericResp -func (d *DMSController) ListOpPermissions(c echo.Context) error { - req := new(aV1.ListOpPermissionReq) +func (ctl *DMSController) ListUsers(c echo.Context) error { + req := new(dmsV1.ListUserReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.ListOpPermissions(c.Request().Context(), req) + reply, err := ctl.DMS.ListUsers(c.Request().Context(), req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/namespaces dms ListNamespaces +// swagger:route GET /v1/dms/users/{user_uid}/op_permission User GetUserOpPermission // -// List namespaces. +// Get user op permission info, This API is used by other component such as sqle&auth to check user permissions. // // responses: -// 200: body:ListNamespaceReply +// 200: body:GetUserOpPermissionReply // default: body:GenericResp -func (d *DMSController) ListNamespaces(c echo.Context) error { - req := new(dmsV1.ListNamespaceReq) +func (ctl *DMSController) GetUserOpPermission(c echo.Context) error { + req := new(dmsV1.GetUserOpPermissionReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - - // get current user id - currentUserUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { + reply, err := ctl.DMS.GetUserOpPermission(c.Request().Context(), req) + if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } + return NewOkRespWithReply(c, reply) +} - reply, err := d.DMS.ListNamespaces(c.Request().Context(), req, currentUserUid) +// swagger:route GET /v1/dms/users/{user_uid} User GetUser +// +// Get user info, This API is used by other component such as sqle&auth to get user info. +// +// responses: +// 200: body:GetUserReply +// default: body:GenericResp +func (ctl *DMSController) GetUser(c echo.Context) error { + req := new(dmsV1.GetUserReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.GetUser(c.Request().Context(), req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/namespaces dms AddNamespace +// swagger:operation POST /v1/dms/users/gen_token User GenAccessToken // -// Add namespaces. +// Gen user access token. // -// responses: -// 200: body:AddNamespaceReply -// default: body:GenericResp -func (d *DMSController) AddNamespace(c echo.Context) error { - req := new(aV1.AddNamespaceReq) +// --- +// parameters: +// - name: expiration_days +// in: body +// required: true +// schema: +// "$ref": "#/definitions/GenAccessToken" +// responses: +// '200': +// description: GenAccessTokenReply +// schema: +// "$ref": "#/definitions/GenAccessTokenReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) GenAccessToken(c echo.Context) error { + req := new(dmsV1.GenAccessToken) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id - currentUserUid, err := jwt.GetUserUidStrFromContext(c) + currentUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - reply, err := d.DMS.AddNamespace(c.Request().Context(), currentUserUid, req) + reply, err := ctl.DMS.GenAccessToken(c.Request().Context(), currentUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route DELETE /v1/dms/namespaces/{namespace_uid} dms DelNamespace +// swagger:operation POST /v1/dms/user_groups UserGroup AddUserGroup // -// Delete a Namespace +// Add user group. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (a *DMSController) DelNamespace(c echo.Context) error { - req := &aV1.DelNamespaceReq{} +// --- +// parameters: +// - name: user_group +// description: Add new user group +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddUserGroupReq" +// responses: +// '200': +// description: AddUserGroupReply +// schema: +// "$ref": "#/definitions/AddUserGroupReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddUserGroup(c echo.Context) error { + req := new(aV1.AddUserGroupReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = a.DMS.DeleteNamespace(c.Request().Context(), currentUserUid, req) + + reply, err := ctl.DMS.AddUserGroup(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) + return NewOkRespWithReply(c, reply) } -// swagger:route PUT /v1/dms/namespaces/{namespace_uid} dms UpdateNamespace +// swagger:operation PUT /v1/dms/user_groups/{user_group_uid} UserGroup UpdateUserGroup // -// update a Namespace. +// Update a user group. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (a *DMSController) UpdateNamespace(c echo.Context) error { - req := &aV1.UpdateNamespaceReq{} +// --- +// parameters: +// - name: user_group_uid +// description: UserGroup uid +// in: path +// required: true +// type: string +// - name: user_group +// description: Update a user group +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateUserGroupReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateUserGroup(c echo.Context) error { + req := new(aV1.UpdateUserGroupReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = a.DMS.UpdateNamespaceDesc(c.Request().Context(), currentUserUid, req) + + err = ctl.DMS.UpdateUserGroup(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route PUT /v1/dms/namespaces/{namespace_uid}/archive dms ArchiveNamespace +// swagger:route DELETE /v1/dms/user_groups/{user_group_uid} UserGroup DelUserGroup // -// Archive a Namespace. +// Delete a user group. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (a *DMSController) ArchiveNamespace(c echo.Context) error { - req := &aV1.ArchiveNamespaceReq{} +func (ctl *DMSController) DelUserGroup(c echo.Context) error { + req := &aV1.DelUserGroupReq{} err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = a.DMS.ArchivedNamespace(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.DelUserGroup(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route PUT /v1/dms/namespaces/{namespace_uid}/unarchive dms UnarchiveNamespace +// swagger:route GET /v1/dms/user_groups UserGroup ListUserGroups // -// Unarchive a Namespace. +// List user groups. // // responses: -// 200: body:GenericResp +// 200: body:ListUserGroupReply // default: body:GenericResp -func (a *DMSController) UnarchiveNamespace(c echo.Context) error { - req := &aV1.UnarchiveNamespaceReq{} +func (ctl *DMSController) ListUserGroups(c echo.Context) error { + req := new(aV1.ListUserGroupReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListUserGroups(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/roles Role AddRole +// +// Add role. +// +// --- +// parameters: +// - name: role +// description: Add new role +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddRoleReq" +// responses: +// '200': +// description: AddRoleReply +// schema: +// "$ref": "#/definitions/AddRoleReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddRole(c echo.Context) error { + req := new(aV1.AddRoleReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = a.DMS.UnarchiveNamespace(c.Request().Context(), currentUserUid, req) + reply, err := ctl.DMS.AddRole(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) + return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/proxy dms RegisterDMSProxyTarget +// swagger:operation PUT /v1/dms/roles/{role_uid} Role UpdateRole // -// Register dms proxy target. +// Update a role. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (d *DMSController) RegisterDMSProxyTarget(c echo.Context) error { - req := new(dmsV1.RegisterDMSProxyTargetReq) +// --- +// parameters: +// - name: role_uid +// description: Role uid +// in: path +// required: true +// type: string +// - name: role +// description: Update a role +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateRoleReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateRole(c echo.Context) error { + req := new(aV1.UpdateRoleReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = d.DMS.RegisterDMSProxyTarget(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.UpdateRole(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) } -// swagger:route POST /v1/dms/plugin dms RegisterDMSPlugin +// swagger:route DELETE /v1/dms/roles/{role_uid} Role DelRole // -// Register dms plugin. +// Delete a role. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (d *DMSController) RegisterDMSPlugin(c echo.Context) error { - req := new(dmsV1.RegisterDMSPluginReq) +func (ctl *DMSController) DelRole(c echo.Context) error { + req := &aV1.DelRoleReq{} err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } + // get current user id currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { return NewErrResp(c, err, apiError.DMSServiceErr) } - err = d.DMS.RegisterDMSPlugin(c.Request().Context(), currentUserUid, req) + err = ctl.DMS.DelRole(c.Request().Context(), currentUserUid, req) if nil != err { return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) } -// swagger:route GET /v1/dms/configurations/oauth2 dms GetOauth2Configuration +// swagger:route GET /v1/dms/roles Role ListRoles // -// Get Oauth2 configuration. +// List roles. // // responses: -// 200: body:GetOauth2ConfigurationResDataReply +// 200: body:ListRoleReply // default: body:GenericResp -func (d *DMSController) GetOauth2Configuration(c echo.Context) error { - reply, err := d.DMS.GetOauth2Configuration(c.Request().Context()) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) +func (ctl *DMSController) ListRoles(c echo.Context) error { + req := new(aV1.ListRoleReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListRoles(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route PATCH /v1/dms/configurations/oauth2 dms UpdateOauth2Configuration +// swagger:operation POST /v1/dms/projects/{project_uid}/members Member AddMember // -// Update Oauth2 configuration.. +// Add member. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (d *DMSController) UpdateOauth2Configuration(c echo.Context) error { - req := new(aV1.Oauth2ConfigurationReq) +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: member +// description: Add new member +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddMemberReq" +// responses: +// '200': +// description: AddMemberReply +// schema: +// "$ref": "#/definitions/AddMemberReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddMember(c echo.Context) error { + req := new(aV1.AddMemberReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.UpdateOauth2Configuration(c.Request().Context(), req) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) + + reply, err := ctl.DMS.AddMember(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/oauth2/tips dms GetOauth2Tips +// swagger:route GET /v1/dms/projects/{project_uid}/members/tips Member ListMemberTips // -// Get Oauth2 Tips. +// List member tips. // // responses: -// 200: body:GetOauth2TipsReply +// 200: body:ListMemberTipsReply // default: body:GenericResp -func (d *DMSController) GetOauth2Tips(c echo.Context) error { - reply, err := d.DMS.GetOauth2ConfigurationTip(c.Request().Context()) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) +func (ctl *DMSController) ListMemberTips(c echo.Context) error { + req := new(aV1.ListMemberTipsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListMemberTips(c.Request().Context(), req.ProjectUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/oauth2/link +// swagger:route GET /v1/dms/projects/{project_uid}/members Member ListMembers +// +// List member, for front page. // -// Oauth2 Link. -func (d *DMSController) Oauth2Link(c echo.Context) error { - uri, err := d.DMS.Oauth2Link(c.Request().Context()) +// responses: +// 200: body:ListMemberReply +// default: body:GenericResp +func (ctl *DMSController) ListMembers(c echo.Context) error { + req := new(aV1.ListMemberReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) } - return c.Redirect(http.StatusFound, uri) + reply, err := ctl.DMS.ListMembers(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) } -// Oauth2Callback is a hidden interface for third-party platform callbacks for oauth2 verification -func (d *DMSController) Oauth2Callback(c echo.Context) error { - req := new(aV1.Oauth2CallbackReq) +// swagger:route GET /v1/dms/projects/{project_uid}/members/internal Member ListMembersForInternal +// +// List members, for internal backend service. +// +// responses: +// 200: body:ListMembersForInternalReply +// default: body:GenericResp +func (ctl *DMSController) ListMembersForInternal(c echo.Context) error { + req := new(dmsV1.ListMembersForInternalReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - uri, err := d.DMS.Oauth2Callback(c.Request().Context(), req) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + reply, err := ctl.DMS.ListMembersForInternal(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } - return c.Redirect(http.StatusFound, uri) + return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/oauth2/user/bind dms BindOauth2User +// swagger:operation PUT /v1/dms/projects/{project_uid}/members/{member_uid} Member UpdateMember // -// Bind Oauth2 User. +// Update a member. // -// responses: -// 200: body:BindOauth2UserReply -// default: body:GenericResp -func (d *DMSController) BindOauth2User(c echo.Context) error { - req := new(aV1.BindOauth2UserReq) +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: member_uid +// description: Member uid +// in: path +// required: true +// type: string +// - name: member +// description: Update a member +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateMemberReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateMember(c echo.Context) error { + req := new(aV1.UpdateMemberReq) err := bindAndValidateReq(c, req) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.BindOauth2User(c.Request().Context(), req) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) + err = ctl.DMS.UpdateMember(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) } -// swagger:route PATCH /v1/dms/configurations/ldap dms UpdateLDAPConfiguration +// swagger:route DELETE /v1/dms/projects/{project_uid}/members/{member_uid} Member DelMember // -// Update ldap configuration. +// Delete a member. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (d *DMSController) UpdateLDAPConfiguration(c echo.Context) error { - req := new(aV1.UpdateLDAPConfigurationReq) +func (ctl *DMSController) DelMember(c echo.Context) error { + req := &aV1.DelMemberReq{} err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.UpdateLDAPConfiguration(c.Request().Context(), req) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.DelMember(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route GET /v1/dms/configurations/ldap dms GetLDAPConfiguration +// swagger:route GET /v1/dms/projects/{project_uid}/member_groups MemberGroup ListMemberGroups // -// Get ldap configuration. +// List member group, for front page. // // responses: -// 200: body:GetLDAPConfigurationResDataReply +// 200: body:ListMemberGroupsReply // default: body:GenericResp -func (d *DMSController) GetLDAPConfiguration(c echo.Context) error { - reply, err := d.DMS.GetLDAPConfiguration(c.Request().Context()) +func (ctl *DMSController) ListMemberGroups(c echo.Context) error { + req := new(aV1.ListMemberGroupsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.ListMemberGroups(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/configurations/smtp dms GetSMTPConfiguration +// swagger:route GET /v1/dms/projects/{project_uid}/member_groups/tips MemberGroup ListMemberGroupTips // -// get smtp configuration. +// List member group tips. // // responses: -// 200: body:GetSMTPConfigurationReply +// 200: body:ListMemberGroupTipsReply // default: body:GenericResp -func (d *DMSController) GetSMTPConfiguration(c echo.Context) error { - reply, err := d.DMS.GetSMTPConfiguration(c.Request().Context()) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) +func (ctl *DMSController) ListMemberGroupTips(c echo.Context) error { + req := new(aV1.ListMemberGroupTipsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.ListMemberGroupTips(c.Request().Context(), req.ProjectUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route PATCH /v1/dms/configurations/smtp dms UpdateSMTPConfiguration +// swagger:route GET /v1/dms/projects/{project_uid}/member_groups/{member_group_uid} MemberGroup GetMemberGroup // -// Get smtp configuration. +// Get member group, for front page. // // responses: -// 200: body:GenericResp +// 200: body:GetMemberGroupReply // default: body:GenericResp -func (d *DMSController) UpdateSMTPConfiguration(c echo.Context) error { - req := new(aV1.UpdateSMTPConfigurationReq) +func (ctl *DMSController) GetMemberGroup(c echo.Context) error { + req := new(aV1.GetMemberGroupReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.UpdateSMTPConfiguration(c.Request().Context(), req) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + reply, err := ctl.DMS.GetMemberGroup(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkResp(c) + return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/configurations/smtp/test dms TestSMTPConfiguration +// swagger:operation POST /v1/dms/projects/{project_uid}/member_groups MemberGroup AddMemberGroup // -// test smtp configuration. +// Add member group. // -// responses: -// 200: body:TestSMTPConfigurationReply -// default: body:GenericResp -func (d *DMSController) TestSMTPConfiguration(c echo.Context) error { - req := new(aV1.TestSMTPConfigurationReq) +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: member_group +// description: Add new member group +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddMemberGroupReq" +// responses: +// '200': +// description: AddMemberGroupReply +// schema: +// "$ref": "#/definitions/AddMemberGroupReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddMemberGroup(c echo.Context) error { + req := new(aV1.AddMemberGroupReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.TestSMTPConfiguration(c.Request().Context(), req) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.AddMemberGroup(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/configurations/wechat dms GetWeChatConfiguration +// swagger:operation PUT /v1/dms/projects/{project_uid}/member_groups/{member_group_uid} MemberGroup UpdateMemberGroup // -// get wechat configuration. +// update member group, for front page. // -// responses: -// 200: body:GetWeChatConfigurationReply -// default: body:GenericResp -func (d *DMSController) GetWeChatConfiguration(c echo.Context) error { - reply, err := d.DMS.GetWeChatConfiguration(c.Request().Context()) +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: member_group_uid +// description: Member group id +// in: path +// required: true +// type: string +// - name: member_group +// description: Update a member group +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateMemberGroupReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateMemberGroup(c echo.Context) error { + req := new(aV1.UpdateMemberGroupReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) + + err = ctl.DMS.UpdateMemberGroup(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) } -// swagger:route PATCH /v1/dms/configurations/wechat dms UpdateWeChatConfiguration +// swagger:route DELETE /v1/dms/projects/{project_uid}/member_groups/{member_group_uid} MemberGroup DeleteMemberGroup // -// update wechat configuration. +// delete member group, for front page. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (d *DMSController) UpdateWeChatConfiguration(c echo.Context) error { - req := new(aV1.UpdateWeChatConfigurationReq) +func (ctl *DMSController) DeleteMemberGroup(c echo.Context) error { + req := new(aV1.DeleteMemberGroupReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.UpdateWeChatConfiguration(c.Request().Context(), req) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.DeleteMemberGroup(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } + return NewOkResp(c) } -// swagger:route POST /v1/dms/configurations/wechat/test dms TestWeChatConfiguration +// swagger:route GET /v1/dms/op_permissions OpPermission ListOpPermissions // -// test wechat configuration. +// List op permission. // // responses: -// 200: body:TestWeChatConfigurationReply +// 200: body:ListOpPermissionReply // default: body:GenericResp -func (d *DMSController) TestWeChatConfiguration(c echo.Context) error { - req := new(aV1.TestWeChatConfigurationReq) +func (ctl *DMSController) ListOpPermissions(c echo.Context) error { + req := new(aV1.ListOpPermissionReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.TestWeChatConfiguration(c.Request().Context(), req) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + + reply, err := ctl.DMS.ListOpPermissions(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route GET /v1/dms/configurations/feishu dms GetFeishuConfiguration +// swagger:route GET /v1/dms/projects Project ListProjects // -// get feishu configuration. +// List projects. // // responses: -// 200: body:GetFeishuConfigurationReply +// 200: body:ListProjectReply // default: body:GenericResp -func (d *DMSController) GetFeishuConfiguration(c echo.Context) error { - reply, err := d.DMS.GetFeishuConfiguration(c.Request().Context()) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) - } - return NewOkRespWithReply(c, reply) +// deprecated: true +func (ctl *DMSController) ListProjects(c echo.Context) error { + return nil } -// swagger:route PATCH /v1/dms/configurations/feishu dms UpdateFeishuConfiguration +// swagger:operation POST /v1/dms/projects/business_tags Project CreateBusinessTag // -// update feishu configuration. +// Create a new business tag. // -// responses: -// 200: body:GenericResp -// default: body:GenericResp -func (d *DMSController) UpdateFeishuConfiguration(c echo.Context) error { - req := new(aV1.UpdateFeishuConfigurationReq) +// --- +// parameters: +// - name: business_tag +// description: business tag to be created +// in: body +// required: true +// schema: +// "$ref": "#/definitions/CreateBusinessTagReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CreateBusinessTag(c echo.Context) error { + req := new(aV1.CreateBusinessTagReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.UpdateFeishuConfiguration(c.Request().Context(), req) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.CreateBusinessTag(c.Request().Context(), currentUserUid, req.BusinessTag) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } + return NewOkResp(c) } -// swagger:route POST /v1/dms/configurations/feishu/test dms TestFeishuConfiguration +// swagger:operation PUT /v1/dms/projects/business_tags/{business_tag_uid} Project UpdateBusinessTag // -// test feishu configuration. +// Update an existing business tag. // -// responses: -// 200: body:TestFeishuConfigurationReply -// default: body:GenericResp -func (d *DMSController) TestFeishuConfig(c echo.Context) error { - req := new(aV1.TestFeishuConfigurationReq) +// --- +// parameters: +// - name: business_tag_uid +// description: business tag id +// in: path +// required: true +// type: string +// - name: business_tag +// description: the business tag to be updated +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateBusinessTagReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateBusinessTag(c echo.Context) error { + req := new(aV1.UpdateBusinessTagReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - reply, err := d.DMS.TestFeishuConfiguration(c.Request().Context(), req) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) -} -// swagger:route GET /v1/dms/configurations/webhook dms GetWebHookConfiguration -// -// get webhook configuration. -// -// responses: -// 200: body:GetWebHookConfigurationReply -// default: body:GenericResp -func (d *DMSController) GetWebHookConfiguration(c echo.Context) error { - reply, err := d.DMS.GetWebHookConfiguration(c.Request().Context()) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + err = ctl.DMS.UpdateBusinessTag(c.Request().Context(), currentUserUid, req.BusinessTagUID, req.BusinessTag) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } - return NewOkRespWithReply(c, reply) + return NewOkResp(c) } -// swagger:route PATCH /v1/dms/configurations/webhook dms UpdateWebHookConfiguration +// swagger:route DELETE /v1/dms/projects/business_tags/{business_tag_uid} Project DeleteBusinessTag // -// update webhook configuration. +// Delete an existing business tag. // // responses: // 200: body:GenericResp // default: body:GenericResp -func (d *DMSController) UpdateWebHookConfiguration(c echo.Context) error { - req := new(aV1.UpdateWebHookConfigurationReq) +func (ctl *DMSController) DeleteBusinessTag(c echo.Context) error { + req := new(aV1.DeleteBusinessTagReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.UpdateWebHookConfiguration(c.Request().Context(), req) + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.DeleteBusinessTag(c.Request().Context(), currentUserUid, req.BusinessTagUID) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route POST /v1/dms/configurations/webhook/test dms TestWebHookConfiguration +// swagger:route GET /v1/dms/projects/business_tags Project ListBusinessTags // -// test webhook configuration. +// List business tags. // // responses: -// 200: body:TestWebHookConfigurationReply +// 200: body:ListBusinessTagsReply // default: body:GenericResp -func (d *DMSController) TestWebHookConfiguration(c echo.Context) error { - - reply, err := d.DMS.TestWebHookConfiguration(c.Request().Context()) - if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) +func (ctl *DMSController) ListBusinessTags(c echo.Context) error{ + req := new(aV1.ListBusinessTagReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.ListBusinessTags(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkRespWithReply(c, reply) } -// swagger:route POST /v1/dms/notifications dms Notification +// swagger:operation POST /v1/dms/projects Project AddProject // -// notify message. +// Add project. +// +// --- +// deprecated: true +// parameters: +// - name: project +// description: Add new Project +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddProjectReq" +// responses: +// '200': +// description: AddProjectReply +// schema: +// "$ref": "#/definitions/AddProjectReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddProject(c echo.Context) error { + return nil +} + +// swagger:route DELETE /v1/dms/projects/{project_uid} Project DelProject +// +// Delete a project // // responses: -// 200: body:NotificationReply +// 200: body:GenericResp // default: body:GenericResp -func (d *DMSController) Notify(c echo.Context) error { - req := new(dmsV1.NotificationReq) +func (ctl *DMSController) DelProject(c echo.Context) error { + req := &aV1.DelProjectReq{} err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.NotifyMessage(c.Request().Context(), req) + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) if err != nil { - return NewErrResp(c, err, apiError.APIServerErr) + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.DeleteProject(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) } return NewOkResp(c) } -// swagger:route POST /v1/dms/webhooks dms WebHookSendMessage +// swagger:operation PUT /v1/dms/projects/{project_uid} Project UpdateProject // -// webhook send message. +// update a project. +// +// --- +// deprecated: true +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: project +// description: Update a project +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateProjectReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateProject(c echo.Context) error { + return nil +} + +// swagger:route PUT /v1/dms/projects/{project_uid}/archive Project ArchiveProject +// +// Archive a project. // // responses: -// 200: body:WebHookSendMessageReply +// 200: body:GenericResp // default: body:GenericResp -func (d *DMSController) WebHookSendMessage(c echo.Context) error { - req := new(dmsV1.WebHookSendMessageReq) +func (ctl *DMSController) ArchiveProject(c echo.Context) error { + req := &aV1.ArchiveProjectReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.ArchivedProject(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:route PUT /v1/dms/projects/{project_uid}/unarchive Project UnarchiveProject +// +// Unarchive a project. +// +// responses: +// 200: body:GenericResp +// default: body:GenericResp +func (ctl *DMSController) UnarchiveProject(c echo.Context) error { + req := &aV1.UnarchiveProjectReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.UnarchiveProject(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/projects/import Project ImportProjects +// +// Import projects. +// +// --- +// deprecated: true +// parameters: +// - name: projects +// description: import projects +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ImportProjectsReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ImportProjects(c echo.Context) error { + return nil +} + +// swagger:route POST /v1/dms/projects/preview_import Project PreviewImportProjects +// +// Preview import projects. +// +// Consumes: +// - multipart/form-data +// +// responses: +// 200: PreviewImportProjectsReply +// default: body:GenericResp +// deprecated: true +func (ctl *DMSController) PreviewImportProjects(c echo.Context) error { + return nil +} + +// swagger:route GET /v1/dms/projects/import_template Project GetImportProjectsTemplate +// +// Get import projects template. +// +// responses: +// 200: GetImportProjectsTemplateReply +// default: body:GenericResp +func (ctl *DMSController) GetImportProjectsTemplate(c echo.Context) error { + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + content, err := ctl.DMS.GetImportProjectsTemplate(c.Request().Context(), currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": "导入项目模版.csv"})) + + return c.Blob(http.StatusOK, "text/csv", content) +} + +// swagger:route GET /v1/dms/projects/export Project ExportProjects +// +// Export projects file. +// +// responses: +// 200: ExportProjectsReply +// default: body:GenericResp +func (ctl *DMSController) ExportProjects(c echo.Context) error { + req := new(aV1.ExportProjectsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + content, err := ctl.DMS.ExportProjects(c.Request().Context(), currentUserUid, req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + fileName := fmt.Sprintf("项目列表_%s.csv", time.Now().Format("20060102150405")) + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": fileName})) + + return c.Blob(http.StatusOK, "text/csv", content) +} + +// swagger:route GET /v1/dms/projects/tips Project GetProjectTips +// +// Get project tips. +// +// responses: +// 200: body:GetProjectTipsReply +// default: body:GenericResp +// deprecated: true +func (ctl *DMSController) GetProjectTips(c echo.Context) error { + return nil +} + +// swagger:route GET /v1/dms/projects/import_db_services_template Project GetImportDBServicesTemplate +// +// Get import DBServices template. +// +// responses: +// 200: GetImportDBServicesTemplateReply +// default: body:GenericResp +func (ctl *DMSController) GetImportDBServicesTemplate(c echo.Context) error { + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + importDBServicesTemplate, err := ctl.DMS.GetImportDBServicesTemplate(c.Request().Context(), currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": "import_db_services_template.csv"})) + + return c.Blob(http.StatusOK, "text/csv", importDBServicesTemplate) +} + +// swagger:route POST /v1/dms/projects/{project_uid}/db_services/import_check DBService ImportDBServicesOfOneProjectCheck +// +// Import DBServices. +// +// Consumes: +// - multipart/form-data +// +// Produces: +// - application/json +// - text/csv +// +// responses: +// 200: ImportDBServicesCheckCsvReply +// default: body:ImportDBServicesCheckReply +// deprecated: true +func (ctl *DMSController) ImportDBServicesOfOneProjectCheck(c echo.Context) error { + return NewOkRespWithReply(c, nil) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/db_services/import DBService ImportDBServicesOfOneProject +// +// Import DBServices. +// +// --- +// deprecated: true +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_services +// description: new db services +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ImportDBServicesOfOneProjectReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ImportDBServicesOfOneProject(c echo.Context) error { + return NewOkResp(c) +} + +// swagger:route POST /v1/dms/projects/import_db_services_check Project ImportDBServicesOfProjectsCheck +// +// Import DBServices. +// +// Consumes: +// - multipart/form-data +// +// Produces: +// - application/json +// - text/csv +// +// responses: +// 200: ImportDBServicesCheckCsvReply +// default: body:ImportDBServicesCheckReply +// deprecated: true +func (ctl *DMSController) ImportDBServicesOfProjectsCheck(c echo.Context) error { + return NewOkRespWithReply(c, nil) +} + +// swagger:operation POST /v1/dms/projects/import_db_services Project ImportDBServicesOfProjects +// +// Import DBServices. +// +// --- +// parameters: +// - name: db_services +// description: new db services +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ImportDBServicesOfProjectsReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// deprecated: true +func (ctl *DMSController) ImportDBServicesOfProjects(c echo.Context) error { + return NewOkResp(c) +} + +// todo 该接口已废弃 +// swagger:operation POST /v1/dms/projects/db_services_connection Project DBServicesConnection +// +// DBServices Connection. +// +// --- +// parameters: +// - name: db_services +// description: check db_service is connectable +// in: body +// schema: +// "$ref": "#/definitions/DBServiceConnectionReq" +// responses: +// '200': +// description: DBServicesConnectionReply +// schema: +// "$ref": "#/definitions/DBServicesConnectionReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) DBServicesConnection(c echo.Context) error { + req := new(aV1.DBServiceConnectionReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.DBServicesConnection(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/projects/db_services_connections Project CheckGlobalDBServicesConnections +// +// check if the global db_services is connectable. +// +// --- +// parameters: +// - name: db_services +// description: check db_services is connectable +// in: body +// schema: +// "$ref": "#/definitions/DBServicesConnectionReq" +// responses: +// '200': +// description: DBServicesConnectionReqReply +// schema: +// "$ref": "#/definitions/DBServicesConnectionReqReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CheckGlobalDBServicesConnections(c echo.Context) error { + var req aV1.DBServicesConnectionReq + err := bindAndValidateReq(c, &req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.CheckDBServiceIsConnectableByIds(c.Request().Context(),"", currentUserUid,req.DBServices) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, reply) +} + + +// swagger:operation POST /v1/dms/projects/check_db_services_privileges Project CheckDBServicesPrivileges +// +// check if the db_services hava enough privileges. +// +// --- +// parameters: +// - name: db_services +// in: body +// description: check db_services have enough privileges +// schema: +// "$ref": "#/definitions/CheckDBServicesPrivilegesReq" +// responses: +// '200': +// description: CheckDBServicesPrivilegesReply +// schema: +// "$ref": "#/definitions/CheckDBServicesPrivilegesReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CheckDBServicesPrivileges(c echo.Context) error { + var req aV1.CheckDBServicesPrivilegesReq + err := bindAndValidateReq(c, &req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.CheckDBServiceHasEnoughPrivileges(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + + +// swagger:operation POST /v1/dms/proxys DMSProxy RegisterDMSProxyTarget +// +// Register dms proxy target. +// +// --- +// parameters: +// - name: dms_proxy_target +// description: register dms proxy +// required: true +// in: body +// schema: +// "$ref": "#/definitions/RegisterDMSProxyTargetReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) RegisterDMSProxyTarget(c echo.Context) error { + req := new(dmsV1.RegisterDMSProxyTargetReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.RegisterDMSProxyTarget(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/plugins DMSPlugin RegisterDMSPlugin +// +// Register dms plugin. +// +// --- +// parameters: +// - name: plugin +// description: Register dms plugin +// required: true +// in: body +// schema: +// "$ref": "#/definitions/RegisterDMSPluginReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) RegisterDMSPlugin(c echo.Context) error { + req := new(dmsV1.RegisterDMSPluginReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.RegisterDMSPlugin(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:route GET /v1/dms/configurations/login/tips Configuration GetLoginTips +// +// get login configuration. +// +// responses: +// 200: body:GetLoginTipsReply +// default: body:GenericResp +func (ctl *DMSController) GetLoginTips(c echo.Context) error { + reply, err := ctl.DMS.GetLoginTips(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/login Configuration UpdateLoginConfiguration +// +// Update login configuration. +// +// --- +// parameters: +// - name: login +// description: update login configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateLoginConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateLoginConfiguration(c echo.Context) error { + req := new(aV1.UpdateLoginConfigurationReq) err := bindAndValidateReq(c, req) if nil != err { return NewErrResp(c, err, apiError.BadRequestErr) } - err = d.DMS.WebHookSendMessage(c.Request().Context(), req) + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.UpdateLoginConfiguration(c.Request().Context(), currentUserUid, req) if err != nil { return NewErrResp(c, err, apiError.APIServerErr) } return NewOkResp(c) } + +// swagger:route GET /v1/dms/configurations/oauth2 Configuration GetOauth2Configuration +// +// Get Oauth2 configuration. +// +// responses: +// 200: body:GetOauth2ConfigurationResDataReply +// default: body:GenericResp +func (ctl *DMSController) GetOauth2Configuration(c echo.Context) error { + reply, err := ctl.DMS.GetOauth2Configuration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/oauth2 Configuration UpdateOauth2Configuration +// +// Update Oauth2 configuration.. +// +// --- +// parameters: +// - name: oauth2 +// description: update oauth2 configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/Oauth2ConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateOauth2Configuration(c echo.Context) error { + req := new(aV1.Oauth2ConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateOauth2Configuration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:route GET /v1/dms/oauth2/tips OAuth2 GetOauth2Tips +// +// Get Oauth2 Tips. +// +// responses: +// 200: body:GetOauth2TipsReply +// default: body:GenericResp +func (ctl *DMSController) GetOauth2Tips(c echo.Context) error { + reply, err := ctl.DMS.GetOauth2ConfigurationTip(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/oauth2/link OAuth2 Oauth2LinkOrCallback +// +// Oauth2 Link or Callback. +func (ctl *DMSController) Oauth2LinkOrCallback(c echo.Context) error { + // 如果是OAuth2 callback请求,QueryParam中会有code这个参数 + if c.QueryParam("code") == "" { + return ctl.oauth2Link(c) + } + return ctl.oauth2Callback(c) +} + +func (ctl *DMSController) oauth2Link(c echo.Context) error { + uri, err := ctl.DMS.Oauth2Link(c.Request().Context(), c.QueryString()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return c.Redirect(http.StatusFound, uri) +} + +// oauth2Callback is a hidden interface for third-party platform callbacks for oauth2 verification +func (ctl *DMSController) oauth2Callback(c echo.Context) error { + req := new(aV1.Oauth2CallbackReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + callbackData, claims, err := ctl.DMS.Oauth2Callback(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + // 1. callbackData.Error 有错误时,前端会回到登录页并展示错误信息 + // 2. callbackData.UserExist 为false时,前端会进入手动绑定页面,绑定时调用绑定接口签发tokens + // 3. 没错误且用户存在时,签发tokens登录成功 + if callbackData.Error == "" && callbackData.UserExist { + dmsToken, dmsCookieExp, err := claims.DmsToken() + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + refreshToken, dmsRefreshCookieExp, err := claims.DmsRefreshToken() + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + callbackData.State = req.State + callbackData.DMSToken = dmsToken + c.SetCookie(&http.Cookie{ + Name: constant.DMSToken, + Value: dmsToken, + Path: "/", + Expires: time.Now().Add(dmsCookieExp), + }) + c.SetCookie(&http.Cookie{ + Name: constant.DMSRefreshToken, + Value: refreshToken, + Path: "/", + HttpOnly: true, // 增加安全性 + SameSite: http.SameSiteStrictMode, // cookie只会在同站请求中发送。 + Expires: time.Now().Add(dmsRefreshCookieExp), + }) + + // 记录登入操作 + if claims != nil && claims.UserId != "" { + user, err := ctl.DMS.UserUsecase.GetUser(c.Request().Context(), claims.UserId) + if err == nil { + recordReq := &aV1.AddOperationRecordReq{ + OperationRecord: &aV1.OperationRecord{ + OperationTime: time.Now(), + OperationUserName: user.Name, + OperationReqIP: c.RealIP(), + OperationUserAgent: c.Request().UserAgent(), + OperationTypeName: "user", + OperationAction: "login", + OperationProjectName: "", + OperationStatus: "succeeded", + OperationI18nContent: i18nPkg.ConvertStr2I18nAsDefaultLang(fmt.Sprintf("用户 %s 通过OAuth2登入系统", user.Name)), + }, + } + _, err = ctl.DMS.AddOperationRecord(c.Request().Context(), recordReq) + if err != nil { + ctl.log.Errorf("failed to save OAuth2 login operation record: %v, operation_record: user_name=%s, ip=%s, user_agent=%s, action=login", + err, user.Name, c.RealIP(), c.Request().UserAgent()) + } + } + } + } + + + return c.Redirect(http.StatusFound, callbackData.Generate()) +} + +// swagger:operation POST /v1/dms/oauth2/user/bind OAuth2 BindOauth2User +// +// Bind Oauth2 User. +// +// --- +// parameters: +// - name: BindOauth2UserReq +// required: true +// in: body +// schema: +// "$ref": "#/definitions/BindOauth2UserReq" +// responses: +// '200': +// description: BindOauth2UserReply +// schema: +// "$ref": "#/definitions/BindOauth2UserReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) BindOauth2User(c echo.Context) error { + req := new(aV1.BindOauth2UserReq) + err := bindAndValidateReq(c, req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + claims, err := ctl.DMS.BindOauth2User(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + dmsToken, dmsCookieExp, err := claims.DmsToken() + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + refreshToken, dmsRefreshCookieExp, err := claims.DmsRefreshToken() + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + c.SetCookie(&http.Cookie{ + Name: constant.DMSToken, + Value: dmsToken, + Path: "/", + Expires: time.Now().Add(dmsCookieExp), + }) + c.SetCookie(&http.Cookie{ + Name: constant.DMSRefreshToken, + Value: refreshToken, + Path: "/", + HttpOnly: true, // 增加安全性 + SameSite: http.SameSiteStrictMode, // cookie只会在同站请求中发送。 + Expires: time.Now().Add(dmsRefreshCookieExp), + }) + + // 记录登入操作 + if claims != nil && claims.UserId != "" { + user, err := ctl.DMS.UserUsecase.GetUser(c.Request().Context(), claims.UserId) + if err == nil { + recordReq := &aV1.AddOperationRecordReq{ + OperationRecord: &aV1.OperationRecord{ + OperationTime: time.Now(), + OperationUserName: user.Name, + OperationReqIP: c.RealIP(), + OperationUserAgent: c.Request().UserAgent(), + OperationTypeName: "user", + OperationAction: "login", + OperationProjectName: "", + OperationStatus: "succeeded", + OperationI18nContent: i18nPkg.ConvertStr2I18nAsDefaultLang(fmt.Sprintf("用户 %s 通过OAuth2绑定登入系统", user.Name)), + }, + } + _, err = ctl.DMS.AddOperationRecord(c.Request().Context(), recordReq) + if err != nil { + ctl.log.Errorf("failed to save OAuth2 bind login operation record: %v, operation_record: user_name=%s, ip=%s, user_agent=%s, action=login", + err, user.Name, c.RealIP(), c.Request().UserAgent()) + } + } + } + + return NewOkRespWithReply(c, &aV1.BindOauth2UserReply{ + Data:aV1.BindOauth2UserResData{Token: dmsToken}, + }) +} + +// BackChannelLogout is a hidden interface for third-party platform callbacks for logout event +// https://openid.net/specs/openid-connect-backchannel-1_0.html#BCRequest +func (ctl *DMSController) BackChannelLogout(c echo.Context) error { + // no-store 指令告诉浏览器和任何中间缓存(例如代理服务器)不要存储响应的任何副本。 + // 这意味着每次请求该资源时,都必须从服务器重新获取 + c.Response().Header().Set(echo.HeaderCacheControl, "no-store") + if err := c.Request().ParseForm(); err != nil { + return c.String(http.StatusBadRequest, "Invalid form data") + } + + logoutToken := c.Request().Form.Get("logout_token") + if logoutToken == "" { + return c.String(http.StatusBadRequest, "Missing logout_token") + } + + // todo Verifier logoutToken by provider + + err := ctl.DMS.BackChannelLogout(c.Request().Context(), logoutToken) + if err != nil { + return c.String(http.StatusInternalServerError, err.Error()) + } + + return c.NoContent(http.StatusOK) +} + +// swagger:operation PATCH /v1/dms/configurations/ldap Configuration UpdateLDAPConfiguration +// +// Update ldap configuration. +// +// --- +// parameters: +// - name: ldap +// description: update ldap configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateLDAPConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateLDAPConfiguration(c echo.Context) error { + req := new(aV1.UpdateLDAPConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateLDAPConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:route GET /v1/dms/configurations/ldap Configuration GetLDAPConfiguration +// +// Get ldap configuration. +// +// responses: +// 200: body:GetLDAPConfigurationResDataReply +// default: body:GenericResp +func (ctl *DMSController) GetLDAPConfiguration(c echo.Context) error { + reply, err := ctl.DMS.GetLDAPConfiguration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/configurations/smtp Configuration GetSMTPConfiguration +// +// get smtp configuration. +// +// responses: +// 200: body:GetSMTPConfigurationReply +// default: body:GenericResp +func (ctl *DMSController) GetSMTPConfiguration(c echo.Context) error { + reply, err := ctl.DMS.GetSMTPConfiguration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/smtp Configuration UpdateSMTPConfiguration +// +// Update smtp configuration. +// +// --- +// parameters: +// - name: smtp_configuration +// description: update smtp configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateSMTPConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateSMTPConfiguration(c echo.Context) error { + req := new(aV1.UpdateSMTPConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateSMTPConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/configurations/smtp/test Configuration TestSMTPConfiguration +// +// test smtp configuration. +// +// --- +// parameters: +// - name: test_smtp_configuration +// description: test smtp configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/TestSMTPConfigurationReq" +// responses: +// '200': +// description: TestSMTPConfigurationReply +// schema: +// "$ref": "#/definitions/TestSMTPConfigurationReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) TestSMTPConfiguration(c echo.Context) error { + req := new(aV1.TestSMTPConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.TestSMTPConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/configurations/wechat Configuration GetWeChatConfiguration +// +// get wechat configuration. +// +// responses: +// 200: body:GetWeChatConfigurationReply +// default: body:GenericResp +func (ctl *DMSController) GetWeChatConfiguration(c echo.Context) error { + reply, err := ctl.DMS.GetWeChatConfiguration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/wechat Configuration UpdateWeChatConfiguration +// +// update wechat configuration. +// +// --- +// parameters: +// - name: update_wechat_configuration +// description: update wechat configuration +// in: body +// schema: +// "$ref": "#/definitions/UpdateWeChatConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateWeChatConfiguration(c echo.Context) error { + req := new(aV1.UpdateWeChatConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateWeChatConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/configurations/wechat/test Configuration TestWeChatConfiguration +// +// test wechat configuration. +// +// --- +// parameters: +// - name: test_wechat_configuration +// description: test wechat configuration +// in: body +// schema: +// "$ref": "#/definitions/TestWeChatConfigurationReq" +// responses: +// '200': +// description: TestWeChatConfigurationReply +// schema: +// "$ref": "#/definitions/TestWeChatConfigurationReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) TestWeChatConfiguration(c echo.Context) error { + req := new(aV1.TestWeChatConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.TestWeChatConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/configurations/feishu Configuration GetFeishuConfiguration +// +// get feishu configuration. +// +// responses: +// 200: body:GetFeishuConfigurationReply +// default: body:GenericResp +func (ctl *DMSController) GetFeishuConfiguration(c echo.Context) error { + reply, err := ctl.DMS.GetFeishuConfiguration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/feishu Configuration UpdateFeishuConfiguration +// +// update feishu configuration. +// +// --- +// parameters: +// - name: update_feishu_configuration +// description: update feishu configuration +// in: body +// schema: +// "$ref": "#/definitions/UpdateFeishuConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateFeishuConfiguration(c echo.Context) error { + req := new(aV1.UpdateFeishuConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateFeishuConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/configurations/feishu/test Configuration TestFeishuConfiguration +// +// test feishu configuration. +// +// --- +// parameters: +// - name: test_feishu_configuration +// description: test feishu configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/TestFeishuConfigurationReq" +// responses: +// '200': +// description: TestFeishuConfigurationReply +// schema: +// "$ref": "#/definitions/TestFeishuConfigurationReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) TestFeishuConfig(c echo.Context) error { + req := new(aV1.TestFeishuConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.TestFeishuConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/configurations/webhook Configuration GetWebHookConfiguration +// +// get webhook configuration. +// +// responses: +// 200: body:GetWebHookConfigurationReply +// default: body:GenericResp +func (ctl *DMSController) GetWebHookConfiguration(c echo.Context) error { + reply, err := ctl.DMS.GetWebHookConfiguration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/webhook Configuration UpdateWebHookConfiguration +// +// update webhook configuration. +// +// --- +// parameters: +// - name: webhook_config +// description: webhook configuration +// in: body +// schema: +// "$ref": "#/definitions/UpdateWebHookConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateWebHookConfiguration(c echo.Context) error { + req := new(aV1.UpdateWebHookConfigurationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateWebHookConfiguration(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:route POST /v1/dms/configurations/webhook/test Configuration TestWebHookConfiguration +// +// test webhook configuration. +// +// responses: +// 200: body:TestWebHookConfigurationReply +// default: body:GenericResp +func (ctl *DMSController) TestWebHookConfiguration(c echo.Context) error { + + reply, err := ctl.DMS.TestWebHookConfiguration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/sms Configuration UpdateSmsConfiguration +// +// update sms configuration. +// +// --- +// parameters: +// - name: update_sms_configuration +// description: update sms configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateSmsConfigurationReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateSmsConfiguration(context echo.Context) error { + req := new(aV1.UpdateSmsConfigurationReq) + err := bindAndValidateReq(context, req) + if nil != err { + return NewErrResp(context, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateSmsConfiguration(context.Request().Context(), req) + if err != nil { + return NewErrResp(context, err, apiError.APIServerErr) + } + return NewOkResp(context) +} + +// swagger:operation POST /v1/dms/configurations/sms/test Configuration TestSmsConfiguration +// +// test smtp configuration. +// +// --- +// parameters: +// - name: test_sms_configuration +// description: test sms configuration +// required: true +// in: body +// schema: +// "$ref": "#/definitions/TestSmsConfigurationReq" +// responses: +// '200': +// description: TestSmsConfigurationReply +// schema: +// "$ref": "#/definitions/TestSmsConfigurationReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) TestSmsConfiguration(context echo.Context) error { + req := new(aV1.TestSmsConfigurationReq) + err := bindAndValidateReq(context, req) + if nil != err { + return NewErrResp(context, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.TestSmsConfiguration(context.Request().Context(), req) + if err != nil { + return NewErrResp(context, err, apiError.APIServerErr) + } + return NewOkRespWithReply(context, reply) +} + + +// swagger:route GET /v1/dms/configurations/sms Configuration GetSmsConfiguration +// +// get sms configuration. +// +// responses: +// 200: body:GetSmsConfigurationReply +// default: body:GenericResp +func (ctl *DMSController) GetSmsConfiguration(c echo.Context) error { + reply, err := ctl.DMS.GetSmsConfiguration(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/configurations/sms/send_code SMS SendSmsCode +// +// send sms code. +// +// --- +// parameters: +// - name: username +// description: user name +// required: true +// in: body +// schema: +// "$ref": "#/definitions/SendSmsCodeReq" +// responses: +// '200': +// description: SendSmsCodeReply +// schema: +// "$ref": "#/definitions/SendSmsCodeReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) SendSmsCode(context echo.Context) error { + req := new(aV1.SendSmsCodeReq) + err := bindAndValidateReq(context, req) + reply, err := ctl.DMS.SendSmsCode(context.Request().Context(), req.Username) + if err != nil { + return NewErrResp(context, err, apiError.APIServerErr) + } + return NewOkRespWithReply(context, reply) +} + +// swagger:operation POST /v1/dms/configurations/sms/verify_code SMS VerifySmsCode +// +// verify sms code. +// +// --- +// parameters: +// - name: code +// description: verify sms code +// required: true +// in: body +// schema: +// "$ref": "#/definitions/VerifySmsCodeReq" +// - name: username +// description: user name +// required: true +// in: body +// schema: +// "$ref": "#/definitions/VerifySmsCodeReq" +// responses: +// '200': +// description: VerifySmsCodeReply +// schema: +// "$ref": "#/definitions/VerifySmsCodeReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) VerifySmsCode(context echo.Context) error { + req := new(aV1.VerifySmsCodeReq) + err := bindAndValidateReq(context, req) + if nil != err { + return NewErrResp(context, err, apiError.BadRequestErr) + } + reply :=ctl.DMS.VerifySmsCode(req) + return NewOkRespWithReply(context, reply) +} + +// swagger:route POST /v1/dms/notifications Notification Notification +// +// notify message. +// +// responses: +// 200: body:NotificationReply +// default: body:GenericResp +func (ctl *DMSController) Notify(c echo.Context) error { + req := new(dmsV1.NotificationReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.NotifyMessage(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/webhooks Webhook WebHookSendMessage +// +// webhook send message. +// +// --- +// parameters: +// - name: webhook_message +// description: webhooks +// required: true +// in: body +// schema: +// "$ref": "#/definitions/WebHookSendMessageReq" +// responses: +// '200': +// description: WebHookSendMessageReply +// schema: +// "$ref": "#/definitions/WebHookSendMessageReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) WebHookSendMessage(c echo.Context) error { + req := new(dmsV1.WebHookSendMessageReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.WebHookSendMessage(c.Request().Context(), req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:operation GET /v1/dms/company_notice CompanyNotice GetCompanyNotice +// +// get company notice info +// +// --- +// parameters: +// - name: include_latest_outside_period +// description: when true, return the latest notice regardless of display window (for admin edit) +// in: query +// required: false +// type: boolean +// responses: +// '200': +// description: GetCompanyNoticeReply +// schema: +// "$ref": "#/definitions/GetCompanyNoticeReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) GetCompanyNotice(c echo.Context) error { + var req aV1.GetCompanyNoticeReq + if err := bindAndValidateReq(c, &req); err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.GetCompanyNotice(c.Request().Context(), currentUserUid, req.IncludeLatestOutsidePeriod) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/company_notice CompanyNotice UpdateCompanyNotice +// +// update company notice info +// +// --- +// parameters: +// - name: company_notice +// description: Update a companynotice +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateCompanyNoticeReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateCompanyNotice(c echo.Context) error { + req := new(aV1.UpdateCompanyNoticeReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.UpdateCompanyNotice(c.Request().Context(), currentUserUid, req) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:route GET /v1/dms/configurations/license Configuration GetLicense +// +// get license. +// +// responses: +// 200: body:GetLicenseReply +// default: body:GenericResp +func (ctl *DMSController) GetLicense(c echo.Context) error { + reply, err := ctl.DMS.GetLicense(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkRespWithReply(c, reply) +} + +const ( + HardwareInfoFileName = "collected.infos" + LicenseFileParamKey = "license_file" + ProjectsFileParamKey = "projects_file" + DBServicesFileParamKey = "db_services_file" +) + +// swagger:route GET /v1/dms/configurations/license/info Configuration GetLicenseInfo +// +// get generate license info. +// +// responses: +// 200: GetLicenseInfoReply +// default: body:GenericResp +func (ctl *DMSController) GetLicenseInfo(c echo.Context) error { + data, err := ctl.DMS.GetLicenseInfo(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": HardwareInfoFileName})) + + return c.Blob(http.StatusOK, echo.MIMEOctetStream, []byte(data)) +} + +// swagger:route GET /v1/dms/configurations/license/usage Configuration GetLicenseUsage +// +// get license usage. +// +// responses: +// 200: body:GetLicenseUsageReply +// default: body:GenericResp +func (ctl *DMSController) GetLicenseUsage(c echo.Context) error { + usage, err := ctl.DMS.GetLicenseUsage(c.Request().Context()) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + return NewOkRespWithReply(c, usage) +} + +// swagger:route POST /v1/dms/configurations/license Configuration SetLicense +// +// import license. +// +// Consumes: +// - multipart/form-data +// +// responses: +// 200: body:GenericResp +// default: body:GenericResp +func (ctl *DMSController) SetLicense(c echo.Context) error { + file, exist, err := ReadFileContent(c, LicenseFileParamKey) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + if !exist { + return NewErrResp(c, fmt.Errorf("upload file is not exist"), apiError.APIServerErr) + } + err = ctl.DMS.SetLicense(c.Request().Context(), file) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + return NewOkResp(c) +} + +// swagger:route POST /v1/dms/configurations/license/check Configuration CheckLicense +// +// notify message. +// +// Consumes: +// - multipart/form-data +// +// responses: +// 200: body:CheckLicenseReply +// default: body:GenericResp +func (ctl *DMSController) CheckLicense(c echo.Context) error { + file, exist, err := ReadFileContent(c, LicenseFileParamKey) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + if !exist { + return NewErrResp(c, fmt.Errorf("upload file is not exist"), apiError.APIServerErr) + } + + reply, err := ctl.DMS.CheckLicense(c.Request().Context(), file) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + return NewOkRespWithReply(c, reply) +} + +// ReadFileContent read content from http body by name if file exist, +// the name is a http form data key, not file name. +func ReadFileContent(c echo.Context, name string) (content string, fileExist bool, err error) { + file, err := c.FormFile(name) + if err == http.ErrMissingFile { + return "", false, nil + } + if err != nil { + return "", false, err + } + src, err := file.Open() + if err != nil { + return "", false, err + } + defer src.Close() + data, err := io.ReadAll(src) + if err != nil { + return "", false, err + } + return string(data), true, nil +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/data_export_workflows DataExportWorkflows AddDataExportWorkflow +// +// Add data_export workflow. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: data_export_workflow +// description: add data export workflow +// in: body +// schema: +// "$ref": "#/definitions/AddDataExportWorkflowReq" +// responses: +// '200': +// description: AddDataExportWorkflowReply +// schema: +// "$ref": "#/definitions/AddDataExportWorkflowReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddDataExportWorkflow(c echo.Context) error { + req := new(aV1.AddDataExportWorkflowReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.AddDataExportWorkflow(c.Request().Context(), req, currentUserUid) + if nil != err { + if errors.Is(err, biz.ErrDataExportWorkflowNameDuplicate) { + return NewErrResp(c, errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.DataExportWorkflowNameDuplicateErr)), apiError.BadRequestErr) + } + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route POST /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/approve DataExportWorkflows ApproveDataExportWorkflow +// +// Approve data_export workflow. +// +// responses: +// 200: body:GenericResp +// default: body:GenericResp +func (ctl *DMSController) ApproveDataExportWorkflow(c echo.Context) error { + req := &aV1.ApproveDataExportWorkflowReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + if err = ctl.DMS.ApproveDataExportWorkflow(c.Request().Context(), req, currentUserUid); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/reject DataExportWorkflows RejectDataExportWorkflow +// +// Reject data_export workflow. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: data_export_workflow_uid +// in: path +// required: true +// type: string +// - name: payload +// required: true +// in: body +// schema: +// "$ref": "#/definitions/RejectDataExportWorkflowReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) RejectDataExportWorkflow(c echo.Context) error { + req := &aV1.RejectDataExportWorkflowReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + if err = ctl.DMS.RejectDataExportWorkflow(c.Request().Context(), req, currentUserUid); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:route GET /v1/dms/projects/{project_uid}/data_export_workflows DataExportWorkflows ListDataExportWorkflows +// +// List data_export workflow. +// +// responses: +// 200: body:ListDataExportWorkflowsReply +// default: body:GenericResp +func (ctl *DMSController) ListDataExportWorkflows(c echo.Context) error { + req := new(aV1.ListDataExportWorkflowsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.ListDataExportWorkflow(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/dashboard/data_export_workflows DataExportWorkflows GetGlobalDataExportWorkflows +// +// Get global data export workflows. +// +// responses: +// 200: body:GetGlobalDataExportWorkflowsReply +// default: body:GenericResp + +func (ctl *DMSController) GetGlobalDataExportWorkflows(c echo.Context) error { + // 内部接口,仅允许sys用户访问 + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + if currentUserUid != pkgConst.UIDOfUserSys && currentUserUid != pkgConst.UIDOfUserAdmin { + return NewErrResp(c, fmt.Errorf("only sys user can get global data export workflows"), apiError.DMSServiceErr) + } + req := new(aV1.FilterGlobalDataExportWorkflowReq) + err = bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.GetGlobalWorkflowsList(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/projects/data_export_workflows DataExportWorkflows ListAllDataExportWorkflows +// +// List all data_export workflow. +// +// responses: +// 200: body:ListDataExportWorkflowsReply +// default: body:GenericResp +func (ctl *DMSController) ListAllDataExportWorkflows(c echo.Context) error { + req := new(aV1.ListDataExportWorkflowsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.ListDataExportWorkflow(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid} DataExportWorkflows GetDataExportWorkflow +// +// Get data_export workflow. +// +// responses: +// 200: body:GetDataExportWorkflowReply +// default: body:GenericResp +func (ctl *DMSController) GetDataExportWorkflow(c echo.Context) error { + req := new(aV1.GetDataExportWorkflowReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.GetDataExportWorkflow(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/data_export_workflows/cancel DataExportWorkflows CancelDataExportWorkflow +// +// Cancel data export workflows. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: payload +// required: true +// in: body +// schema: +// "$ref": "#/definitions/CancelDataExportWorkflowReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) CancelDataExportWorkflow(c echo.Context) error { + req := &aV1.CancelDataExportWorkflowReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + if err = ctl.DMS.CancelDataExportWorkflow(c.Request().Context(), req, currentUserUid); err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:route POST /v1/dms/projects/{project_uid}/data_export_workflows/{data_export_workflow_uid}/export DataExportWorkflows ExportDataExportWorkflow +// +// exec data_export workflow. +// +// responses: +// 200: body:GenericResp +// default: body:GenericResp +func (ctl *DMSController) ExportDataExportWorkflow(c echo.Context) error { + req := &aV1.ExportDataExportWorkflowReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.ExportDataExportWorkflow(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/projects/{project_uid}/data_export_tasks DataExportTask AddDataExportTask +// +// Add data_export task. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: data_export_tasks +// description: add data export workflow +// in: body +// schema: +// "$ref": "#/definitions/AddDataExportTaskReq" +// responses: +// '200': +// description: AddDataExportTaskReply +// schema: +// "$ref": "#/definitions/AddDataExportTaskReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddDataExportTask(c echo.Context) error { + req := new(aV1.AddDataExportTaskReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.AddDataExportTask(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) + +} + +// swagger:route GET /v1/dms/projects/{project_uid}/data_export_tasks DataExportTask BatchGetDataExportTask +// +// Batch get data_export task. +// +// responses: +// 200: body:BatchGetDataExportTaskReply +// default: body:GenericResp +func (ctl *DMSController) BatchGetDataExportTask(c echo.Context) error { + req := new(aV1.BatchGetDataExportTaskReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + reply, err := ctl.DMS.BatchGetDataExportTask(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/data_export_task_sqls DataExportTask ListDataExportTaskSQLs +// +// List data_export workflow. +// +// responses: +// 200: body:ListDataExportTaskSQLsReply +// default: body:GenericResp +func (ctl *DMSController) ListDataExportTaskSQLs(c echo.Context) error { + req := new(aV1.ListDataExportTaskSQLsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.ListDataExportTaskSQLs(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/data_export_task_sqls/download DataExportTask DownloadDataExportTaskSQLs +// +// dowload data_export sqls. +// +// responses: +// 200: DownloadDataExportTaskSQLsReply +// default: body:GenericResp +func (ctl *DMSController) DownloadDataExportTaskSQLs(c echo.Context) error { + req := new(aV1.DownloadDataExportTaskSQLsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + fileName, content, err := ctl.DMS.DownloadDataExportTaskSQLs(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": fileName})) + + return c.Blob(http.StatusOK, echo.MIMETextPlain, content) +} + +// swagger:route GET /v1/dms/projects/{project_uid}/data_export_tasks/{data_export_task_uid}/download DataExportTask DownloadDataExportTask +// +// download task file. +// +// responses: +// 200: DownloadDataExportTaskReply +// default: body:GenericResp +func (ctl *DMSController) DownloadDataExportTask(c echo.Context) error { + req := &aV1.DownloadDataExportTaskReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + isProxy, filePath, err := ctl.DMS.DownloadDataExportTask(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + if isProxy { + return ctl.proxyDownloadDataExportTask(c, filePath) + } + + fileName := filepath.Base(filePath) + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": fileName})) + + return c.File(filePath) +} + +func (ctl *DMSController) proxyDownloadDataExportTask(c echo.Context, reportHost string) (err error) { + protocol := strings.ToLower(strings.Split(c.Request().Proto, "/")[0]) + + // reference from echo framework proxy middleware + target, _ := url.Parse(fmt.Sprintf("%s://%s", protocol, reportHost)) + reverseProxy := httputil.NewSingleHostReverseProxy(target) + reverseProxy.ErrorHandler = func(resp http.ResponseWriter, req *http.Request, err error) { + // If the client canceled the request (usually by closing the connection), we can report a + // client error (4xx) instead of a server error (5xx) to correctly identify the situation. + // The Go standard library (at of late 2020) wraps the exported, standard + // context.Canceled error with unexported garbage value requiring a substring check, see + // https://github.com/golang/go/blob/6965b01ea248cabb70c3749fd218b36089a21efb/src/net/net.go#L416-L430 + if err == context.Canceled || strings.Contains(err.Error(), "operation was canceled") { + httpError := echo.NewHTTPError(middleware.StatusCodeContextCanceled, fmt.Sprintf("client closed connection: %v", err)) + httpError.Internal = err + c.Set("_error", httpError) + } else { + httpError := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("remote %s unreachable, could not forward: %v", reportHost, err)) + httpError.Internal = err + c.Set("_error", httpError) + } + } + + reverseProxy.ServeHTTP(c.Response(), c.Request()) + + if e, ok := c.Get("_error").(error); ok { + err = e + } + + return +} + + +// swagger:route GET /v1/dms/projects/{project_uid}/cb_operation_logs CBOperationLogs ListCBOperationLogs +// +// List cb operation logs. +// +// responses: +// 200: body:ListCBOperationLogsReply +// default: body:GenericResp +func (ctl *DMSController) ListCBOperationLogs(c echo.Context) error { + req := &aV1.ListCBOperationLogsReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.ListCBOperationLogs(c.Request().Context(), req, currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/projects/{project_uid}/cb_operation_logs/export CBOperationLogs ExportCBOperationLogs +// +// Export cb operation logs. +// +// responses: +// 200: ExportCBOperationLogsReply +// default: body:GenericResp +func (ctl *DMSController) ExportCBOperationLogs(c echo.Context) error { + req := &aV1.ExportCBOperationLogsReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + content, err := ctl.DMS.ExportCBOperationLogs(c.Request().Context(), req, currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + fileName := fmt.Sprintf("CBoperation_%s.csv", time.Now().Format("20060102150405.000")) + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": fileName})) + + return c.Blob(http.StatusOK, "text/csv", content) + +} + +// swagger:route GET /v1/dms/projects/{project_uid}/cb_operation_logs/tips CBOperationLogs GetCBOperationLogTips +// +// Get cb operation log tips. +// +// responses: +// 200: GetCBOperationLogTipsReply +// default: body:GenericResp +func (ctl *DMSController) GetCBOperationLogTips(c echo.Context) error { + req := &aV1.GetCBOperationLogTipsReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.GetCBOperationLogTips(c.Request().Context(), req, currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + return NewOkRespWithReply(c, reply) +} + +func (ctl *DMSController) SwaggerHandler(c echo.Context) error { + err := ctl.DMS.RegisterSwagger(c) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + + optionList := []func(config *echoSwagger.Config){ + func(config *echoSwagger.Config) { + // for clear the default URLs + config.URLs = []string{} + }, + } + + // 设置InstanceName,为了找到正确的swagger配置 + for swagType := range api.GetAllSwaggerDocs() { + urlPath := swagType.GetUrlPath() + optionList = append(optionList, echoSwagger.URL(urlPath)) + + if strings.HasSuffix(c.Request().RequestURI, urlPath) { + optionList = append(optionList, echoSwagger.InstanceName(urlPath)) + } + } + + handler := echoSwagger.EchoWrapHandler(optionList...) + return handler(c) +} + +// swagger:operation GET /v1/dms/db_service_sync_tasks DBServiceSyncTask ListDBServiceSyncTasks +// +// List database synchronization tasks. +// +// --- +// responses: +// '200': +// description: ListDBServiceSyncTasksReply +// schema: +// "$ref": "#/definitions/ListDBServiceSyncTasksReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListDBServiceSyncTasks(c echo.Context) error { + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.ListDBServiceSyncTask(c.Request().Context(), currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/db_service_sync_tasks/{db_service_sync_task_uid} DBServiceSyncTask GetDBServiceSyncTask +// +// Get database synchronization task. +// +// --- +// parameters: +// - name: db_service_sync_task_uid +// description: db service sync task uid +// in: path +// required: true +// type: string +// responses: +// '200': +// description: GetDBServiceSyncTaskReply +// schema: +// "$ref": "#/definitions/GetDBServiceSyncTaskReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) GetDBServiceSyncTask(c echo.Context) error { + req := new(aV1.GetDBServiceSyncTaskReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.GetDBServiceSyncTask(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/db_service_sync_tasks DBServiceSyncTask AddDBServiceSyncTask +// +// Add database synchronization task. +// +// --- +// parameters: +// - name: db_service_sync_task +// description: Add new db service sync task +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddDBServiceSyncTaskReq" +// responses: +// '200': +// description: AddDBServiceReply +// schema: +// "$ref": "#/definitions/AddDBServiceReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddDBServiceSyncTask(c echo.Context) error { + req := new(aV1.AddDBServiceSyncTaskReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.AddDBServiceSyncTask(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PUT /v1/dms/db_service_sync_tasks/{db_service_sync_task_uid} DBServiceSyncTask UpdateDBServiceSyncTask +// +// update database synchronization task. +// +// --- +// parameters: +// - name: db_service_sync_task_uid +// description: db service sync task uid +// in: path +// required: true +// type: string +// - name: db_service_sync_task +// description: update db service sync task +// in: body +// required: true +// schema: +// "$ref": "#/definitions/UpdateDBServiceSyncTaskReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateDBServiceSyncTask(c echo.Context) error { + req := &aV1.UpdateDBServiceSyncTaskReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.UpdateDBServiceSyncTask(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:operation DELETE /v1/dms/db_service_sync_tasks/{db_service_sync_task_uid} DBServiceSyncTask DeleteDBServiceSyncTask +// +// Delete database synchronization task. +// +// --- +// parameters: +// - name: db_service_sync_task_uid +// description: db service sync task uid +// in: path +// required: true +// type: string +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) DeleteDBServiceSyncTask(c echo.Context) error { + req := &aV1.DeleteDBServiceSyncTaskReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.DeleteDBServiceSyncTask(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:operation GET /v1/dms/db_service_sync_tasks/tips DBServiceSyncTask ListDBServiceSyncTaskTips +// +// List database synchronization task tips. +// +// --- +// responses: +// '200': +// description: ListDBServiceSyncTaskTipsReply +// schema: +// "$ref": "#/definitions/ListDBServiceSyncTaskTipsReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ListDBServiceSyncTaskTips(c echo.Context) error { + reply, err := ctl.DMS.ListDBServiceSyncTaskTips(c.Request().Context()) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v1/dms/db_service_sync_tasks/{db_service_sync_task_uid}/sync DBServiceSyncTask SyncDBServices +// +// Sync db service. +// +// --- +// parameters: +// - name: db_service_sync_task_uid +// description: db service sync task uid +// in: path +// required: true +// type: string +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) SyncDBServices(c echo.Context) error { + req := &aV1.SyncDBServicesReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.SyncDBServices(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:operation GET /v1/dms/resource_overview/statistics ResourceOverview GetResourceOverviewStatisticsV1 +// +// Get resource overview statistics. +// +// --- +// responses: +// '200': +// description: resource overview statistics response body +// schema: +// "$ref": "#/definitions/ResourceOverviewStatisticsResV1" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (d *DMSController) GetResourceOverviewStatistics(c echo.Context) error { + // 获取当前用户ID + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + // 直接获取并返回统计信息 + reply, err := d.DMS.GetResourceOverviewStatistics(c.Request().Context(), currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/resource_overview/resource_type_distribution ResourceOverview GetResourceOverviewResourceTypeDistributionV1 +// +// Get resource overview resource type distribution. +// +// --- +// responses: +// '200': +// description: resource overview resource type distribution response body +// schema: +// "$ref": "#/definitions/ResourceOverviewResourceTypeDistributionResV1" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (d *DMSController) GetResourceOverviewResourceTypeDistribution(c echo.Context) error { + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + // 直接获取并返回统计信息 + reply, err := d.DMS.GetResourceOverviewResourceTypeDistribution(c.Request().Context(), currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/resource_overview/topology ResourceOverview GetResourceOverviewTopologyV1 +// +// Get resource overview topology. +// +// --- +// responses: +// '200': +// description: resource overview topology response body +// schema: +// "$ref": "#/definitions/ResourceOverviewTopologyResV1" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (d *DMSController) GetResourceOverviewTopology(c echo.Context) error { + req := &aV1.ResourceOverviewTopologyReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + // 获取资源概览拓扑图 + reply, err := d.DMS.GetResourceOverviewTopology(c.Request().Context(), currentUserUid, req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/resource_overview/resource_list ResourceOverview GetResourceOverviewResourceListV1 +// +// Get resource overview resource list. +// +// --- +// responses: +// '200': +// description: resource overview resource list response body +// schema: +// "$ref": "#/definitions/ResourceOverviewResourceListResV1" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (d *DMSController) GetResourceOverviewResourceList(c echo.Context) error { + req := &aV1.ResourceOverviewResourceListReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + // 获取资源概详情列表 + reply, err := d.DMS.GetResourceOverviewList(c.Request().Context(), currentUserUid, req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/resource_overview/download ResourceOverview DownloadResourceOverviewList +// +// download resource overview list csv file. +// +// responses: +// 200: DownloadResourceOverviewListRes +// default: body:GenericResp +func (d *DMSController) DownloadResourceOverviewList(c echo.Context) error { + req := &aV1.DownloadResourceOverviewListReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + content, err := d.DMS.DownloadResourceOverviewList(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + // TODO 后续需要增加国际化时,需要修改文件名以及CSV文件中的字段 + fileName := fmt.Sprintf("资源全景视图_%s.csv", time.Now().Format("20060102150405")) + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": fileName})) + + return c.Blob(http.StatusOK, "text/csv", content) +} + + + + +// swagger:operation PUT /v1/dms/gateways/{gateway_id} Gateway UpdateGateway +// +// update gateways. +// +// --- +// parameters: +// - name: gateway_id +// description: gateway id +// in: path +// required: true +// type: string +// - name: update_gateway +// description: update gateway +// in: body +// required: true +// schema: +// "$ref": "#/definitions/UpdateGatewayReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateGateway(c echo.Context) error { + req := &aV1.UpdateGatewayReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.UpdateGateway(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +func (ctl *DMSController) SyncGateways(c echo.Context) error { + req := &aV1.SyncGatewayReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.SyncGateways(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:route GET /v1/dms/gateways Gateway ListGateways +// +// List gateways. +// +// responses: +// 200: body:ListGatewaysReply +// default: body:GenericResp +func (ctl *DMSController) ListGateways(c echo.Context) error { + req := &aV1.ListGatewaysReq{} + err := bindAndValidateReq(c, req) + if nil!= err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.ListGateways(c.Request().Context(),req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/gateways/{gateway_id} Gateway GetGateway +// +// Get gateways. +// +// responses: +// 200: body:GetGatewayReply +// default: body:GenericResp +func (ctl *DMSController)GetGateway(c echo.Context) error { + req := &aV1.GetGatewayReq{} + err := bindAndValidateReq(c, req) + if nil!= err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + reply, err := ctl.DMS.GetGateway(c.Request().Context(), req) + if nil!= err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v1/dms/gateways/tips Gateway GetGatewayTips +// +// Get gateway tips. +// +// responses: +// 200: body:GetGatewayTipsReply +// default: body:GenericResp +func (ctl *DMSController)GetGatewayTips(c echo.Context) error { + reply,err := ctl.DMS.GetGatewayTips(c.Request().Context()) + if nil!= err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route DELETE /v1/dms/gateways/{gateway_id} Gateway DeleteGateway +// +// Delete gateways. +// +// responses: +// 200: body:GenericResp +// default: body:GenericResp +func (ctl *DMSController)DeleteGateway(c echo.Context) error { + req := &aV1.DeleteGatewayReq{} + err := bindAndValidateReq(c, req) + if nil!= err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.DeleteGateway(c.Request().Context(), req) + if nil!= err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/gateways Gateway AddGateway +// +// Add gateways. +// +// --- +// parameters: +// - name: add_gateway +// description: add gateway +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddGatewayReq" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController)AddGateway(c echo.Context) error { + req := &aV1.AddGatewayReq{} + err := bindAndValidateReq(c, req) + if nil!= err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + err = ctl.DMS.AddGateway(c.Request().Context(), req.AddGateway) + if nil!= err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:route GET /v1/dms/configurations/system_variables Configuration GetSystemVariables +// +// 获取系统变量配置 +// +// responses: +// 200: body:GetSystemVariablesReply +// default: body:GenericResp +func (ctl *DMSController) GetSystemVariables(c echo.Context) error { + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.GetSystemVariables(c.Request().Context(), currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PATCH /v1/dms/configurations/system_variables Configuration UpdateSystemVariables +// +// 更新系统变量配置 +// +// --- +// parameters: +// - name: system_variables +// description: 更新系统变量配置 +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateSystemVariablesReqV1" +// +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateSystemVariables(c echo.Context) error { + req := new(dmsV1.UpdateSystemVariablesReqV1) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.UpdateSystemVariables(c.Request().Context(), req, currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:operation POST /v1/dms/operation_records OperationRecord AddOperationRecord +// +// Add operation record. +// +// --- +// parameters: +// - name: operation_record +// in: body +// required: true +// description: Add new operation record +// schema: +// "$ref": "#/definitions/AddOperationRecordReq" +// responses: +// '200': +// description: AddOperationRecordReply +// schema: +// "$ref": "#/definitions/AddOperationRecordReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddOperationRecord(c echo.Context) error { + req := new(aV1.AddOperationRecordReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + // check if user is admin/sys + isAdmin, err := ctl.DMS.OpPermissionVerifyUsecase.IsUserDMSAdmin(c.Request().Context(), currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + if !isAdmin { + return NewErrResp(c, errors.New("insufficient permission"), apiError.UnauthorizedErr) + } + + reply, err := ctl.DMS.AddOperationRecord(c.Request().Context(), req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/operation_records OperationRecord GetOperationRecordList +// +// Get operation record list. +// +// --- +// parameters: +// - name: filter_operate_time_from +// in: query +// type: string +// - name: filter_operate_time_to +// in: query +// type: string +// - name: filter_operate_project_name +// in: query +// type: string +// - name: fuzzy_search_operate_user_name +// in: query +// type: string +// - name: filter_operate_type_name +// in: query +// type: string +// - name: filter_operate_action +// in: query +// type: string +// - name: page_index +// in: query +// required: true +// type: integer +// - name: page_size +// in: query +// required: true +// type: integer +// responses: +// '200': +// description: GetOperationRecordListReply +// schema: +// "$ref": "#/definitions/GetOperationRecordListReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) GetOperationRecordList(c echo.Context) error { + req := new(aV1.GetOperationRecordListReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.GetOperationRecordList(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation GET /v1/dms/operation_records/exports OperationRecord ExportOperationRecordList +// +// Export operation record list. +// +// --- +// parameters: +// - name: filter_operate_time_from +// in: query +// type: string +// - name: filter_operate_time_to +// in: query +// type: string +// - name: filter_operate_project_name +// in: query +// type: string +// - name: fuzzy_search_operate_user_name +// in: query +// type: string +// - name: filter_operate_type_name +// in: query +// type: string +// - name: filter_operate_action +// in: query +// type: string +// responses: +// '200': +// description: ExportOperationRecordListReply +// schema: +// type: file +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ExportOperationRecordList(c echo.Context) error { + req := new(aV1.ExportOperationRecordListReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + fileData, err := ctl.DMS.ExportOperationRecordList(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + fileName := fmt.Sprintf("%s_operation_record.csv", time.Now().Format("20060102150405")) + c.Response().Header().Set(echo.HeaderContentDisposition, mime.FormatMediaType("attachment", map[string]string{ + "filename": fileName, + })) + + return c.Blob(http.StatusOK, "text/csv", fileData) +} diff --git a/internal/apiserver/service/dms_controller_v2.go b/internal/apiserver/service/dms_controller_v2.go new file mode 100644 index 000000000..3613fd649 --- /dev/null +++ b/internal/apiserver/service/dms_controller_v2.go @@ -0,0 +1,518 @@ +package service + +import ( + "fmt" + "mime" + "net/http" + + dmsApiV2 "github.com/actiontech/dms/api/dms/service/v2" + apiError "github.com/actiontech/dms/internal/apiserver/pkg/error" + commonApiV2 "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/labstack/echo/v4" +) + +// swagger:operation POST /v2/dms/projects Project AddProjectV2 +// +// Add project. +// +// --- +// parameters: +// - name: project +// description: Add new Project +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddProjectReqV2" +// responses: +// '200': +// description: AddProjectReplyV2 +// schema: +// "$ref": "#/definitions/AddProjectReplyV2" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddProjectV2(c echo.Context) error { + req := new(dmsApiV2.AddProjectReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.AddProject(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v2/dms/projects/import Project ImportProjectsV2 +// +// Import projects. +// +// --- +// parameters: +// - name: projects +// description: import projects +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ImportProjectsReqV2" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ImportProjectsV2(c echo.Context) error { + req := new(dmsApiV2.ImportProjectsReq) + err := bindAndValidateReq(c, req) + if err != nil { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.ImportProjects(c.Request().Context(), currentUserUid, req) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + + +// swagger:route POST /v2/dms/projects/preview_import Project PreviewImportProjectsV2 +// +// Preview import projects. +// +// Consumes: +// - multipart/form-data +// +// responses: +// 200: PreviewImportProjectsReplyV2 +// default: body:GenericResp +func (ctl *DMSController) PreviewImportProjectsV2(c echo.Context) error{ + file, exist, err := ReadFileContent(c, ProjectsFileParamKey) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + if !exist { + return NewErrResp(c, fmt.Errorf("upload file is not exist"), apiError.APIServerErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.PreviewImportProjects(c.Request().Context(), currentUserUid, file) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v2/dms/projects Project ListProjectsV2 +// +// List projects. +// +// responses: +// 200: body:ListProjectReplyV2 +// default: body:GenericResp +func (ctl *DMSController) ListProjectsV2(c echo.Context) error { + req := new(commonApiV2.ListProjectReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.ListProjects(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + + +// swagger:operation PUT /v2/dms/projects/{project_uid} Project UpdateProjectV2 +// +// update a project. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: project +// description: Update a project +// required: true +// in: body +// schema: +// "$ref": "#/definitions/UpdateProjectReqV2" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateProjectV2(c echo.Context) error { + req := &dmsApiV2.UpdateProjectReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.UpdateProject(c.Request().Context(), currentUserUid, req) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + + +// swagger:operation POST /v2/dms/projects/{project_uid}/db_services DBService AddDBServiceV2 +// +// Add DB Service. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_service +// description: Add new db service +// in: body +// required: true +// schema: +// "$ref": "#/definitions/AddDBServiceReqV2" +// responses: +// '200': +// description: AddDBServiceReply +// schema: +// "$ref": "#/definitions/AddDBServiceReply" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) AddDBServiceV2(c echo.Context) error{ + req := new(dmsApiV2.AddDBServiceReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, err := ctl.DMS.AddDBServiceV2(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:operation POST /v2/dms/projects/import_db_services Project ImportDBServicesOfProjectsV2 +// +// Import DBServices. +// +// --- +// parameters: +// - name: db_services +// description: new db services +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ImportDBServicesOfProjectsReqV2" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ImportDBServicesOfProjectsV2(c echo.Context) error { + req := new(dmsApiV2.ImportDBServicesOfProjectsReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.ImportDBServicesOfProjects(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + + +// swagger:operation POST /v2/dms/projects/{project_uid}/db_services/import DBService ImportDBServicesOfOneProjectV2 +// +// Import DBServices. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_services +// description: new db services +// in: body +// required: true +// schema: +// "$ref": "#/definitions/ImportDBServicesOfOneProjectReqV2" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) ImportDBServicesOfOneProjectV2(c echo.Context) error { + req := new(dmsApiV2.ImportDBServicesOfOneProjectReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + err = ctl.DMS.ImportDBServicesOfOneProject(c.Request().Context(), req, currentUserUid) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + return NewOkResp(c) +} + +// swagger:route POST /v2/dms/projects/{project_uid}/db_services/import_check DBService ImportDBServicesOfOneProjectCheckV2 +// +// Import DBServices. +// +// Consumes: +// - multipart/form-data +// +// Produces: +// - application/json +// - text/csv +// +// responses: +// 200: ImportDBServicesCheckCsvReply +// default: body:ImportDBServicesCheckReply +func (ctl *DMSController) ImportDBServicesOfOneProjectCheckV2(c echo.Context) error { + req := new(dmsApiV2.ImportDBServicesOfOneProjectCheckReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + + fileContent, exist, err := ReadFileContent(c, DBServicesFileParamKey) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + if !exist { + return NewErrResp(c, fmt.Errorf("upload file is not exist"), apiError.APIServerErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, csvCheckResult, err := ctl.DMS.ImportDBServicesOfOneProjectCheck(c.Request().Context(), currentUserUid, req.ProjectUid, fileContent) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + if csvCheckResult != nil { + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": "import_db_services_problems.csv"})) + return c.Blob(http.StatusOK, "text/csv", csvCheckResult) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:route POST /v2/dms/projects/import_db_services_check Project ImportDBServicesOfProjectsCheckV2 +// +// Import DBServices. +// +// Consumes: +// - multipart/form-data +// +// Produces: +// - application/json +// - text/csv +// +// responses: +// 200: ImportDBServicesCheckCsvReply +// default: body:ImportDBServicesCheckReply +func (ctl *DMSController) ImportDBServicesOfProjectsCheckV2(c echo.Context) error { + fileContent, exist, err := ReadFileContent(c, DBServicesFileParamKey) + if err != nil { + return NewErrResp(c, err, apiError.APIServerErr) + } + if !exist { + return NewErrResp(c, fmt.Errorf("upload file is not exist"), apiError.APIServerErr) + } + + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + + reply, csvCheckResult, err := ctl.DMS.ImportDBServicesOfProjectsCheck(c.Request().Context(), currentUserUid, fileContent) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + if csvCheckResult != nil { + c.Response().Header().Set(echo.HeaderContentDisposition, + mime.FormatMediaType("attachment", map[string]string{"filename": "import_db_services_problems.csv"})) + return c.Blob(http.StatusOK, "text/csv", csvCheckResult) + } + + return NewOkRespWithReply(c, reply) +} + +// swagger:operation PUT /v2/dms/projects/{project_uid}/db_services/{db_service_uid} DBService UpdateDBServiceV2 +// +// update a DB Service. +// +// --- +// parameters: +// - name: project_uid +// description: project id +// in: path +// required: true +// type: string +// - name: db_service_uid +// description: db_service_uid id +// in: path +// required: true +// type: string +// - name: db_service +// description: Update a DB service +// in: body +// schema: +// "$ref": "#/definitions/UpdateDBServiceReqV2" +// responses: +// '200': +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +// default: +// description: GenericResp +// schema: +// "$ref": "#/definitions/GenericResp" +func (ctl *DMSController) UpdateDBServiceV2(c echo.Context) error{ + req := &dmsApiV2.UpdateDBServiceReq{} + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + // get current user id + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + err = ctl.DMS.UpdateDBService(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkResp(c) +} + +// swagger:route GET /v2/dms/db_services DBService ListGlobalDBServicesV2 +// +// list global DBServices +// +// responses: +// 200: body:ListGlobalDBServicesReplyV2 +// default: body:GenericResp +func (ctl *DMSController) ListGlobalDBServicesV2(c echo.Context) error { + req := new(dmsApiV2.ListGlobalDBServicesReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.ListGlobalDBServices(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} + +// swagger:route GET /v2/dms/projects/{project_uid}/db_services DBService ListDBServicesV2 +// +// List db service. +// +// responses: +// 200: body:ListDBServiceReplyV2 +// default: body:GenericResp +func (ctl *DMSController) ListDBServicesV2(c echo.Context) error { + req := new(commonApiV2.ListDBServiceReq) + err := bindAndValidateReq(c, req) + if nil != err { + return NewErrResp(c, err, apiError.BadRequestErr) + } + currentUserUid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + reply, err := ctl.DMS.ListDBServices(c.Request().Context(), req, currentUserUid) + if nil != err { + return NewErrResp(c, err, apiError.DMSServiceErr) + } + return NewOkRespWithReply(c, reply) +} diff --git a/internal/apiserver/service/middleware.go b/internal/apiserver/service/middleware.go deleted file mode 100644 index faebcdf3a..000000000 --- a/internal/apiserver/service/middleware.go +++ /dev/null @@ -1,105 +0,0 @@ -package service - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "sync" - - pkgConst "github.com/actiontech/dms/internal/apiserver/pkg/constant" - pkgApiError "github.com/actiontech/dms/internal/apiserver/pkg/error" - pkgQueue "github.com/actiontech/dms/pkg/process_queue" - - "github.com/actiontech/dms/pkg/dms-common/api/jwt" - - "github.com/go-kratos/kratos/v2/log" - "github.com/labstack/echo/v4" -) - -var controllerProcessRecordsMaker sync.Once -var controllerProcessRecordsInstance *pkgQueue.ProcessRecordQueue - -type ResponseBodyWriter struct { - io.Writer - http.ResponseWriter - http.Flusher -} - -func (w *ResponseBodyWriter) Write(b []byte) (int, error) { - return w.Writer.Write(b) -} - -func (w *ResponseBodyWriter) WriteHeader(statusCode int) { - w.ResponseWriter.WriteHeader(statusCode) -} - -func (w *ResponseBodyWriter) Flush() { - if responseFlush, ok := w.ResponseWriter.(http.Flusher); ok { - responseFlush.Flush() - } -} - -// echo middleware for process record -func ProcessRecordMiddleware(logger log.Logger) echo.MiddlewareFunc { - log := log.NewHelper(log.With(logger, "middleware", "process_record")) - controllerProcessRecordsMaker.Do(func() { - controllerProcessRecordsInstance = pkgQueue.NewProcessRecordQueue(logger, pkgConst.ProcessRecordFile) - }) - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) (err error) { - req := c.Request() - if req.Method == "GET" { - return next(c) - } - - userUid, err := jwt.GetUserUidStrFromContext(c) - if err != nil { - log.Debugf("get user from context error: %v, skip user uid in record", err) - } else { - log.Debugf("get user from context: %v", userUid) - } - - p := controllerProcessRecordsInstance.Push(userUid, req.RequestURI) - - resBody := new(bytes.Buffer) - mw := io.MultiWriter(c.Response().Writer, resBody) - writer := &ResponseBodyWriter{ - Writer: mw, - ResponseWriter: c.Response().Writer, - } - - c.Response().Writer = writer - - if err = next(c); err != nil { - c.Error(err) - } - - responseBody := resBody.Bytes() - - var response map[string]interface{} - errorCode := fmt.Sprintf("%v", pkgApiError.Unknown) - errorMessage := "" - httpCode := c.Response().Status - - if err := json.Unmarshal(responseBody, &response); err == nil { - if val, ok := response["code"]; ok { - errorCode = fmt.Sprintf("%v", val) - } - errorMessage = fmt.Sprintf("%v", response["msg"]) - } else { - errorMessage = fmt.Sprintf("failed to unmarshal response body: %v", err) - } - - // update and persistent operation log - { - p.UpdateRecord(httpCode, errorCode, errorMessage) - - controllerProcessRecordsInstance.Save() - } - - return - } - } -} diff --git a/internal/apiserver/service/router.go b/internal/apiserver/service/router.go index 7631e428b..825f1d880 100644 --- a/internal/apiserver/service/router.go +++ b/internal/apiserver/service/router.go @@ -2,24 +2,46 @@ package service import ( "fmt" + "net/http" "strings" - pkgLog "github.com/actiontech/dms/internal/pkg/log" - + dmsMiddleware "github.com/actiontech/dms/internal/apiserver/middleware" + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/pkg/locale" + "github.com/actiontech/dms/internal/pkg/utils" + sqlWorkbenchService "github.com/actiontech/dms/internal/sql_workbench/service" dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - + dmsV2 "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + commonLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" echojwt "github.com/labstack/echo-jwt/v4" - - "github.com/go-kratos/kratos/v2/log" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) func (s *APIServer) initRouter() error { - v1 := s.echo.Group(dmsV1.CurrentGroupVersion) + s.echo.GET("/swagger/*", s.DMSController.SwaggerHandler, SwaggerMiddleWare) + v1 := s.echo.Group(dmsV1.CurrentGroupVersion) + if err := s.initRouterDMS(v1); err != nil { + return err + } + v2 := s.echo.Group(dmsV2.CurrentGroupVersion) // DMS RESTful resource { + { + v1.GET("/dms/basic_info", s.DMSController.GetBasicInfo) + v1.GET(biz.PersonalizationUrl, s.DMSController.GetStaticLogo) + v1.POST("/dms/personalization", s.DMSController.Personalization) + v1.GET("/dms/db_services/driver_options", s.DMSController.ListDBServiceDriverOption) + v1.GET("/dms/db_services", s.DeprecatedBy(dmsV2.GroupV2)) + v1.GET("/dms/db_services/tips", s.DMSController.ListGlobalDBServicesTips) + } + { + v2.GET("/dms/db_services", s.DMSController.ListGlobalDBServicesV2) + } + dmsProxyV1 := v1.Group(dmsV1.ProxyRouterGroup) dmsProxyV1.POST("", s.DMSController.RegisterDMSProxyTarget) @@ -27,24 +49,58 @@ func (s *APIServer) initRouter() error { dmsPluginV1.POST("", s.DMSController.RegisterDMSPlugin) dbServiceV1 := v1.Group(dmsV1.DBServiceRouterGroup) - dbServiceV1.POST("", s.DMSController.AddDBService) - dbServiceV1.GET("", s.DMSController.ListDBServices) - dbServiceV1.DELETE("/:db_service_uid", s.DMSController.DelDBService) - dbServiceV1.PUT("/:db_service_uid", s.DMSController.UpdateDBService) - dbServiceV1.POST("/connect", s.DMSController.CheckDBServiceIsConnectable) + { + dbServiceV1.POST("", s.DeprecatedBy(dmsV2.GroupV2)) + dbServiceV1.GET("", s.DMSController.ListDBServicesV2) // 兼容jet brain插件,临时开放v1接口 + dbServiceV1.GET("/tips", s.DMSController.ListDBServiceTips) + dbServiceV1.DELETE("/:db_service_uid", s.DMSController.DelDBService) + dbServiceV1.PUT("/:db_service_uid", s.DeprecatedBy(dmsV2.GroupV2)) + dbServiceV1.POST("/connection", s.DMSController.CheckDBServiceIsConnectable) + dbServiceV1.POST("/:db_service_uid/connection", s.DMSController.CheckDBServiceIsConnectableById) + dbServiceV1.POST("/connections", s.DMSController.CheckProjectDBServicesConnections) + dbServiceV1.POST("/import_check", s.DeprecatedBy(dmsV2.GroupV2)) + dbServiceV1.POST("/import", s.DeprecatedBy(dmsV2.GroupV2)) + } + + dbServiceV2 := v2.Group(dmsV2.DBServiceRouterGroup) + { + dbServiceV2.POST("", s.DMSController.AddDBServiceV2) + dbServiceV2.POST("/import_check", s.DMSController.ImportDBServicesOfOneProjectCheckV2) + dbServiceV2.POST("/import", s.DMSController.ImportDBServicesOfOneProjectV2) + dbServiceV2.PUT("/:db_service_uid", s.DMSController.UpdateDBServiceV2) + dbServiceV2.GET("", s.DMSController.ListDBServicesV2) + } + environmentTagV1 := v1.Group(dmsV1.DBEnvironmentTagGroup) + environmentTagV1.POST("", s.DMSController.CreateEnvironmentTag) + environmentTagV1.GET("", s.DMSController.ListEnvironmentTags) + environmentTagV1.PUT("/:environment_tag_uid", s.DMSController.UpdateEnvironmentTag) + environmentTagV1.DELETE("/:environment_tag_uid", s.DMSController.DeleteEnvironmentTag) + + dbServiceSyncTaskV1 := v1.Group("/dms/db_service_sync_tasks") + dbServiceSyncTaskV1.GET("/tips", s.DMSController.ListDBServiceSyncTaskTips) + dbServiceSyncTaskV1.GET("", s.DMSController.ListDBServiceSyncTasks) + dbServiceSyncTaskV1.POST("", s.DMSController.AddDBServiceSyncTask) + dbServiceSyncTaskV1.GET("/:db_service_sync_task_uid", s.DMSController.GetDBServiceSyncTask) + dbServiceSyncTaskV1.PUT("/:db_service_sync_task_uid", s.DMSController.UpdateDBServiceSyncTask) + dbServiceSyncTaskV1.DELETE("/:db_service_sync_task_uid", s.DMSController.DeleteDBServiceSyncTask) + dbServiceSyncTaskV1.POST("/:db_service_sync_task_uid/sync", s.DMSController.SyncDBServices) userV1 := v1.Group(dmsV1.UserRouterGroup) - userV1.POST("", s.DMSController.AddUser) + userV1.POST("", s.DMSController.AddUser, s.DMSController.DMS.GatewayUsecase.Broadcast()) userV1.GET("", s.DMSController.ListUsers) userV1.GET("/:user_uid", s.DMSController.GetUser) - userV1.DELETE("/:user_uid", s.DMSController.DelUser) - userV1.PUT("/:user_uid", s.DMSController.UpdateUser) - // userV1.DELETE("/batch", s.APIAdminController.DMSDelUserBatch) + userV1.DELETE("/:user_uid", s.DMSController.DelUser, s.DMSController.DMS.GatewayUsecase.Broadcast()) + userV1.PUT("/:user_uid", s.DMSController.UpdateUser, s.DMSController.DMS.GatewayUsecase.Broadcast()) userV1.GET(dmsV1.GetUserOpPermissionRouterWithoutPrefix(":user_uid"), s.DMSController.GetUserOpPermission) + userV1.PUT("", s.DMSController.UpdateCurrentUser, s.DMSController.DMS.GatewayUsecase.Broadcast()) + userV1.POST("/gen_token", s.DMSController.GenAccessToken) + userV1.POST("/verify_user_login", s.DMSController.VerifyUserLogin) sessionv1 := v1.Group(dmsV1.SessionRouterGroup) sessionv1.POST("", s.DMSController.AddSession) sessionv1.GET("/user", s.DMSController.GetUserBySession) + sessionv1.DELETE("", s.DMSController.DelSession) + sessionv1.POST("/refresh", s.DMSController.RefreshSession) userGroupV1 := v1.Group("/dms/user_groups") userGroupV1.POST("", s.DMSController.AddUserGroup) @@ -60,30 +116,69 @@ func (s *APIServer) initRouter() error { memberV1 := v1.Group(dmsV1.MemberRouterGroup) memberV1.POST("", s.DMSController.AddMember) + memberV1.GET("/tips", s.DMSController.ListMemberTips) memberV1.GET("", s.DMSController.ListMembers) memberV1.GET(dmsV1.MemberForInternalRouterSuffix, s.DMSController.ListMembersForInternal) memberV1.DELETE("/:member_uid", s.DMSController.DelMember) memberV1.PUT("/:member_uid", s.DMSController.UpdateMember) + memberGroupV1 := v1.Group("/dms/projects/:project_uid/member_groups") + memberGroupV1.GET("", s.DMSController.ListMemberGroups) + memberGroupV1.GET("/tips", s.DMSController.ListMemberGroupTips) + memberGroupV1.GET("/:member_group_uid", s.DMSController.GetMemberGroup) + memberGroupV1.POST("", s.DMSController.AddMemberGroup) + memberGroupV1.PUT("/:member_group_uid", s.DMSController.UpdateMemberGroup) + memberGroupV1.DELETE("/:member_group_uid", s.DMSController.DeleteMemberGroup) + opPermissionV1 := v1.Group("/dms/op_permissions") opPermissionV1.GET("", s.DMSController.ListOpPermissions) - namespaceV1 := v1.Group(dmsV1.NamespaceRouterGroup) - namespaceV1.GET("", s.DMSController.ListNamespaces) - namespaceV1.POST("", s.DMSController.AddNamespace) - namespaceV1.DELETE("/:namespace_uid", s.DMSController.DelNamespace) - namespaceV1.PUT("/:namespace_uid", s.DMSController.UpdateNamespace) - namespaceV1.PUT("/:namespace_uid/archive", s.DMSController.ArchiveNamespace) - namespaceV1.PUT("/:namespace_uid/unarchive", s.DMSController.UnarchiveNamespace) + projectV1 := v1.Group(dmsV2.ProjectRouterGroup) + projectV1.GET("", s.DMSController.ListProjectsV2) // 兼容jet brain插件,临时开放v1接口 + projectV1.POST("", s.DeprecatedBy(dmsV2.GroupV2)) + projectV1.DELETE("/:project_uid", s.DMSController.DelProject) + projectV1.PUT("/:project_uid", s.DeprecatedBy(dmsV2.GroupV2)) + projectV1.PUT("/:project_uid/archive", s.DMSController.ArchiveProject) + projectV1.PUT("/:project_uid/unarchive", s.DMSController.UnarchiveProject) + projectV1.POST("/import", s.DeprecatedBy(dmsV2.GroupV2)) + projectV1.GET("/import_template", s.DMSController.GetImportProjectsTemplate) + projectV1.POST("/preview_import", s.DeprecatedBy(dmsV2.GroupV2)) + projectV1.GET("/export", s.DMSController.ExportProjects) + projectV1.GET("/tips", s.DMSController.GetProjectTips) + projectV1.GET("/import_db_services_template", s.DMSController.GetImportDBServicesTemplate) + projectV1.POST("/import_db_services_check", s.DeprecatedBy(dmsV2.GroupV2)) + projectV1.POST("/import_db_services", s.DeprecatedBy(dmsV2.GroupV2)) + projectV1.POST("/db_services_connection", s.DeprecatedBy(dmsV2.GroupV2)) + projectV1.POST("/check_db_services_privileges", s.DMSController.CheckDBServicesPrivileges) + projectV1.POST("/db_services_connections", s.DMSController.CheckGlobalDBServicesConnections) + projectV1.POST("/business_tags", s.DMSController.CreateBusinessTag) + projectV1.GET("/business_tags", s.DMSController.ListBusinessTags) + projectV1.PUT("/business_tags/:business_tag_uid", s.DMSController.UpdateBusinessTag) + projectV1.DELETE("/business_tags/:business_tag_uid", s.DMSController.DeleteBusinessTag) + + resourceOverviewV1 := v1.Group("/dms/resource_overview") + resourceOverviewV1.GET("/statistics", s.DMSController.GetResourceOverviewStatistics) + resourceOverviewV1.GET("/resource_type_distribution", s.DMSController.GetResourceOverviewResourceTypeDistribution) + resourceOverviewV1.GET("/topology", s.DMSController.GetResourceOverviewTopology) + resourceOverviewV1.GET("/resource_list", s.DMSController.GetResourceOverviewResourceList) + resourceOverviewV1.GET("/download", s.DMSController.DownloadResourceOverviewList) // oauth2 interface does not require login authentication oauth2V1 := v1.Group("/dms/oauth2") oauth2V1.GET("/tips", s.DMSController.GetOauth2Tips) - oauth2V1.GET("/link", s.DMSController.Oauth2Link) - oauth2V1.GET("/callback", s.DMSController.Oauth2Callback) + oauth2V1.GET("/link", s.DMSController.Oauth2LinkOrCallback) + oauth2V1.GET("/callback", s.DMSController.Oauth2LinkOrCallback) oauth2V1.POST("/user/bind", s.DMSController.BindOauth2User) + oauth2V1.POST(biz.BackChannelLogoutUri, s.DMSController.BackChannelLogout) + + // company notice + companyNoticeV1 := v1.Group("/dms/company_notice") + companyNoticeV1.GET("", s.DMSController.GetCompanyNotice) + companyNoticeV1.PATCH("", s.DMSController.UpdateCompanyNotice) /* TODO AdminUserAllowed()*/ configurationV1 := v1.Group("/dms/configurations") + configurationV1.GET("/login/tips", s.DMSController.GetLoginTips) + configurationV1.PATCH("/login", s.DMSController.UpdateLoginConfiguration) /* TODO AdminUserAllowed()*/ configurationV1.GET("/oauth2", s.DMSController.GetOauth2Configuration) /* TODO AdminUserAllowed()*/ configurationV1.PATCH("/oauth2", s.DMSController.UpdateOauth2Configuration) /* TODO AdminUserAllowed()*/ configurationV1.GET("/ldap", s.DMSController.GetLDAPConfiguration) /* TODO AdminUserAllowed()*/ @@ -100,8 +195,20 @@ func (s *APIServer) initRouter() error { configurationV1.GET("/webhook", s.DMSController.GetWebHookConfiguration) /* TODO AdminUserAllowed()*/ configurationV1.PATCH("/webhook", s.DMSController.UpdateWebHookConfiguration) /* TODO AdminUserAllowed()*/ configurationV1.POST("/webhook/test", s.DMSController.TestWebHookConfiguration) /* TODO AdminUserAllowed()*/ - configurationV1.GET("/sql_query", s.CloudbeaverController.GetSQLQueryConfiguration) - + configurationV1.GET("/sql_query", s.SqlWorkbenchController.GetSQLQueryConfiguration) + configurationV1.GET("/sms", s.DMSController.GetSmsConfiguration) /* TODO AdminUserAllowed()*/ + configurationV1.POST("/sms/test", s.DMSController.TestSmsConfiguration) + configurationV1.PATCH("/sms", s.DMSController.UpdateSmsConfiguration) + configurationV1.POST("/sms/send_code", s.DMSController.SendSmsCode) + configurationV1.POST("/sms/verify_code", s.DMSController.VerifySmsCode) + + configurationV1.GET("/license", s.DMSController.GetLicense) /* TODO AdminUserAllowed()*/ + configurationV1.POST("/license", s.DMSController.SetLicense) /* TODO AdminUserAllowed()*/ + configurationV1.GET("/license/info", s.DMSController.GetLicenseInfo) /* TODO AdminUserAllowed()*/ + configurationV1.POST("/license/check", s.DMSController.CheckLicense) /* TODO AdminUserAllowed()*/ + configurationV1.GET("/license/usage", s.DMSController.GetLicenseUsage) /* TODO AdminUserAllowed()*/ + configurationV1.GET("/system_variables", s.DMSController.GetSystemVariables) /* TODO AdminUserAllowed()*/ + configurationV1.PATCH("/system_variables", s.DMSController.UpdateSystemVariables) /* TODO AdminUserAllowed()*/ // notify notificationV1 := v1.Group(dmsV1.NotificationRouterGroup) notificationV1.POST("", s.DMSController.Notify) /* TODO AdminUserAllowed()*/ @@ -109,38 +216,228 @@ func (s *APIServer) initRouter() error { webhookV1 := v1.Group(dmsV1.WebHookRouterGroup) webhookV1.POST("", s.DMSController.WebHookSendMessage) /* TODO AdminUserAllowed()*/ - if s.CloudbeaverController.CloudbeaverService.CloudbeaverUsecase.IsCloudbeaverConfigured() { - cloudbeaverV1 := s.echo.Group(s.CloudbeaverController.CloudbeaverService.CloudbeaverUsecase.GetRootUri()) - targets, err := s.CloudbeaverController.CloudbeaverService.ProxyUsecase.GetCloudbeaverProxyTarget() + dataExportWorkflowsV1 := v1.Group("/dms/projects/:project_uid/data_export_workflows") + dataExportWorkflowsV1.POST("", s.DMSController.AddDataExportWorkflow) + dataExportWorkflowsV1.GET("", s.DMSController.ListDataExportWorkflows) + dataExportWorkflowsV1.GET("/:data_export_workflow_uid", s.DMSController.GetDataExportWorkflow) + dataExportWorkflowsV1.POST("/:data_export_workflow_uid/approve", s.DMSController.ApproveDataExportWorkflow) + dataExportWorkflowsV1.POST("/:data_export_workflow_uid/reject", s.DMSController.RejectDataExportWorkflow) + dataExportWorkflowsV1.POST("/:data_export_workflow_uid/export", s.DMSController.ExportDataExportWorkflow) + dataExportWorkflowsV1.POST("/cancel", s.DMSController.CancelDataExportWorkflow) + + // 内部接口,仅允许sys用户访问 + dataExportWorkflowsDashboardV1 := v1.Group("/dms/dashboard/data_export_workflows") + dataExportWorkflowsDashboardV1.GET("", s.DMSController.GetGlobalDataExportWorkflows) + + allDataExportWorkflowsV1 := v1.Group("/dms/projects/data_export_workflows") + allDataExportWorkflowsV1.GET("", s.DMSController.ListAllDataExportWorkflows) + + dataExportTaskV1 := v1.Group("/dms/projects/:project_uid/data_export_tasks") + dataExportTaskV1.POST("", s.DMSController.AddDataExportTask) + dataExportTaskV1.GET("", s.DMSController.BatchGetDataExportTask) + dataExportTaskV1.GET("/:data_export_task_uid/data_export_task_sqls", s.DMSController.ListDataExportTaskSQLs) + dataExportTaskV1.GET("/:data_export_task_uid/data_export_task_sqls/download", s.DMSController.DownloadDataExportTaskSQLs) + dataExportTaskV1.GET("/:data_export_task_uid/download", s.DMSController.DownloadDataExportTask) + + cbOperationLogsV1 := v1.Group("/dms/projects/:project_uid/cb_operation_logs") + cbOperationLogsV1.GET("", s.DMSController.ListCBOperationLogs) + cbOperationLogsV1.GET("/export", s.DMSController.ExportCBOperationLogs) + cbOperationLogsV1.GET("/tips", s.DMSController.GetCBOperationLogTips) + + operationRecordV1 := v1.Group("/dms/operation_records") + operationRecordV1.POST("", s.DMSController.AddOperationRecord) + operationRecordV1.GET("", s.DMSController.GetOperationRecordList) + operationRecordV1.GET("/exports", s.DMSController.ExportOperationRecordList) + + gatewayV1 := v1.Group("/dms/gateways") + + gatewayV1.POST("", s.DMSController.AddGateway) + gatewayV1.DELETE("/:gateway_id", s.DMSController.DeleteGateway) + gatewayV1.PUT("/:gateway_id", s.DMSController.UpdateGateway) + gatewayV1.GET("/:gateway_id", s.DMSController.GetGateway) + gatewayV1.GET("", s.DMSController.ListGateways) + gatewayV1.GET("/tips", s.DMSController.GetGatewayTips) + gatewayV1.PUT("/", s.DMSController.SyncGateways, s.DMSController.DMS.GatewayUsecase.Broadcast()) + + if s.SqlWorkbenchController.CloudbeaverService.CloudbeaverUsecase.IsCloudbeaverConfigured() { + cloudbeaverV1 := s.echo.Group(s.SqlWorkbenchController.CloudbeaverService.CloudbeaverUsecase.GetRootUri()) + targets, err := s.SqlWorkbenchController.CloudbeaverService.ProxyUsecase.GetCloudbeaverProxyTarget() if err != nil { return err } - cloudbeaverV1.Use(s.CloudbeaverController.CloudbeaverService.CloudbeaverUsecase.Login()) - cloudbeaverV1.Use(s.CloudbeaverController.CloudbeaverService.CloudbeaverUsecase.GraphQLDistributor()) + cloudbeaverV1.Use(s.SqlWorkbenchController.CloudbeaverService.CloudbeaverUsecase.Login()) + cloudbeaverV1.Use(s.SqlWorkbenchController.CloudbeaverService.CloudbeaverUsecase.GraphQLDistributor()) cloudbeaverV1.Use(middleware.ProxyWithConfig(middleware.ProxyConfig{ Skipper: middleware.DefaultSkipper, Balancer: middleware.NewRandomBalancer(targets), })) } + + if s.SqlWorkbenchController.SqlWorkbenchService.IsConfigured() { + sqlWorkbenchV1 := s.echo.Group(s.SqlWorkbenchController.SqlWorkbenchService.GetRootUri()) + targets, err := s.SqlWorkbenchController.SqlWorkbenchService.GetOdcProxyTarget() + if err != nil { + return err + } + + sqlWorkbenchV1.Use(s.SqlWorkbenchController.SqlWorkbenchService.Login()) + + // 添加操作日志记录中间件 + sqlWorkbenchV1.Use(sqlWorkbenchService.GetOperationLogBodyDumpMiddleware(sqlWorkbenchService.OperationLogMiddlewareConfig{ + CbOperationLogUsecase: s.DMSController.DMS.CbOperationLogUsecase, + DBServiceUsecase: s.DMSController.DMS.DBServiceUsecase, + SqlWorkbenchService: s.SqlWorkbenchController.SqlWorkbenchService, + })) + + sqlWorkbenchV1.Use(s.SqlWorkbenchController.SqlWorkbenchService.AuditMiddleware()) + sqlWorkbenchV1.Use(middleware.ProxyWithConfig(middleware.ProxyConfig{ + Skipper: middleware.DefaultSkipper, + Balancer: middleware.NewRandomBalancer(targets), + Rewrite: map[string]string{ + "/odc_query": "/", + "/odc_query/*": "/$1", + }, + })) + } + } + + { + projectV2 := v2.Group(dmsV2.ProjectRouterGroup) + projectV2.POST("", s.DMSController.AddProjectV2) + projectV2.GET("", s.DMSController.ListProjectsV2) + projectV2.PUT("/:project_uid", s.DMSController.UpdateProjectV2) + projectV2.POST("/import", s.DMSController.ImportProjectsV2) + projectV2.POST("/preview_import", s.DMSController.PreviewImportProjectsV2) + projectV2.POST("/import_db_services_check", s.DMSController.ImportDBServicesOfProjectsCheckV2) + projectV2.POST("/import_db_services", s.DMSController.ImportDBServicesOfProjectsV2) } return nil } +func SwaggerMiddleWare(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + // swagger 请求分为两种,一种是swagger html页面请求,一种是swagger json请求. eg: + // swagger/index.html 获取html + // swagger/dms/doc.yaml 获取json + hasPkPrefix := strings.HasPrefix(c.Request().RequestURI, "/swagger/index.html?urls.primaryName=") + if hasPkPrefix { + // 为了避免404 + c.Request().RequestURI = "/swagger/index.html" + } + + return next(c) + } +} + +// 解码 Gzip 数据 +func decodeGzip(data []byte) string { + gzipBytes, err := utils.DecodeGzipBytes(data) + if err != nil { + return fmt.Sprintf("Gzip decode error: %v", err) + } + return string(gzipBytes) +} + func (s *APIServer) installMiddleware() error { + allowedMethods := []string{"GET", "POST", "PUT", "DELETE", "PATCH"} + s.echo.Use(func(allowedMethods []string) echo.MiddlewareFunc { + methodSet := make(map[string]struct{}) + for _, m := range allowedMethods { + methodSet[strings.ToUpper(m)] = struct{}{} + } + + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if _, ok := methodSet[strings.ToUpper(c.Request().Method)]; !ok { + return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed") + } + return next(c) + } + } + }(allowedMethods)) + + var skipJWTPaths = []string{ + dmsV1.SessionRouterGroup, + "/v1/dms/sessions/refresh", + "/v1/dms/oauth2", + "/v1/dms/configurations/login/tips", + "/v1/dms/personalization/logo", + "/v1/dms/configurations/license", + "/v1/dms/users/verify_user_login", + "/v1/dms/configurations/sms/send_code", + "/v1/dms/configurations/sms/verify_code", + "/v1/dms/basic_info", + } + var notSkipJWTPaths = []string{ + sqlWorkbenchService.SQL_WORKBENCH_URL, + } + s.echo.Use(dmsMiddleware.JWTTokenAdapter(), echojwt.WithConfig(echojwt.Config{ + Skipper: middleware.Skipper(func(c echo.Context) bool { + uri := c.Request().RequestURI + for _, skipPath := range skipJWTPaths { + if strings.HasSuffix(uri, skipPath) || strings.HasPrefix(uri, skipPath) { + return true + } + } + for _, notSkipPath := range notSkipJWTPaths { + if strings.HasSuffix(uri, notSkipPath) || strings.HasPrefix(uri, notSkipPath) { + return false + } + } + // Non-DMS component's own uri + return !(strings.HasPrefix(uri, dmsV1.CurrentGroupVersion) || strings.HasPrefix(uri, dmsV2.CurrentGroupVersion)) + }), + SigningKey: dmsV1.JwtSigningKey, + TokenLookup: "cookie:dms-token,header:Authorization:Bearer ", // tell the middleware where to get token: from cookie and header, + })) + s.echo.Use(s.DMSController.DMS.Oauth2ConfigurationUsecase.CheckBackChannelLogoutEvent()) + // middleware gateway + s.echo.Use(middleware.ProxyWithConfig(middleware.ProxyConfig{ + Skipper: s.DMSController.DMS.GatewayUsecase.Skipper, + Balancer: s.DMSController.DMS.GatewayUsecase, + })) + // Middleware - s.echo.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ + s.echo.Use(middleware.BodyDumpWithConfig(middleware.BodyDumpConfig{ + Skipper: func(c echo.Context) bool { + return !strings.HasPrefix(c.Request().RequestURI, dmsV1.GroupV1) + }, + Handler: func(context echo.Context, req []byte, reply []byte) { + userUid, _ := jwt.GetUserUidStrFromContext(context) + + // 将请求转为字符串 + reqStr := string(req) + // 尝试解码 reply(gzip 格式) + var replyStr string + if utils.IsGzip(reply) { + replyStr = decodeGzip(reply) + } else { + replyStr = string(reply) + } + + commonLog.NewHelper(s.logger).Log( + commonLog.LevelDebug, + "middleware.uri", context.Request().RequestURI, + "user_id", userUid, + "req", reqStr, // 输出处理后的请求数据 + "reply", replyStr, // 输出处理后的响应数据 + ) + }, + })) + + s.echo.Use(middleware.GzipWithConfig(middleware.GzipConfig{ Skipper: middleware.DefaultSkipper, - Format: `${time_custom} ECHO id:${id}, remote_ip:${remote_ip}, ` + - `host:${host}, method:${method}, uri:${uri}, user_agent:${user_agent}, ` + - `status:${status}, error:${error}, latency:${latency}, latency_human:${latency_human}` + - `, bytes_in:${bytes_in}, bytes_out:${bytes_out}` + "\n", - CustomTimeFormat: pkgLog.LogTimeLayout, + Level: 5, })) s.echo.Use(middleware.StaticWithConfig(middleware.StaticConfig{ Skipper: middleware.Skipper(func(c echo.Context) bool { - if strings.HasPrefix(c.Request().URL.Path, s.CloudbeaverController.CloudbeaverService.CloudbeaverUsecase.GetRootUri()) { + if strings.HasPrefix(c.Request().URL.Path, s.SqlWorkbenchController.CloudbeaverService.CloudbeaverUsecase.GetRootUri()) { + return true + } + if strings.HasPrefix(c.Request().URL.Path, "/provision/v") || + strings.HasPrefix(c.Request().URL.Path, "/sqle/v") { return true } @@ -151,51 +448,42 @@ func (s *APIServer) installMiddleware() error { HTML5: true, Browse: false, })) + s.echo.Match(allowedMethods, "", echo.NotFoundHandler) + s.echo.Match(allowedMethods, "/*", echo.NotFoundHandler) - s.echo.Use(echojwt.WithConfig(echojwt.Config{ - Skipper: middleware.Skipper(func(c echo.Context) bool { - logger := log.NewHelper(log.With(pkgLog.NewKLogWrapper(s.logger), "middleware", "jwt")) - if strings.HasSuffix(c.Request().RequestURI, dmsV1.SessionRouterGroup) || - strings.HasPrefix(c.Request().RequestURI, "/v1/dms/oauth2" /* TODO 使用统一方法skip */) || - !strings.HasPrefix(c.Request().RequestURI, dmsV1.CurrentGroupVersion) { - logger.Debugf("skipper url jwt check: %v", c.Request().RequestURI) - return true - } - return false - }), - SigningKey: dmsV1.JwtSigningKey, - })) + s.echo.Use(dmsMiddleware.LicenseAdapter(s.DMSController.DMS.LicenseUsecase)) - s.echo.Use(ProcessRecordMiddleware(pkgLog.NewKLogWrapper(s.logger))) + s.echo.Use(s.DMSController.DMS.AuthAccessTokenUseCase.CheckLatestAccessToken()) s.echo.Use(middleware.ProxyWithConfig(middleware.ProxyConfig{ Skipper: s.DMSController.DMS.DmsProxyUsecase.GetEchoProxySkipper(), Balancer: s.DMSController.DMS.DmsProxyUsecase.GetEchoProxyBalancer(), Rewrite: s.DMSController.DMS.DmsProxyUsecase.GetEchoProxyRewrite(), })) + + s.echo.Use(locale.Bundle.EchoMiddlewareByCustomFunc( + s.DMSController.DMS.UserUsecase.GetUserLanguageByEchoCtx, + i18nPkg.GetLangByAcceptLanguage, + )) + + s.echo.Use(dmsMiddleware.OperationRecordMiddleware(s.DMSController.DMS)) + return nil } func (s *APIServer) installController() error { - - // authController, err := NewAuthController(pkgLog.NewKLogWrapper(s.logger), s.opts) - // if nil != err { - // return fmt.Errorf("failed to create authController: %v", err) - // } - // s.AuthController = authController - - DMSController, err := NewDMSController(s.logger, s.opts) + sqlWorkbenchController, err := NewSqlWorkbenchController(s.logger, s.opts) if nil != err { - return fmt.Errorf("failed to create DMSController: %v", err) + return fmt.Errorf("failed to create SqlWorkbenchController: %v", err) } - cloudbeaverController, err := NewCloudbeaverController(s.logger, s.opts) + DMSController, err := NewDMSController(s.logger, s.opts, sqlWorkbenchController.CloudbeaverService) if nil != err { - return fmt.Errorf("failed to create CloudbeaverController: %v", err) + return fmt.Errorf("failed to create DMSController: %v", err) } s.DMSController = DMSController - s.CloudbeaverController = cloudbeaverController + s.SqlWorkbenchController = sqlWorkbenchController // s.AuthController.RegisterPlugin(s.DMSController.GetRegisterPluginFn()) return nil @@ -210,3 +498,11 @@ func (s *APIServer) Shutdown() error { } return nil } + +// DeprecatedBy is a controller used to mark deprecated and used to replace the original controller. +func (s *APIServer) DeprecatedBy(version string) func(echo.Context) error { + return func(ctx echo.Context) error { + return echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf( + "the API has been deprecated, please using the %s version", version)) + } +} diff --git a/internal/apiserver/service/router_dms_ce.go b/internal/apiserver/service/router_dms_ce.go new file mode 100644 index 000000000..eb606e4f7 --- /dev/null +++ b/internal/apiserver/service/router_dms_ce.go @@ -0,0 +1,9 @@ +//go:build !dms + +package service + +import "github.com/labstack/echo/v4" + +func (s *APIServer) initRouterDMS(v1 *echo.Group) error { + return nil +} diff --git a/internal/apiserver/service/service.go b/internal/apiserver/service/service.go index 26e6527d4..b507b425c 100644 --- a/internal/apiserver/service/service.go +++ b/internal/apiserver/service/service.go @@ -2,54 +2,77 @@ // // Documentation of our dms API. // -// Schemes: http, https -// BasePath: / -// Version: 0.1.0 +// Schemes: http, https +// BasePath: / +// Version: 0.1.0 // -// Consumes: -// - application/json +// Consumes: +// - application/json // -// Produces: -// - application/json +// Produces: +// - application/json // -// Security: -// - basic +// Security: +// - basic // // SecurityDefinitions: // basic: -// type: basic +// type: apiKey +// in: header +// name: Authorization // // swagger:meta package service import ( + "crypto/tls" "fmt" "net/http" - bV1 "github.com/actiontech/dms/api/base/v1" "github.com/actiontech/dms/internal/apiserver/conf" apiError "github.com/actiontech/dms/internal/apiserver/pkg/error" + bV1 "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + "github.com/labstack/echo/v4" utilConf "github.com/actiontech/dms/pkg/dms-common/pkg/config" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" - "github.com/labstack/echo/v4" ) type APIServer struct { DMSController *DMSController - CloudbeaverController *CloudbeaverController + SqlWorkbenchController *SqlWorkbenchController // more controllers echo *echo.Echo - opts *conf.Options + opts *conf.DMSOptions logger utilLog.Logger } -func NewAPIServer(logger utilLog.Logger, opts *conf.Options) (*APIServer, error) { +func NewAPIServer(logger utilLog.Logger, opts *conf.DMSOptions) (*APIServer, error) { + e := echo.New() + e.HideBanner = true + e.HidePort = true + e.HTTPErrorHandler = func(err error, c echo.Context) { + if c.Response().Committed { + return + } + + message := err.Error() + if httpErr, ok := err.(*echo.HTTPError); ok { + if msg, ok := httpErr.Message.(string); ok && msg != "" { + message = msg + } + } + + _ = c.JSON(http.StatusBadRequest, bV1.GenericResp{ + Code: int(apiError.BadRequestErr), + Message: message, + }) + } return &APIServer{ logger: logger, opts: opts, - echo: echo.New(), + echo: e, }, nil } @@ -57,23 +80,74 @@ func (s *APIServer) RunHttpServer(logger utilLog.Logger) error { if err := s.installController(); nil != err { return fmt.Errorf("failed to install controller: %v", err) } + + if s.opts.EnableClusterMode { + if s.opts.ServerId == "" { + return fmt.Errorf("server id is required on cluster mode") + } + + if s.opts.ReportHost == "" { + return fmt.Errorf("report host is required on cluster mode") + } + + s.DMSController.DMS.ClusterUsecase.SetClusterMode(true) + if err := s.DMSController.DMS.ClusterUsecase.Join(s.opts.ServerId); err != nil { + return err + } + + defer s.DMSController.DMS.ClusterUsecase.Leave() + } + if err := s.installMiddleware(); nil != err { return fmt.Errorf("failed to install middleware: %v", err) } if err := s.initRouter(); nil != err { return fmt.Errorf("failed to init router: %v", err) } - - if err := s.echo.Start(s.opts.GetAPIServer().GetHTTPAddr()); nil != err { - if err != http.ErrServerClosed { - return fmt.Errorf("failed to run http server: %v", err) + if s.opts.APIServiceOpts.EnableHttps { + if s.opts.APIServiceOpts.CertFilePath == "" || s.opts.APIServiceOpts.KeyFilePath == "" { + return fmt.Errorf("cert file path and key file path are required on https mode") + } + // 自定义 TLS 配置 + tlsConfig := &tls.Config{ + MinVersion: tls.VersionTLS12, // 禁用 TLS1.0 和 TLS1.1 + CipherSuites: []uint16{ + tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, + tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, + // 你可以添加你信任的其他套件,但不要添加 TLS_RSA_WITH_3DES_EDE_CBC_SHA + }, + PreferServerCipherSuites: true, + } + // 启动 HTTPS 服务器 + server := &http.Server{ + Addr: s.opts.GetAPIServer().GetHTTPAddr(), + Handler: s.echo, + TLSConfig: tlsConfig, + } + err := server.ListenAndServeTLS(s.opts.APIServiceOpts.CertFilePath, s.opts.APIServiceOpts.KeyFilePath) + if err != nil { + if err != http.ErrServerClosed { + return fmt.Errorf("failed to run https server: %v", err) + } else { + s.DMSController.log.Warnf("failed to run https server,err :%v", err) + } + } + } else { + if err := s.echo.Start(s.opts.GetAPIServer().GetHTTPAddr()); nil != err { + if err != http.ErrServerClosed { + return fmt.Errorf("failed to run http server: %v", err) + } } } return nil } func NewErrResp(c echo.Context, err error, code apiError.ErrorCode) error { - return c.JSON(http.StatusOK, bV1.GenericResp{Code: int(code), Msg: err.Error()}) + return c.JSON(http.StatusOK, bV1.GenericResp{Code: int(code), Message: err.Error()}) } func NewOkRespWithReply(c echo.Context, reply bV1.GenericResper) error { @@ -82,7 +156,7 @@ func NewOkRespWithReply(c echo.Context, reply bV1.GenericResper) error { } func NewOkResp(c echo.Context) error { - return c.JSON(http.StatusOK, bV1.GenericResp{Code: int(apiError.StatusOK), Msg: "OK"}) + return c.JSON(http.StatusOK, bV1.GenericResp{Code: int(apiError.StatusOK), Message: "OK"}) } func bindAndValidateReq(c echo.Context, i interface{}) error { diff --git a/internal/apiserver/service/sql_workbench_controller.go b/internal/apiserver/service/sql_workbench_controller.go new file mode 100644 index 000000000..750bec533 --- /dev/null +++ b/internal/apiserver/service/sql_workbench_controller.go @@ -0,0 +1,69 @@ +package service + +import ( + "fmt" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + sql_workbench "github.com/actiontech/dms/internal/sql_workbench/service" + + "github.com/actiontech/dms/internal/apiserver/conf" + "github.com/actiontech/dms/internal/dms/service" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "github.com/labstack/echo/v4" +) + +type SqlWorkbenchController struct { + CloudbeaverService *service.CloudbeaverService + SqlWorkbenchService *sql_workbench.SqlWorkbenchService + shutdownCallback func() error +} + +func NewSqlWorkbenchController(logger utilLog.Logger, opts *conf.DMSOptions) (*SqlWorkbenchController, error) { + cloudbeaverService, err := service.NewAndInitCloudbeaverService(logger, opts) + if nil != err { + return nil, fmt.Errorf("failed to init cloudbeaver service: %v", err) + } + sqlWorkbenchService, err := sql_workbench.NewAndInitSqlWorkbenchService(logger, opts) + if nil != err { + return nil, fmt.Errorf("failed to init sql workbench service: %v", err) + } + return &SqlWorkbenchController{ + CloudbeaverService: cloudbeaverService, + SqlWorkbenchService: sqlWorkbenchService, + shutdownCallback: func() error { + return nil + }, + }, nil +} + +func (cc *SqlWorkbenchController) Shutdown() error { + if nil != cc.shutdownCallback { + return cc.shutdownCallback() + } + return nil +} + +// swagger:route GET /v1/dms/configurations/sql_query CloudBeaver GetSQLQueryConfiguration +// +// get sql_query configuration. +// +// responses: +// 200: body:GetSQLQueryConfigurationReply +// default: body:GenericResp +func (cc *SqlWorkbenchController) GetSQLQueryConfiguration(c echo.Context) error { + reply := &dmsV1.GetSQLQueryConfigurationReply{ + Data: struct { + EnableSQLQuery bool `json:"enable_sql_query"` + SQLQueryRootURI string `json:"sql_query_root_uri"` + EnableOdcQuery bool `json:"enable_odc_query"` + OdcQueryRootURI string `json:"odc_query_root_uri"` + }{ + EnableSQLQuery: cc.CloudbeaverService.CloudbeaverUsecase.IsCloudbeaverConfigured(), + SQLQueryRootURI: cc.CloudbeaverService.CloudbeaverUsecase.GetRootUri() + "/", // 确保URL以斜杠结尾,防止DMS开启HTTPS时,Web服务器重定向到HTTP根路径导致访问错误 + EnableOdcQuery: cc.SqlWorkbenchService.IsConfigured(), + OdcQueryRootURI: cc.SqlWorkbenchService.GetRootUri(), + }, + } + return NewOkRespWithReply(c, reply) +} diff --git a/internal/dms/biz/access_token.go b/internal/dms/biz/access_token.go new file mode 100644 index 000000000..fee1c82ad --- /dev/null +++ b/internal/dms/biz/access_token.go @@ -0,0 +1,59 @@ +package biz + +import ( + "fmt" + "net/http" + + jwtPkg "github.com/actiontech/dms/pkg/dms-common/api/jwt" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + + "github.com/labstack/echo/v4" +) + +const AccessTokenLogin = "access_token_login" + +type AuthAccessTokenUsecase struct { + userUsecase *UserUsecase + log *utilLog.Helper +} + +func NewAuthAccessTokenUsecase(log utilLog.Logger, usecase *UserUsecase) *AuthAccessTokenUsecase { + au := &AuthAccessTokenUsecase{ + userUsecase: usecase, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.accesstoken")), + } + return au +} + +func (au *AuthAccessTokenUsecase) CheckLatestAccessToken() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + tokenDetail, err := jwtPkg.GetTokenDetailFromContext(c) + if err != nil { + echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("get token detail failed, err:%v", err)) + return err + } + + // LoginType为空,不需要校验access token + if tokenDetail.LoginType == "" { + return next(c) + } + + if tokenDetail.LoginType != AccessTokenLogin { + return echo.NewHTTPError(http.StatusUnauthorized, "access token login type is error") + } + + accessTokenInfo, err := au.userUsecase.repo.GetAccessTokenByUser(c.Request().Context(), tokenDetail.UID) + + if err != nil { + return err + } + + if accessTokenInfo.Token != tokenDetail.TokenStr { + return echo.NewHTTPError(http.StatusUnauthorized, "access token is not latest") + } + + return next(c) + } + } +} diff --git a/internal/dms/biz/basic.go b/internal/dms/biz/basic.go new file mode 100644 index 000000000..694d95629 --- /dev/null +++ b/internal/dms/biz/basic.go @@ -0,0 +1,90 @@ +package biz + +import ( + "context" + "fmt" + "mime/multipart" + + "github.com/actiontech/dms/internal/dms/conf" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +type BasicConfigRepo interface { + GetBasicConfig(ctx context.Context) (*BasicConfigParams, error) + SaveBasicConfig(ctx context.Context, params *BasicConfigParams) error +} + +type BasicUsecase struct { + basicConfigRepo BasicConfigRepo + log *utilLog.Helper + dmsProxyUsecase *DmsProxyUsecase +} + +func NewBasicInfoUsecase(log utilLog.Logger, dmsProxyUsecase *DmsProxyUsecase, repo BasicConfigRepo) *BasicUsecase { + return &BasicUsecase{ + basicConfigRepo: repo, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.basic")), + dmsProxyUsecase: dmsProxyUsecase, + } +} + +type BasicConfigParams struct { + Base + UID string `json:"uid"` + Title string `json:"title"` + File *multipart.FileHeader `json:"file"` + Logo []byte `json:"logo"` +} + +type ComponentNameWithVersion struct { + Name string + Version string +} +type BasicInfo struct { + LogoUrl string `json:"logo_url"` + Title string `json:"title"` + Components []ComponentNameWithVersion `json:"components"` +} + +const ( + PersonalizationUrl = "/dms/personalization/logo" +) + +func (d *BasicUsecase) GetBasicInfo(ctx context.Context) (*BasicInfo, error) { + targets, err := d.dmsProxyUsecase.ListProxyTargets(ctx) + if err != nil { + return nil, err + } + + basicConfig, err := d.basicConfigRepo.GetBasicConfig(ctx) + if err != nil { + return nil, err + } + + ret := &BasicInfo{ + Components: []ComponentNameWithVersion{ + { + Name: _const.DmsComponentName, + Version: conf.Version, + }, + }, + } + for _, target := range targets { + ret.Components = append(ret.Components, ComponentNameWithVersion{ + Name: target.Name, + Version: target.Version, + }) + } + + if basicConfig.Title != "" { + ret.Title = basicConfig.Title + } + + if len(basicConfig.Logo) > 0 { + ret.LogoUrl = fmt.Sprintf("%s%s", dmsCommonV1.CurrentGroupVersion, PersonalizationUrl) + } + + return ret, nil +} diff --git a/internal/dms/biz/basic_ce.go b/internal/dms/biz/basic_ce.go new file mode 100644 index 000000000..b18f100d4 --- /dev/null +++ b/internal/dms/biz/basic_ce.go @@ -0,0 +1,18 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" +) + +var errNotBasicConfig = errors.New("personalization are enterprise version functions") + +func (d *BasicUsecase) GetStaticLogo(ctx context.Context) (*BasicConfigParams, string, error) { + return nil, "", errNotBasicConfig +} + +func (d *BasicUsecase) Personalization(ctx context.Context, params *BasicConfigParams) error { + return errNotBasicConfig +} diff --git a/internal/dms/biz/business_tag.go b/internal/dms/biz/business_tag.go new file mode 100644 index 000000000..477477bbd --- /dev/null +++ b/internal/dms/biz/business_tag.go @@ -0,0 +1,159 @@ +package biz + +import ( + "context" + "fmt" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" +) + +type BusinessTagRepo interface { + CreateBusinessTag(ctx context.Context, businessTag *BusinessTag) error + UpdateBusinessTag(ctx context.Context, businessTagName, businessTagUID string) error + DeleteBusinessTag(ctx context.Context, businessTagUID string) error + GetBusinessTagByName(ctx context.Context, name string) (*BusinessTag, error) + GetBusinessTagByUID(ctx context.Context, uid string) (*BusinessTag, error) + ListBusinessTags(ctx context.Context, options *ListBusinessTagsOption) ([]*BusinessTag, int64, error) +} + +type BusinessTagUsecase struct { + businessTagRepo BusinessTagRepo + log *utilLog.Helper +} + +func NewBusinessTagUsecase(businessTagRepo BusinessTagRepo, logger utilLog.Logger) *BusinessTagUsecase { + return &BusinessTagUsecase{ + businessTagRepo: businessTagRepo, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.business_tag")), + } +} + +type BusinessTag struct { + UID string + Name string +} + +func (uc *BusinessTagUsecase) newBusinessTag(tagName string) (*BusinessTag, error) { + uid, err := pkgRand.GenStrUid() + if err != nil { + return nil, err + } + if tagName == "" { + return nil, fmt.Errorf("business tag name is empty") + } + return &BusinessTag{ + UID: uid, + Name: tagName, + }, nil +} + +func (uc *BusinessTagUsecase) CreateBusinessTag(ctx context.Context, tagName string) error { + businessTag, err := uc.newBusinessTag(tagName) + if err != nil { + uc.log.Errorf("new business tag failed: %v", err) + return err + } + err = uc.businessTagRepo.CreateBusinessTag(ctx, businessTag) + if err != nil { + uc.log.Errorf("create business tag failed: %v", err) + return err + } + return nil +} + +func (uc *BusinessTagUsecase) UpdateBusinessTag(ctx context.Context, businessTagUID, businessTagName string) error { + if businessTagUID == "" || businessTagName == "" { + return fmt.Errorf("business tag name or uid is empty, please check: businessTagID %v, businessTagName %v", businessTagUID, businessTagName) + } + _, err := uc.businessTagRepo.GetBusinessTagByUID(ctx, businessTagUID) + if err != nil { + uc.log.Errorf("get business tag failed: %v", err) + return err + } + err = uc.businessTagRepo.UpdateBusinessTag(ctx, businessTagUID, businessTagName) + if err != nil { + uc.log.Errorf("update business tag failed: %v", err) + return err + } + return nil +} + +func (uc *BusinessTagUsecase) DeleteBusinessTag(ctx context.Context, businessTagUID string) error { + _, err := uc.businessTagRepo.GetBusinessTagByUID(ctx, businessTagUID) + if err != nil { + uc.log.Errorf("get business tag failed: %v", err) + return err + } + err = uc.businessTagRepo.DeleteBusinessTag(ctx, businessTagUID) + if err != nil { + uc.log.Errorf("delete business tag failed: %v", err) + return err + } + return nil +} + +type ListBusinessTagsOption struct { + Limit int + Offset int + FuzzyKeyword string +} + +func (uc *BusinessTagUsecase) ListBusinessTags(ctx context.Context, options *ListBusinessTagsOption) ([]*BusinessTag, int64, error) { + businessTags, count, err := uc.businessTagRepo.ListBusinessTags(ctx, options) + if err != nil { + uc.log.Errorf("list business tags failed: %v", err) + return nil, 0, err + } + return businessTags, count, nil +} + +func (uc *BusinessTagUsecase) GetBusinessTagByName(ctx context.Context, tagName string) (*BusinessTag, error) { + businessTag, err := uc.businessTagRepo.GetBusinessTagByName(ctx, tagName) + if err != nil { + uc.log.Errorf("get business tag failed: %v", err) + return nil, err + } + return businessTag, nil +} + +func (uc *BusinessTagUsecase) GetBusinessTagByUID(ctx context.Context, uid string) (*BusinessTag, error) { + businessTag, err := uc.businessTagRepo.GetBusinessTagByUID(ctx, uid) + if err != nil { + uc.log.Errorf("get business tag failed: %v", err) + return nil, err + } + return businessTag, nil +} + +// LoadBusinessTagForProjects 根据 UID 和名称补全项目的所属业务标签。 +// 对于每个项目,如果 BusinessTag 的 Name 为空但 UID 不为空,则通过 UID 查找并填充 Name。 +// 如果 BusinessTag 的 Name 不为空但 UID 为空,则通过 Name 查找并填充 UID。 +func (uc *BusinessTagUsecase) LoadBusinessTagForProjects(ctx context.Context, projects []*Project) error { + businessTags, _, err := uc.businessTagRepo.ListBusinessTags(ctx, &ListBusinessTagsOption{Limit: 9999, Offset: 0, FuzzyKeyword: ""}) + if err != nil { + uc.log.Errorf("list business tags failed: %v", err) + return err + } + businessTagUIDMap := make(map[string]*BusinessTag) + businessTagNameMap := make(map[string]*BusinessTag) + for _, businessTag := range businessTags { + businessTagUIDMap[businessTag.UID] = businessTag + businessTagNameMap[businessTag.Name] = businessTag + } + for _, project := range projects { + if project.BusinessTag.Name == "" && project.BusinessTag.UID != "" { + if businessTag, ok := businessTagUIDMap[project.BusinessTag.UID]; ok { + project.BusinessTag.Name = businessTag.Name + continue + } + } + if project.BusinessTag.Name != "" && project.BusinessTag.UID == "" { + if businessTag, ok := businessTagNameMap[project.BusinessTag.Name]; ok { + project.BusinessTag.UID = businessTag.UID + continue + } + } + } + return nil +} diff --git a/internal/dms/biz/cb_operation_log.go b/internal/dms/biz/cb_operation_log.go new file mode 100644 index 000000000..9cb0b039e --- /dev/null +++ b/internal/dms/biz/cb_operation_log.go @@ -0,0 +1,117 @@ +package biz + +import ( + "context" + "time" + + "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/dms/storage/model" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +type CbOperationLogType string + +const ( + CbOperationLogTypeSql CbOperationLogType = "SQL" + + CbExecOpSuccess = "Success" + CbExecOpFailure = "Failure" +) + +// CbOperationLogRepo 定义操作日志的存储接口 +type CbOperationLogRepo interface { + GetCbOperationLogByID(ctx context.Context, uid string) (*CbOperationLog, error) + SaveCbOperationLog(ctx context.Context, log *CbOperationLog) error + UpdateCbOperationLog(ctx context.Context, log *CbOperationLog) error + ListCbOperationLogs(ctx context.Context, opt *ListCbOperationLogOption) ([]*CbOperationLog, int64, error) + CleanCbOperationLogOpTimeBefore(ctx context.Context, t time.Time) (int64, error) + CountOperationLogs(ctx context.Context, opt *ListCbOperationLogOption) (int64, error) +} + +// CbOperationLog 代表操作日志记录 +type CbOperationLog struct { + UID string + OpPersonUID string + OpTime *time.Time + DBServiceUID string + OpType CbOperationLogType + I18nOpDetail i18nPkg.I18nStr + OpSessionID *string + OpHost string + ProjectID string + AuditResults model.AuditResults + IsAuditPass *bool + ExecResult string + ExecTotalSec int64 + ResultSetRowCount int64 + WorkflowID *string + + User *User + DbService *DBService + Project *Project +} + +func (c CbOperationLog) GetOpTime() time.Time { + if c.OpTime != nil { + return *c.OpTime + } + return time.Time{} +} + +func (c CbOperationLog) GetSessionID() string { + if c.OpSessionID != nil { + return *c.OpSessionID + } + return "" +} + +func (c CbOperationLog) GetUserName() string { + if c.User != nil { + return c.User.Name + } + return "" +} + +func (c CbOperationLog) GetProjectName() string { + if c.Project != nil { + return c.Project.Name + } + return "" +} + +func (c CbOperationLog) GetDbServiceName() string { + if c.DbService != nil { + return c.DbService.Name + } + return "" + +} + +// ListCbOperationLogOption 用于查询操作日志的选项 +type ListCbOperationLogOption struct { + PageNumber uint32 + LimitPerPage uint32 + OrderBy string + FilterByOptions constant.FilterOptions +} + +// CbOperationLogUsecase 定义操作日志的业务逻辑 +type CbOperationLogUsecase struct { + opPermissionVerifyUsecase *OpPermissionVerifyUsecase + repo CbOperationLogRepo + dmsProxyTargetRepo ProxyTargetRepo + systemVariableUsecase *SystemVariableUsecase + log *utilLog.Helper +} + +// NewCbOperationLogUsecase 创建一个新的操作日志业务逻辑实例 +func NewCbOperationLogUsecase(logger utilLog.Logger, repo CbOperationLogRepo, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, proxyTargetRepo ProxyTargetRepo, systemVariableUsecase *SystemVariableUsecase) *CbOperationLogUsecase { + return &CbOperationLogUsecase{ + repo: repo, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.cbOperationLog")), + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + dmsProxyTargetRepo: proxyTargetRepo, + systemVariableUsecase: systemVariableUsecase, + } +} diff --git a/internal/dms/biz/cb_operation_log_ce.go b/internal/dms/biz/cb_operation_log_ce.go new file mode 100644 index 000000000..286821e21 --- /dev/null +++ b/internal/dms/biz/cb_operation_log_ce.go @@ -0,0 +1,30 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" +) + +var errNotSupportCbOperationLog = errors.New("cb operation log related functions are enterprise version functions") + +func (cu *CbOperationLogUsecase) GetCbOperationLogByID(ctx context.Context, uid string) (*CbOperationLog, error) { + return nil, errNotSupportCbOperationLog +} + +func (u *CbOperationLogUsecase) SaveCbOperationLog(ctx context.Context, log *CbOperationLog) error { + return errNotSupportCbOperationLog +} + +func (u *CbOperationLogUsecase) UpdateCbOperationLog(ctx context.Context, log *CbOperationLog) error { + return errNotSupportCbOperationLog +} + +func (u *CbOperationLogUsecase) ListCbOperationLog(ctx context.Context, option *ListCbOperationLogOption, currentUid string, filterPersonID string, projectUid string) ([]*CbOperationLog, int64, error) { + return nil, 0, errNotSupportCbOperationLog +} + +func (u *CbOperationLogUsecase) DoClean() { + return +} diff --git a/internal/dms/biz/cloudbeaver.go b/internal/dms/biz/cloudbeaver.go index 0e6818e93..24766f0f7 100644 --- a/internal/dms/biz/cloudbeaver.go +++ b/internal/dms/biz/cloudbeaver.go @@ -8,22 +8,25 @@ import ( "errors" "fmt" "io" + "mime/multipart" "net" "net/http" "path" + "strconv" "strings" "sync" + "time" + "github.com/99designs/gqlgen/graphql" + "github.com/99designs/gqlgen/graphql/executor" "github.com/actiontech/dms/internal/dms/pkg/constant" "github.com/actiontech/dms/internal/pkg/cloudbeaver" "github.com/actiontech/dms/internal/pkg/cloudbeaver/model" "github.com/actiontech/dms/internal/pkg/cloudbeaver/resolver" - + "github.com/actiontech/dms/internal/pkg/locale" "github.com/actiontech/dms/pkg/dms-common/api/jwt" "github.com/actiontech/dms/pkg/dms-common/pkg/aes" - - "github.com/99designs/gqlgen/graphql" - "github.com/99designs/gqlgen/graphql/executor" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" "github.com/labstack/echo/v4" ) @@ -51,49 +54,68 @@ type CloudbeaverUser struct { type CloudbeaverConnection struct { DMSDBServiceID string `json:"dms_db_service_id"` + Purpose string `json:"purpose"` + DMSUserId string `json:"dms_user_id"` DMSDBServiceFingerprint string `json:"dms_db_service_fingerprint"` CloudbeaverConnectionID string `json:"cloudbeaver_connection_id"` } +func (c CloudbeaverConnection) PrimaryKey() string { + return getDBPrimaryKey(c.DMSDBServiceID, c.Purpose, c.DMSUserId) +} + +type SQLResultMasker interface { + MaskSQLResults(ctx context.Context, result *model.SQLExecuteInfo, dbServiceUID, schemaName string) error +} + type CloudbeaverRepo interface { GetCloudbeaverUserByID(ctx context.Context, cloudbeaverUserId string) (*CloudbeaverUser, bool, error) UpdateCloudbeaverUserCache(ctx context.Context, u *CloudbeaverUser) error - GetCloudbeaverConnectionByDMSDBServiceIds(ctx context.Context, dmsDBServiceIds []string) ([]*CloudbeaverConnection, error) + GetDbServiceIdByConnectionId(ctx context.Context, connectionId string) (string, error) + GetAllCloudbeaverConnections(ctx context.Context) ([]*CloudbeaverConnection, error) + GetCloudbeaverConnectionsByUserIdAndDBServiceIds(ctx context.Context, userId string, dmsDBServiceIds []string) ([]*CloudbeaverConnection, error) + GetCloudbeaverConnectionsByUserId(ctx context.Context, userId string) ([]*CloudbeaverConnection, error) UpdateCloudbeaverConnectionCache(ctx context.Context, u *CloudbeaverConnection) error + DeleteCloudbeaverConnectionCache(ctx context.Context, dbServiceId, userId, purpose string) error + DeleteAllCloudbeaverCachesByUserId(ctx context.Context, userId string) error } type CloudbeaverUsecase struct { graphQl cloudbeaver.GraphQLImpl - cloudbeaverCfg CloudbeaverCfg + cloudbeaverCfg *CloudbeaverCfg log *utilLog.Helper userUsecase *UserUsecase dbServiceUsecase *DBServiceUsecase opPermissionVerifyUsecase *OpPermissionVerifyUsecase + dmsConfigUseCase *DMSConfigUseCase + sqlResultMasker SQLResultMasker + cbOperationLogUsecase *CbOperationLogUsecase + projectUsecase *ProjectUsecase + maskingTaskRepo MaskingTaskRepo repo CloudbeaverRepo proxyTargetRepo ProxyTargetRepo + maintenanceTimeUsecase *MaintenanceTimeUsecase } -func NewCloudbeaverUsecase(log utilLog.Logger, cfg CloudbeaverCfg, userUsecase *UserUsecase, dbServiceUsecase *DBServiceUsecase, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, cloudbeaverRepo CloudbeaverRepo, proxyTargetRepo ProxyTargetRepo) (cu *CloudbeaverUsecase) { +func NewCloudbeaverUsecase(log utilLog.Logger, cfg *CloudbeaverCfg, userUsecase *UserUsecase, dbServiceUsecase *DBServiceUsecase, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, dmsConfigUseCase *DMSConfigUseCase, sqlResultMasker SQLResultMasker, cloudbeaverRepo CloudbeaverRepo, proxyTargetRepo ProxyTargetRepo, cbOperationUseCase *CbOperationLogUsecase, projectUsecase *ProjectUsecase, maskingTaskRepo MaskingTaskRepo, maintenanceTimeUsecase *MaintenanceTimeUsecase) (cu *CloudbeaverUsecase) { cu = &CloudbeaverUsecase{ repo: cloudbeaverRepo, proxyTargetRepo: proxyTargetRepo, userUsecase: userUsecase, dbServiceUsecase: dbServiceUsecase, opPermissionVerifyUsecase: opPermissionVerifyUsecase, + dmsConfigUseCase: dmsConfigUseCase, + sqlResultMasker: sqlResultMasker, + cbOperationLogUsecase: cbOperationUseCase, + projectUsecase: projectUsecase, + maskingTaskRepo: maskingTaskRepo, cloudbeaverCfg: cfg, log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.cloudbeaver")), + maintenanceTimeUsecase: maintenanceTimeUsecase, } - if cu.IsCloudbeaverConfigured() { - graphQl, err := cloudbeaver.NewGraphQL(cu.getGraphQLServerURI()) - if err != nil { - cu.log.Errorf("NewGraphQL err: %v", err) - - return - } - - cu.graphQl = graphQl - } + // 启动缓存清理协程 + go cu.startCacheCleanupRoutine() return } @@ -103,9 +125,28 @@ func (cu *CloudbeaverUsecase) GetRootUri() string { } func (cu *CloudbeaverUsecase) IsCloudbeaverConfigured() bool { + if cu.cloudbeaverCfg == nil { + return false + } + return cu.cloudbeaverCfg.Host != "" && cu.cloudbeaverCfg.Port != "" && cu.cloudbeaverCfg.AdminUser != "" && cu.cloudbeaverCfg.AdminPassword != "" } +func (cu *CloudbeaverUsecase) initialGraphQL() error { + if cu.IsCloudbeaverConfigured() && cu.graphQl == nil { + graphQl, graphQlErr := cloudbeaver.NewGraphQL(cu.getGraphQLServerURI()) + if graphQlErr != nil { + cu.log.Errorf("NewGraphQL err: %v", graphQlErr) + + return fmt.Errorf("initial graphql client err: %v", graphQlErr) + } + + cu.graphQl = graphQl + } + + return nil +} + func (cu *CloudbeaverUsecase) getGraphQLServerURI() string { protocol := "http" if cu.cloudbeaverCfg.EnableHttps { @@ -115,9 +156,16 @@ func (cu *CloudbeaverUsecase) getGraphQLServerURI() string { return fmt.Sprintf("%v://%v:%v%v%v", protocol, cu.cloudbeaverCfg.Host, cu.cloudbeaverCfg.Port, CbRootUri, CbGqlApi) } +const ( + dmsUserIdKey = "dmsToken" + CBErrorCode = "sessionExpired" +) + func (cu *CloudbeaverUsecase) Login() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { + + // 从Cookie中获取DMS token var dmsToken string for _, cookie := range c.Cookies() { if cookie.Name == constant.DMSToken { @@ -126,21 +174,55 @@ func (cu *CloudbeaverUsecase) Login() echo.MiddlewareFunc { } } + // 普通非WebSocket的GET请求跳过token校验和cookie设置逻辑 + if c.Request().Method == http.MethodGet && !c.IsWebSocket() { + cu.log.Debugf("Cloudbeaver login middleware: Skipping GET request to %s", c.Request().RequestURI) + return next(c) + } + if dmsToken == "" { - return c.Redirect(http.StatusFound, "/login?target=/sql_query") + gqlResp := GraphQLResponse{ + Data: nil, + Errors: []GraphQLError{{ + Extensions: map[string]interface{}{ + "webErrorCode": CBErrorCode, + }, + Message: "dms user token is empty", + }}, + } + + cu.log.Errorf("dmsToken is empty") + return c.JSON(http.StatusOK, gqlResp) } dmsUserId, err := jwt.ParseUidFromJwtTokenStr(dmsToken) if err != nil { + gqlResp := GraphQLResponse{ + Data: nil, + Errors: []GraphQLError{{ + Extensions: map[string]interface{}{ + "webErrorCode": CBErrorCode, + }, + Message: "dms user token expired", + }}, + } + cu.log.Errorf("GetUserUidStrFromContext err: %v", err) - return errors.New("get user name from token failed") + return c.JSON(http.StatusOK, gqlResp) + } + // set dmsUserId to context for save ob operation log + c.Set(dmsUserIdKey, dmsUserId) + if err = cu.initialGraphQL(); err != nil { + return err } + // 当前用户已经用同一个token登录过CB cloudbeaverSessionId := cu.getCloudbeaverSession(dmsUserId, dmsToken) if cloudbeaverSessionId != "" { cookie := &http.Cookie{Name: CloudbeaverCookieName, Value: cloudbeaverSessionId} - c.Request().AddCookie(cookie) + c.Request().Header.Set("Cookie", fmt.Sprintf("%s=%s", CloudbeaverCookieName, cookie.Value)) + // 根据cookie 获取登录用户 cloudbeaverActiveUser, err := cu.getActiveUserQuery([]*http.Cookie{cookie}) if err != nil { cu.log.Errorf("getActiveUserQuery err: %v", err) @@ -172,16 +254,17 @@ func (cu *CloudbeaverUsecase) Login() echo.MiddlewareFunc { return err } - cookies, err := cu.loginCloudbeaverServer(cloudbeaverUserId, user.Password) + // 获取认证 cookies(已包含缓存逻辑) + cookies, err := cu.getAuthCookies(cloudbeaverUserId, user.Password) if err != nil { - cu.log.Errorf("login to cloudbeaver failed: %v", err) + cu.log.Errorf("CloudBeaver authentication failed: %v", err) return err } for _, cookie := range cookies { if cookie.Name == CloudbeaverCookieName { cu.setCloudbeaverSession(user.UID, dmsToken, cookie.Value) - c.Request().AddCookie(&http.Cookie{Name: CloudbeaverCookieName, Value: cookie.Value}) + SetOrReplaceCBCookieByDMSToken(c, cookie) } } @@ -190,32 +273,51 @@ func (cu *CloudbeaverUsecase) Login() echo.MiddlewareFunc { } } -type responseProcessWriter struct { - tmp *bytes.Buffer - headerCode int - http.ResponseWriter -} - -func (w *responseProcessWriter) WriteHeader(code int) { - w.headerCode = code -} - -func (w *responseProcessWriter) Write(b []byte) (int, error) { - return w.tmp.Write(b) -} +// SetOrReplaceCBCookieByDMSToken sets or replaces a specific cookie in the request header of an echo.Context. +// +// Example: +// +// cookie = token=abc123 +// +// Replace existing cookie: +// before: "sessionid=xyz789; token=oldval; lang=zh" +// after: "sessionid=xyz789; token=abc123; lang=zh" +// +// Set new cookie (when "token" does not exist): +// before: "sessionid=xyz789; lang=zh" +// after: "sessionid=xyz789; lang=zh; token=abc123" +func SetOrReplaceCBCookieByDMSToken(c echo.Context, cookie *http.Cookie) { + req := c.Request() + + // Get the original "Cookie" header, e.g., "a=1; b=2" + original := req.Header.Get("Cookie") + pairs := []string{} + found := false + + // Split the cookie string into individual name-value pairs + for _, segment := range strings.Split(original, ";") { + pair := strings.SplitN(strings.TrimSpace(segment), "=", 2) + if len(pair) != 2 { + continue // Skip malformed cookie segments + } -func (w *responseProcessWriter) Flush() { - if wf, ok := w.ResponseWriter.(http.Flusher); ok { - wf.Flush() + if pair[0] == cookie.Name { + // Replace the value if the target cookie is found + pairs = append(pairs, fmt.Sprintf("%s=%s", cookie.Name, cookie.Value)) + found = true + } else { + // Preserve other cookies + pairs = append(pairs, fmt.Sprintf("%s=%s", pair[0], pair[1])) + } } -} -func (w *responseProcessWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if wh, ok := w.ResponseWriter.(http.Hijacker); ok { - return wh.Hijack() + // If the target cookie was not found, append it as a new entry + if !found { + pairs = append(pairs, fmt.Sprintf("%s=%s", cookie.Name, cookie.Value)) } - return nil, nil, errors.New("responseProcessWriter assert Hijacker failed") + // Set the updated "Cookie" header back to the request + req.Header.Set("Cookie", strings.Join(pairs, "; ")) } func (cu *CloudbeaverUsecase) getSQLEUrl(ctx context.Context) (string, error) { @@ -227,24 +329,62 @@ func (cu *CloudbeaverUsecase) getSQLEUrl(ctx context.Context) (string, error) { return target.URL.String(), nil } +type TaskInfo struct { + Data struct { + TaskInfo *model.AsyncTaskInfo `json:"taskInfo"` + } `json:"data"` +} + +type taskMaskingContext struct { + Enabled bool + DBServiceUID string + SchemaName string +} + +var ( + taskIDAssocUid sync.Map + taskIdAssocMasking sync.Map +) + +func (cu *CloudbeaverUsecase) buildTaskIdAssocDataMasking(raw []byte, maskingCtx taskMaskingContext) error { + var taskInfo TaskInfo + + if err := UnmarshalGraphQLResponse(raw, &taskInfo); err != nil { + cu.log.Errorf("extract task id err: %v", err) + + return fmt.Errorf("extract task id err: %v", err) + } + + taskIdAssocMasking.Store(taskInfo.Data.TaskInfo.ID, maskingCtx) + + return nil +} + +// TODO 这个函数太大了,需要找时间拆分一下 +// GraphQLDistributor 返回一个Echo中间件函数,用于分发和处理CloudBeaver的GraphQL请求 func (cu *CloudbeaverUsecase) GraphQLDistributor() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { - if c.Request().RequestURI != path.Join(CbRootUri, CbGqlApi) { + // 检查请求URI是否匹配CloudBeaver的GraphQL API路径 + gqlPath := path.Join(CbRootUri, CbGqlApi) + + if c.Request().RequestURI != gqlPath { return next(c) } - // copy request body - var reqBody = make([]byte, 0) - if c.Request().Body != nil { // Read - reqBody, err = io.ReadAll(c.Request().Body) + // 复制请求体内容 + reqBody := make([]byte, 0) + if c.Request().Body != nil { // 读取请求体 + reqBody, err = io.ReadAll(c.Request().Body) if err != nil { cu.log.Errorf("read request body err: %v", err) return err } } - c.Request().Body = io.NopCloser(bytes.NewBuffer(reqBody)) // Reset + // 重置请求体以便后续处理 + c.Request().Body = io.NopCloser(bytes.NewBuffer(reqBody)) + // 解析GraphQL请求参数 var params *graphql.RawParams err = json.Unmarshal(reqBody, ¶ms) if err != nil { @@ -252,11 +392,12 @@ func (cu *CloudbeaverUsecase) GraphQLDistributor() echo.MiddlewareFunc { return err } + // 根据操作名称查找对应的处理器 cloudbeaverHandle, ok := cloudbeaver.GraphQLHandlerRouters[params.OperationName] if !ok { return next(c) } - + // 如果该操作被禁用,返回错误响应 if cloudbeaverHandle.Disable { message := "this feature is prohibited" cu.log.Errorf("%v:%v", message, params.OperationName) @@ -265,6 +406,7 @@ func (cu *CloudbeaverUsecase) GraphQLDistributor() echo.MiddlewareFunc { }) } + // 执行预处理函数(如果存在) if cloudbeaverHandle.Preprocessing != nil { if err = cloudbeaverHandle.Preprocessing(c, params); err != nil { cu.log.Error(err) @@ -272,69 +414,394 @@ func (cu *CloudbeaverUsecase) GraphQLDistributor() echo.MiddlewareFunc { } } + // 只有当使用本地处理器或需要特殊处理时才创建smartResponseWriter + var srw *ResponseInterceptor + var cloudbeaverResBuf *bytes.Buffer + var needSmartWriter bool = cloudbeaverHandle.UseLocalHandler || + params.OperationName == "navNodeChildren" + + if needSmartWriter { + srw = newSmartResponseWriter(c) + cloudbeaverResBuf = srw.Buffer + c.Response().Writer = srw + defer func() { + if !needSmartWriter || srw == nil { + return + } + cu.handleNavNodeChildrenOperation(params, c, cloudbeaverResBuf) + respBytesBuf := cloudbeaverResBuf.Bytes() + + length := c.Response().Header().Get("content-length") + actualLength := strconv.Itoa(len(respBytesBuf)) + if length != actualLength { + cu.log.Warnf("Response content-length mismatch, header: %s, actual: %s", length, actualLength) + // 在WriteHeader之前设置正确的content-length + c.Response().Header().Set("content-length", actualLength) + } + + if srw.status != 0 { + srw.original.WriteHeader(srw.status) + } + _, writeErr := srw.original.Write(respBytesBuf) + if writeErr != nil { + c.Logger().Error("Failed to write original response:", writeErr) + } + }() + } + + // 使用本地处理方法 if cloudbeaverHandle.UseLocalHandler { + ctx := graphql.StartOperationTrace(c.Request().Context()) + + var dbService *DBService + var maskingSchemaName string + if params.OperationName == "asyncReadDataFromContainer" { + dbService, err = cu.getDbService(c.Request().Context(), params) + if err != nil { + cu.log.Error(err) + return err + } + + if err = next(c); err != nil { + return err + } + + isMaskingEnabled, _ := cu.maskingTaskRepo.CheckMaskingTaskExist(c.Request().Context(), dbService.UID) + // 构建任务ID与数据脱敏的关联 + return cu.buildTaskIdAssocDataMasking(cloudbeaverResBuf.Bytes(), taskMaskingContext{ + Enabled: isMaskingEnabled, + DBServiceUID: dbService.UID, + }) + } + + // 处理异步SQL执行查询请求 + if params.OperationName == "asyncSqlExecuteQuery" { + dbService, err = cu.getDbService(c.Request().Context(), params) + if err != nil { + cu.log.Error(err) + return err + } + + // 如果未启用SQL审计 + if !cu.isEnableSQLAudit(dbService) { + + if err = next(c); err != nil { + return err + } + + // 保存未启用SQL审计的日志 + err := cu.SaveCbLogSqlAuditNotEnable(c, dbService, params, cloudbeaverResBuf) + if err != nil { + cu.log.Error(err) + } + + isMaskingEnabled, _ := cu.maskingTaskRepo.CheckMaskingTaskExist(c.Request().Context(), dbService.UID) + maskCtx := taskMaskingContext{ + Enabled: isMaskingEnabled, + DBServiceUID: dbService.UID, + } + if ep, epErr := cu.getWorkflowExecParams(c, params); epErr == nil { + maskCtx.SchemaName = ep.instanceSchema + } + + // 构建任务ID与数据脱敏的关联 + return cu.buildTaskIdAssocDataMasking(cloudbeaverResBuf.Bytes(), maskCtx) + } + + // 获取SQLE服务地址 + sqleUrl, err := cu.getSQLEUrl(c.Request().Context()) + if err != nil { + return err + } + + execParams, err := cu.getWorkflowExecParams(c, params) + if err != nil { + return err + } + maskingSchemaName = execParams.instanceSchema + // 构建直接审计请求参数 + directAuditReq := cloudbeaver.DirectAuditParams{ + AuditSQLReq: cloudbeaver.AuditSQLReq{ + InstanceType: dbService.DBType, + ProjectId: dbService.ProjectUID, + RuleTemplateName: dbService.SQLEConfig.SQLQueryConfig.RuleTemplateName, + InstanceName: dbService.Name, + SchemaName: execParams.instanceSchema, + }, + SQLEAddr: fmt.Sprintf("%s/v2/sql_audit", sqleUrl), + AllowQueryWhenLessThanAuditLevel: dbService.GetAllowQueryWhenLessThanAuditLevel(), + } + + // 将SQLE直接审计参数传递到上下文中 + ctx = context.WithValue(ctx, cloudbeaver.SQLEDirectAudit, directAuditReq) + } + + // 处理批量更新结果请求 + if params.OperationName == "updateResultsDataBatch" { + + if err = next(c); err != nil { + return err + } + + // 保存UI操作日志 + if err := cu.SaveUiOp(c, cloudbeaverResBuf, params); err != nil { + cu.log.Errorf("save ui op err: %v", err) + return nil + } + + return nil + } + + // 处理异步批量更新结果请求 + if params.OperationName == "asyncUpdateResultsDataBatch" { + dbService, err := cu.getDbService(c.Request().Context(), params) + if err != nil { + cu.log.Error(err) + return err + } + + if err = next(c); err != nil { + return err + } + + isMaskingEnabled, _ := cu.maskingTaskRepo.CheckMaskingTaskExist(c.Request().Context(), dbService.UID) + // 构建任务ID与数据脱敏的关联 + return cu.buildTaskIdAssocDataMasking(cloudbeaverResBuf.Bytes(), taskMaskingContext{ + Enabled: isMaskingEnabled, + DBServiceUID: dbService.UID, + }) + } + + // 处理获取异步任务信息请求 + if params.OperationName == "getAsyncTaskInfo" { + if err = next(c); err != nil { + return err + } + + // 从任务ID关联中获取用户ID + cbUid, exist := taskIDAssocUid.Load(params.Variables["taskId"]) + if !exist { + return nil + } + cbUidStr, ok := cbUid.(string) + if !ok { + return nil + } + + // 获取操作日志 + operationLog, err := cu.cbOperationLogUsecase.GetCbOperationLogByID(ctx, cbUidStr) + if err != nil { + cu.log.Errorf("get cb operation log by id %s failed: %v", cbUidStr, err) + return nil + } + + var taskInfo TaskInfo + if err := UnmarshalGraphQLResponse(cloudbeaverResBuf.Bytes(), &taskInfo); err != nil { + cu.log.Errorf("extract task id err: %v", err) + return nil + } + task := taskInfo.Data.TaskInfo + if task.Running { + return nil + } + if task.Error != nil { + operationLog.ExecResult = *task.Error.Message + } + if task.TaskResult != nil { + operationLog.ExecResult = fmt.Sprintf("%s", task.TaskResult) + } + + // 更新操作日志 + err = cu.cbOperationLogUsecase.UpdateCbOperationLog(ctx, operationLog) + if err != nil { + cu.log.Error(err) + return nil + } + return nil + } + + var maskingCtx taskMaskingContext + // 处理获取SQL执行任务结果请求 + if params.OperationName == "getSqlExecuteTaskResults" { + // 检查是否需要数据脱敏 + taskIdAssocMaskingVal, exist := taskIdAssocMasking.LoadAndDelete(params.Variables["taskId"]) + if !exist { + msg := fmt.Sprintf("task id %v assoc masking val does not exist", params.Variables["taskId"]) + return c.JSON(http.StatusOK, model.ServerError{Message: &msg}) + } + + var ctxOk bool + maskingCtx, ctxOk = taskIdAssocMaskingVal.(taskMaskingContext) + if !ctxOk { + msg := fmt.Sprintf("task id %v assoc masking context type assertion failed", params.Variables["taskId"]) + return c.JSON(http.StatusOK, model.ServerError{Message: &msg}) + } + } + + // 设置GraphQL请求的读取时间 params.ReadTime = graphql.TraceTiming{ Start: graphql.Now(), End: graphql.Now(), } - sqleUrl, sqleErr := cu.getSQLEUrl(c.Request().Context()) - if sqleErr != nil { - return sqleErr - } - - // pass sqle proxy address by context - ctx := graphql.StartOperationTrace(context.WithValue(c.Request().Context(), cloudbeaver.SQLEProxyAddrName, fmt.Sprintf("%s/v2/sql_audit", sqleUrl))) + // 克隆请求头 params.Headers = c.Request().Header.Clone() var cloudbeaverNext cloudbeaver.Next - var resWrite *responseProcessWriter + var resp cloudbeaver.AuditResults + // 如果不需要修改远程响应 if !cloudbeaverHandle.NeedModifyRemoteRes { cloudbeaverNext = func(c echo.Context) ([]byte, error) { - return nil, next(c) + resp, ok = c.Get(cloudbeaver.AuditResultKey).(cloudbeaver.AuditResults) + isExecuteAnyway := cu.isExecuteAnyway(params) // 是否为“仍要执行”触发 + if ok && !resp.IsSuccess && !isExecuteAnyway { + err = cu.SaveCbOpLog(c, dbService, params, resp.Results, resp.IsSuccess, nil) + if err != nil { + cu.log.Errorf("save cb operation log err: %v", err) + } + + return nil, c.JSON(http.StatusOK, convertToResp(ctx, resp)) + } + + // [运维时间管控检查] 在审核通过后、工单判断前检查运维时间管控 + if blocked, err := cu.checkMaintenanceTime(c, resp.Results, dbService); blocked || err != nil { + return nil, err + } + + // 判断是否需要通过工单执行(非 DQL 语句) + if cu.shouldExecuteByWorkflow(dbService, resp.Results) { + return cu.executeNonDQLByWorkflow(ctx, c, dbService, params, resp) + } + + if err = next(c); err != nil { + return nil, err + } + + if ok && resp.IsSuccess { + var taskInfo TaskInfo + err = UnmarshalGraphQLResponse(cloudbeaverResBuf.Bytes(), &taskInfo) + if err != nil { + cu.log.Errorf("extract task id err: %v", err) + } else { + err = cu.SaveCbOpLog(c, dbService, params, resp.Results, resp.IsSuccess, &taskInfo.Data.TaskInfo.ID) + if err != nil { + cu.log.Errorf("save cb operation log err: %v", err) + } + } + } + + if params.OperationName == "getSqlExecuteTaskResults" { + err = cu.UpdateCbOpResult(c, cloudbeaverResBuf, params, ctx) + if err != nil { + cu.log.Errorf("update cb operation result err: %v", err) + } + } + + if params.OperationName == "asyncSqlExecuteQuery" { + isMaskingEnabled, _ := cu.maskingTaskRepo.CheckMaskingTaskExist(c.Request().Context(), dbService.UID) + if err := cu.buildTaskIdAssocDataMasking(cloudbeaverResBuf.Bytes(), taskMaskingContext{ + Enabled: isMaskingEnabled, + DBServiceUID: dbService.UID, + SchemaName: maskingSchemaName, + }); err != nil { + return nil, err + } + } + + return nil, nil } - } else { + } else { // 需要修改远程响应 cloudbeaverNext = func(c echo.Context) ([]byte, error) { - resWrite = &responseProcessWriter{tmp: &bytes.Buffer{}, ResponseWriter: c.Response().Writer} - c.Response().Writer = resWrite + resp, ok = c.Get(cloudbeaver.AuditResultKey).(cloudbeaver.AuditResults) + if ok && !resp.IsSuccess { + err = cu.SaveCbOpLog(c, dbService, params, resp.Results, resp.IsSuccess, nil) + if err != nil { + cu.log.Errorf("save cb operation log err: %v", err) + } + + return nil, c.JSON(http.StatusOK, convertToResp(ctx, resp)) + } if err = next(c); err != nil { return nil, err } - return resWrite.tmp.Bytes(), nil + if ok && resp.IsSuccess { + var taskInfo TaskInfo + err = UnmarshalGraphQLResponse(cloudbeaverResBuf.Bytes(), &taskInfo) + if err != nil { + cu.log.Errorf("extract task id err: %v", err) + } else { + err = cu.SaveCbOpLog(c, dbService, params, resp.Results, resp.IsSuccess, &taskInfo.Data.TaskInfo.ID) + if err != nil { + cu.log.Errorf("save cb operation log err: %v", err) + } + } + } + // 处理SQL执行结果 + if params.OperationName == "getSqlExecuteTaskResults" { + err = cu.UpdateCbOpResult(c, cloudbeaverResBuf, params, ctx) + if err != nil { + cu.log.Errorf("update cb operation result err: %v", err) + } + } + + return cloudbeaverResBuf.Bytes(), nil + } + } + + maskingHandler := func(ctx context.Context, result *model.SQLExecuteInfo) error { + if cu.sqlResultMasker == nil { + return nil } + return cu.sqlResultMasker.MaskSQLResults(ctx, result, maskingCtx.DBServiceUID, maskingCtx.SchemaName) } + // 创建GraphQL可执行schema g := resolver.NewExecutableSchema(resolver.Config{ - Resolvers: &cloudbeaver.ResolverImpl{ - Ctx: c, - Next: cloudbeaverNext, + Resolvers: cloudbeaver.NewResolverImpl(c, cloudbeaverNext, maskingHandler, maskingCtx.Enabled), + Directives: resolver.DirectiveRoot{ + Since: func(ctx context.Context, obj any, next graphql.Resolver, version string) (res any, err error) { + // @since directive implementation + // This directive is used to mark fields that are available since a specific version + // For CloudBeaver integration, we'll always allow access to these fields + // as they are part of the current schema + return next(ctx) + }, }, }) + // 创建GraphQL执行器 exec := executor.New(g) + // 创建操作上下文 rc, err := exec.CreateOperationContext(ctx, params) if err != nil { return err } + // 分发操作 responses, ctx := exec.DispatchOperation(ctx, rc) + // 获取响应 res := responses(ctx) if res.Errors.Error() != "" { + cu.log.Errorf("GraphQL error: %v", res.Errors) return res.Errors } if !cloudbeaverHandle.NeedModifyRemoteRes { return nil } else { - header := resWrite.ResponseWriter.Header() + // 设置响应头 b, err := json.Marshal(res) if err != nil { return err } + header := srw.original.Header() + // 重写响应内容 header.Set("Content-Length", fmt.Sprintf("%d", len(b))) - _, err = resWrite.ResponseWriter.Write(b) + cloudbeaverResBuf.Reset() + // 写入新内容 + cloudbeaverResBuf.Write(b) return err } } @@ -343,103 +810,436 @@ func (cu *CloudbeaverUsecase) GraphQLDistributor() echo.MiddlewareFunc { } } -type ActiveUserQueryRes struct { - User interface{} `json:"user"` -} - -func (cu *CloudbeaverUsecase) getActiveUserQuery(cookies []*http.Cookie) (*ActiveUserQueryRes, error) { - client := cloudbeaver.NewGraphQlClient(cu.getGraphQLServerURI(), cloudbeaver.WithCookie(cookies)) - req := cloudbeaver.NewRequest(cu.graphQl.GetActiveUserQuery(), map[string]interface{}{}) +func convertToResp(ctx context.Context, resp cloudbeaver.AuditResults) interface{} { + var messages []string + var executionFailedMessage []string + langTag := locale.Bundle.GetLangTagFromCtx(ctx) + for _, sqlResult := range resp.Results { + for _, audit := range sqlResult.AuditResult { + msg := audit.GetAuditMsgByLangTag(langTag) + if audit.ExecutionFailed { + executionFailedMessage = append(executionFailedMessage, msg) + } else { + messages = append(messages, msg) + } + } + } - res := &ActiveUserQueryRes{} - if err := client.Run(context.TODO(), req, res); err != nil { - return nil, err + messageStr := "审核未通过:" + strings.Join(messages, ";") + executionFailedMessageStr := strings.Join(executionFailedMessage, ";") + name := "SQL Audit Failed" + + return struct { + Data struct { + TaskInfo model.AsyncTaskInfo `json:"taskInfo"` + } `json:"data"` + }{ + struct { + TaskInfo model.AsyncTaskInfo `json:"taskInfo"` + }{ + TaskInfo: model.AsyncTaskInfo{ + Name: &name, + Running: false, + Status: &resp.SQL, + Error: &model.ServerError{ + Message: &messageStr, + ExecutionFailedMessage: &executionFailedMessageStr, + StackTrace: &messageStr, + }, + }, + }, } - return res, nil } -type cloudbeaverSession struct { - dmsToken string - cloudbeaverSessionId string +func newResp(ctx context.Context, name, errCode, msg string) interface{} { + return struct { + Data struct { + TaskInfo model.AsyncTaskInfo `json:"taskInfo"` + } `json:"data"` + }{ + struct { + TaskInfo model.AsyncTaskInfo `json:"taskInfo"` + }{ + TaskInfo: model.AsyncTaskInfo{ + Name: &name, + Running: false, + Error: &model.ServerError{ + Message: &msg, + ErrorCode: &errCode, + StackTrace: &msg, + }, + }, + }, + } } -var ( - dmsUserIdCloudbeaverLoginMap = make(map[string]cloudbeaverSession) - tokenMapMutex = &sync.Mutex{} -) - -func (cu *CloudbeaverUsecase) getCloudbeaverSession(dmsUserId, dmsToken string) string { - tokenMapMutex.Lock() - defer tokenMapMutex.Unlock() +// ResponseInterceptor 拦截HTTP响应,允许在响应发送到客户端之前进行修改或日志记录 +type ResponseInterceptor struct { + echo.Response + Buffer *bytes.Buffer + original http.ResponseWriter + status int + hijacked bool // 添加劫持状态标记 +} - if item, ok := dmsUserIdCloudbeaverLoginMap[dmsUserId]; ok { - if dmsToken == item.dmsToken { - return item.cloudbeaverSessionId - } +func newSmartResponseWriter(c echo.Context) *ResponseInterceptor { + buf := new(bytes.Buffer) + return &ResponseInterceptor{ + Response: *c.Response(), + Buffer: buf, + original: c.Response().Writer, + hijacked: false, } +} - return "" +// 实现Hijacker接口 +func (w *ResponseInterceptor) Hijack() (net.Conn, *bufio.ReadWriter, error) { + w.hijacked = true + if hijacker, ok := w.original.(http.Hijacker); ok { + return hijacker.Hijack() + } + return nil, nil, fmt.Errorf("underlying ResponseWriter does not support Hijack") } -func (cu *CloudbeaverUsecase) setCloudbeaverSession(dmsUserId, dmsToken, cloudbeaverSessionId string) { - tokenMapMutex.Lock() - defer tokenMapMutex.Unlock() +func (w *ResponseInterceptor) Write(b []byte) (int, error) { + // 检查连接是否已被劫持 + if w.hijacked { + return len(b), nil + } - dmsUserIdCloudbeaverLoginMap[dmsUserId] = cloudbeaverSession{ - dmsToken: dmsToken, - cloudbeaverSessionId: cloudbeaverSessionId, + // 如果未设置状态码,则补默认值 + if w.status == 0 { + w.WriteHeader(http.StatusOK) } + // 写入 buffer,不立即写给客户端 + return w.Buffer.Write(b) } -type UserList struct { - ListUsers []struct { - UserID string `json:"userID"` - } `json:"listUsers"` +func (w *ResponseInterceptor) WriteHeader(code int) { + // 检查连接是否已被劫持 + if w.hijacked { + return + } + w.status = code } -func (cu *CloudbeaverUsecase) createUserIfNotExist(ctx context.Context, cloudbeaverUserId string, dmsUser *User) error { - cloudbeaverUser, exist, err := cu.repo.GetCloudbeaverUserByID(ctx, cloudbeaverUserId) - if err != nil { - return err +func (cu *CloudbeaverUsecase) handleNavNodeChildrenOperation(params *graphql.RawParams, c echo.Context, responseBuf *bytes.Buffer) { + if params.OperationName != "navNodeChildren" { + return } - fingerprint := cu.userUsecase.GetUserFingerprint(dmsUser) - if exist && cloudbeaverUser.DMSFingerprint == fingerprint { - return nil + parentPath, ok := params.Variables["parentPath"].(string) + if !ok || parentPath != "resource://g_GlobalConfiguration" { + return } - reservedCloudbeaverUserId := map[string]struct{}{"admin": {}, "user": {}} - if _, ok := reservedCloudbeaverUserId[cloudbeaverUserId]; ok { - return fmt.Errorf("this username cannot be used") + currentUserUid := c.Get(dmsUserIdKey).(string) + var navNodeChildrenResponse cloudbeaver.NavNodeChildrenResponse + if err := UnmarshalGraphQLResponseNavNodeChildren(responseBuf.Bytes(), &navNodeChildrenResponse); err != nil { + cu.log.Errorf("Cloudbeaver extract navNodeChildren response err: %v", err) + return } - // 使用管理员身份登录 - graphQLClient, err := cu.getGraphQLClientWithRootUser() + cu.log.Debugf("user %s get connections navNodeChildren: %v", currentUserUid, navNodeChildrenResponse.Data.NavNodeChildren) + connections, err := cu.repo.GetCloudbeaverConnectionsByUserId(c.Request().Context(), currentUserUid) if err != nil { - return err + cu.log.Errorf("get cloudbeaver connections by user id %s failed: %v", currentUserUid, err) + return } - checkExistReq := cloudbeaver.NewRequest(cu.graphQl.IsUserExistQuery(), map[string]interface{}{ - "userId": cloudbeaverUserId, - }) - - cloudbeaverUserList := UserList{} - err = graphQLClient.Run(ctx, checkExistReq, &cloudbeaverUserList) - if err != nil { - return fmt.Errorf("check cloudbeaver user exist failed: %v", err) - } + if len(connections) != len(navNodeChildrenResponse.Data.NavNodeChildren) && + len(navNodeChildrenResponse.Data.NavNodeChildren) > 0 { + // 根据connections的值来过滤navNodeChildren,删除多余的信息 + originalCount := len(navNodeChildrenResponse.Data.NavNodeChildren) + filteredNavNodeChildren := make([]cloudbeaver.NavNodeInfo, 0) + + // 创建connections的ID映射,提高查找效率 + connectionIDMap := make(map[string]bool) + for _, connection := range connections { + if connection != nil { + connectionIDMap[connection.CloudbeaverConnectionID] = true + } + } - // 用户不存在则创建CloudBeaver用户 - if len(cloudbeaverUserList.ListUsers) == 0 { - // 创建用户 - createUserReq := cloudbeaver.NewRequest(cu.graphQl.CreateUserQuery(), map[string]interface{}{ - "userId": cloudbeaverUserId, - }) - err = graphQLClient.Run(ctx, createUserReq, &UserList{}) - if err != nil { - return fmt.Errorf("create cloudbeaver user failed: %v", err) + // 只保留在connections中存在的navNode + for _, navNode := range navNodeChildrenResponse.Data.NavNodeChildren { + if connectionIDMap[strings.TrimPrefix(navNode.ID, "database://")] { + filteredNavNodeChildren = append(filteredNavNodeChildren, navNode) + } } + // 保持完整的 GraphQL 响应结构,只修改 data.navNodeChildren 部分 + var originalResponse map[string]interface{} + if err := json.Unmarshal(responseBuf.Bytes(), &originalResponse); err != nil { + cu.log.Errorf("failed to unmarshal original response: %v", err) + return + } + + // 更新 data.navNodeChildren + if data, ok := originalResponse["data"].(map[string]interface{}); ok { + data["navNodeChildren"] = filteredNavNodeChildren + } + + // 重新序列化并更新responseBuf + updatedResponseBytes, err := json.Marshal(originalResponse) + if err != nil { + cu.log.Errorf("failed to marshal updated response: %v", err) + return + } + + // 清空原buffer并写入新的响应 + responseBuf.Reset() + responseBuf.Write(updatedResponseBytes) + + cu.log.Warnf("user %s filtered navNodeChildren from %d to %d based on connections", + currentUserUid, originalCount, len(filteredNavNodeChildren)) + } +} + +func (cu *CloudbeaverUsecase) isEnableSQLAudit(dbService *DBService) bool { + if dbService.SQLEConfig == nil || dbService.SQLEConfig.SQLQueryConfig == nil { + return false + } + return dbService.SQLEConfig.AuditEnabled && dbService.SQLEConfig.SQLQueryConfig.AuditEnabled +} + +func (cu *CloudbeaverUsecase) isEnableWorkflowExec(dbService *DBService) bool { + if dbService.SQLEConfig == nil || dbService.SQLEConfig.SQLQueryConfig == nil { + return false + } + return dbService.SQLEConfig.AuditEnabled && dbService.SQLEConfig.SQLQueryConfig.WorkflowExecEnabled +} + +func (cu *CloudbeaverUsecase) isExecuteAnyway(params *graphql.RawParams) bool { + if params == nil || params.Variables == nil { + return false + } + + v, exist := params.Variables["isExecuteAnyway"] + if !exist || v == nil { + return false + } + + switch val := v.(type) { + case bool: + return val + case string: + b, err := strconv.ParseBool(val) + if err == nil { + return b + } + } + + return false +} + +func (cu *CloudbeaverUsecase) getDbService(ctx context.Context, params *graphql.RawParams) (*DBService, error) { + var connectionId interface{} + var connectionIdStr string + var ok bool + + connectionId, ok = params.Variables["connectionId"] + if !ok { + return nil, fmt.Errorf("missing connectionId in %s query", params.OperationName) + } + + connectionIdStr, ok = connectionId.(string) + if !ok { + return nil, fmt.Errorf("connectionId %s convert failed", connectionId) + } + dbServiceId, err := cu.repo.GetDbServiceIdByConnectionId(ctx, connectionIdStr) + if err != nil { + return nil, err + } + + return cu.dbServiceUsecase.GetDBService(ctx, dbServiceId) +} + +type ActiveUserQueryRes struct { + User interface{} `json:"user"` +} + +func (cu *CloudbeaverUsecase) getActiveUserQuery(cookies []*http.Cookie) (*ActiveUserQueryRes, error) { + client := cloudbeaver.NewGraphQlClient(cu.getGraphQLServerURI(), cloudbeaver.WithCookie(cookies), cloudbeaver.WithLogger(cu.log)) + req := cloudbeaver.NewRequest(cu.graphQl.GetActiveUserQuery(), map[string]interface{}{}) + + res := &ActiveUserQueryRes{} + if err := client.Run(context.TODO(), req, res); err != nil { + return nil, err + } + return res, nil +} + +type cloudbeaverSession struct { + dmsToken string + cloudbeaverSessionId string +} + +type authCache struct { + cookies []*http.Cookie + expiresAt time.Time +} + +var ( + dmsUserIdCloudbeaverLoginMap = make(map[string]cloudbeaverSession) + tokenMapMutex = &sync.Mutex{} + + // 统一认证缓存 + authCacheMap = make(map[string]*authCache) + authMutex = &sync.Mutex{} + + // 缓存过期时间:5分钟 + authCacheExpiry = 5 * time.Minute +) + +func (cu *CloudbeaverUsecase) getCloudbeaverSession(dmsUserId, dmsToken string) string { + tokenMapMutex.Lock() + defer tokenMapMutex.Unlock() + + if item, ok := dmsUserIdCloudbeaverLoginMap[dmsUserId]; ok { + if dmsToken == item.dmsToken { + return item.cloudbeaverSessionId + } + } + + return "" +} + +func (cu *CloudbeaverUsecase) UnbindCBSession(token string) { + tokenMapMutex.Lock() + defer tokenMapMutex.Unlock() + delete(dmsUserIdCloudbeaverLoginMap, token) +} + +func (cu *CloudbeaverUsecase) setCloudbeaverSession(dmsUserId, dmsToken, cloudbeaverSessionId string) { + tokenMapMutex.Lock() + defer tokenMapMutex.Unlock() + + dmsUserIdCloudbeaverLoginMap[dmsUserId] = cloudbeaverSession{ + dmsToken: dmsToken, + cloudbeaverSessionId: cloudbeaverSessionId, + } +} + +// getAuthCache 获取认证缓存 +func (cu *CloudbeaverUsecase) getAuthCache(username string) []*http.Cookie { + authMutex.Lock() + defer authMutex.Unlock() + + cache, exists := authCacheMap[username] + if !exists || time.Now().After(cache.expiresAt) { + // 缓存不存在或已过期,清理 + delete(authCacheMap, username) + return nil + } + + cu.log.Debugf("Using cached auth for user: %s", username) + return cache.cookies +} + +// setAuthCache 设置认证缓存 +func (cu *CloudbeaverUsecase) setAuthCache(username string, cookies []*http.Cookie) { + authMutex.Lock() + defer authMutex.Unlock() + + authCacheMap[username] = &authCache{ + cookies: cookies, + expiresAt: time.Now().Add(authCacheExpiry), + } + + cu.log.Debugf("Cached auth for user: %s, expires at: %v", username, authCacheMap[username].expiresAt) +} + +// getAuthCookies 获取认证 cookies(复用缓存逻辑) +func (cu *CloudbeaverUsecase) getAuthCookies(username, password string) ([]*http.Cookie, error) { + // 尝试从缓存获取认证信息 + cachedCookies := cu.getAuthCache(username) + if cachedCookies != nil { + cu.log.Debugf("Using cached authentication for user: %s", username) + return cachedCookies, nil + } + + // 缓存未命中,执行登录 + cu.log.Debugf("Cache miss, performing CloudBeaver login for user: %s", username) + cookies, err := cu.loginCloudbeaverServer(username, password) + if err != nil { + return nil, err + } + + // 缓存认证信息 + cu.setAuthCache(username, cookies) + return cookies, nil +} + +// clearExpiredAuthCache 清理过期的认证缓存 +func (cu *CloudbeaverUsecase) clearExpiredAuthCache() { + authMutex.Lock() + defer authMutex.Unlock() + + now := time.Now() + for user, cache := range authCacheMap { + if now.After(cache.expiresAt) { + delete(authCacheMap, user) + cu.log.Debugf("Cleared expired auth cache for user: %s", user) + } + } +} + +// startCacheCleanupRoutine 启动缓存清理协程 +func (cu *CloudbeaverUsecase) startCacheCleanupRoutine() { + ticker := time.NewTicker(authCacheExpiry / 2) // 每2.5分钟清理一次 + defer ticker.Stop() + + for range ticker.C { + cu.clearExpiredAuthCache() + } +} + +type UserList struct { + ListUsers []struct { + UserID string `json:"userID"` + } `json:"listUsers"` +} + +var reservedCloudbeaverUserId = map[string]struct{}{"admin": {}, "user": {}} + +func (cu *CloudbeaverUsecase) createUserIfNotExist(ctx context.Context, cloudbeaverUserId string, dmsUser *User) error { + cu.log.Infof("Creating CloudBeaver user if not exist: %s for DMS user: %s", cloudbeaverUserId, dmsUser.UID) + + if _, ok := reservedCloudbeaverUserId[cloudbeaverUserId]; ok { + cu.log.Errorf("Username %s is reserved and cannot be used", cloudbeaverUserId) + return fmt.Errorf("username %s is reserved, cann't be used", cloudbeaverUserId) + } + + // 使用管理员身份登录 + graphQLClient, err := cu.getGraphQLClientWithRootUser() + if err != nil { + cu.log.Errorf("Failed to get GraphQL client with root user for creating user %s: %v", cloudbeaverUserId, err) + return err + } + + userExist, err := cu.checkCloudBeaverUserExist(ctx, graphQLClient, cloudbeaverUserId) + if err != nil { + cu.log.Errorf("Failed to check if CloudBeaver user %s exists: %v", cloudbeaverUserId, err) + return fmt.Errorf("check cloudbeaver user exist failed: %v", err) + } + + // 用户不存在则创建CloudBeaver用户 + if !userExist { + cu.log.Infof("CloudBeaver user %s does not exist, creating new user", cloudbeaverUserId) + + // 创建用户 + createUserReq := cloudbeaver.NewRequest(cu.graphQl.CreateUserQuery(), map[string]interface{}{ + "userId": cloudbeaverUserId, + }) + err = graphQLClient.Run(ctx, createUserReq, &UserList{}) + if err != nil { + cu.log.Errorf("Failed to create CloudBeaver user %s: %v", cloudbeaverUserId, err) + return fmt.Errorf("create cloudbeaver user failed: %v", err) + } + + cu.log.Infof("Successfully created CloudBeaver user: %s", cloudbeaverUserId) + // 授予角色(不授予角色的用户无法登录) grantUserRoleReq := cloudbeaver.NewRequest(cu.graphQl.GrantUserRoleQuery(), map[string]interface{}{ "userId": cloudbeaverUserId, @@ -448,11 +1248,29 @@ func (cu *CloudbeaverUsecase) createUserIfNotExist(ctx context.Context, cloudbea }) err = graphQLClient.Run(ctx, grantUserRoleReq, nil) if err != nil { - return fmt.Errorf("create cloudbeaver user failed: %v", err) + cu.log.Errorf("Failed to grant role to CloudBeaver user %s: %v", cloudbeaverUserId, err) + return fmt.Errorf("grant cloudbeaver user failed: %v", err) + } + + cu.log.Infof("Successfully granted role to CloudBeaver user: %s", cloudbeaverUserId) + } else { + cu.log.Debugf("CloudBeaver user %s already exists, checking fingerprint", cloudbeaverUserId) + + cloudbeaverUser, exist, err := cu.repo.GetCloudbeaverUserByID(ctx, cloudbeaverUserId) + if err != nil { + cu.log.Errorf("Failed to get CloudBeaver user %s from cache: %v", cloudbeaverUserId, err) + return err + } + + if exist && cloudbeaverUser.DMSFingerprint == cu.userUsecase.GetUserFingerprint(dmsUser) { + cu.log.Debugf("CloudBeaver user %s fingerprint matches, no update needed", cloudbeaverUserId) + return nil } } // 设置CloudBeaver用户密码 + cu.log.Infof("Updating CloudBeaver user password for user: %s", cloudbeaverUserId) + updatePasswordReq := cloudbeaver.NewRequest(cu.graphQl.UpdatePasswordQuery(), map[string]interface{}{ "userId": cloudbeaverUserId, "credentials": model.JSON{ @@ -461,38 +1279,73 @@ func (cu *CloudbeaverUsecase) createUserIfNotExist(ctx context.Context, cloudbea }) err = graphQLClient.Run(ctx, updatePasswordReq, nil) if err != nil { + cu.log.Errorf("Failed to update CloudBeaver user password for user %s: %v", cloudbeaverUserId, err) return fmt.Errorf("update cloudbeaver user failed: %v", err) } - cloudbeaverUser = &CloudbeaverUser{ + cu.log.Infof("Successfully updated CloudBeaver user password for user: %s", cloudbeaverUserId) + + cloudbeaverUser := &CloudbeaverUser{ DMSUserID: dmsUser.UID, - DMSFingerprint: fingerprint, + DMSFingerprint: cu.userUsecase.GetUserFingerprint(dmsUser), CloudbeaverUserID: cloudbeaverUserId, } return cu.repo.UpdateCloudbeaverUserCache(ctx, cloudbeaverUser) } +func (cu *CloudbeaverUsecase) checkCloudBeaverUserExist(ctx context.Context, graphQLClient *cloudbeaver.Client, cloudbeaverUserId string) (bool, error) { + if graphQLClient == nil { + return false, fmt.Errorf("graphQLClient is nil") + } + + checkExistReq := cloudbeaver.NewRequest(cu.graphQl.IsUserExistQuery(cloudbeaverUserId)) + cloudbeaverUserList := UserList{} + err := graphQLClient.Run(ctx, checkExistReq, &cloudbeaverUserList) + if err != nil { + return false, err + } + for _, cloudBeaverUser := range cloudbeaverUserList.ListUsers { + if cloudBeaverUser.UserID == cloudbeaverUserId { + return true, nil + } + } + return false, nil +} + func (cu *CloudbeaverUsecase) connectManagement(ctx context.Context, cloudbeaverUserId string, dmsUser *User) error { activeDBServices, err := cu.dbServiceUsecase.GetActiveDBServices(ctx, nil) if err != nil { return err } - var dbServiceIds []string - if isAdmin, _ := cu.opPermissionVerifyUsecase.IsUserDMSAdmin(ctx, dmsUser.UID); !isAdmin { + if len(activeDBServices) == 0 { + return cu.clearConnection(ctx) + } + + hasGlobalOpPermission, err := cu.opPermissionVerifyUsecase.CanOpGlobal(ctx, dmsUser.UID) + if err != nil { + return err + } + + if !hasGlobalOpPermission { + activeDBServices, err = cu.ResetDbServiceByAuth(ctx, activeDBServices, dmsUser.UID) + if err != nil { + return err + } opPermissions, err := cu.opPermissionVerifyUsecase.GetUserOpPermission(ctx, dmsUser.UID) if err != nil { return err } - namespaceIdMap := map[string]struct{}{} + // 已配置的项目管理权限和数据源工作台查询权限 + projectIdMap := map[string]struct{}{} dbServiceIdMap := map[string]struct{}{} for _, opPermission := range opPermissions { - // namespace permission - if opPermission.OpRangeType == OpRangeTypeNamespace && opPermission.OpPermissionUID == constant.UIDOfOpPermissionNamespaceAdmin { + // project permission + if opPermission.OpRangeType == OpRangeTypeProject && opPermission.OpPermissionUID == constant.UIDOfOpPermissionProjectAdmin { for _, rangeUid := range opPermission.RangeUIDs { - namespaceIdMap[rangeUid] = struct{}{} + projectIdMap[rangeUid] = struct{}{} } } @@ -506,7 +1359,7 @@ func (cu *CloudbeaverUsecase) connectManagement(ctx context.Context, cloudbeaver var lastActiveDBServices []*DBService for _, activeDBService := range activeDBServices { - if _, ok := namespaceIdMap[activeDBService.NamespaceUID]; ok { + if _, ok := projectIdMap[activeDBService.ProjectUID]; ok { lastActiveDBServices = append(lastActiveDBServices, activeDBService) continue } @@ -519,14 +1372,6 @@ func (cu *CloudbeaverUsecase) connectManagement(ctx context.Context, cloudbeaver activeDBServices = lastActiveDBServices } - if len(activeDBServices) == 0 { - return nil - } - - if err = cu.createConnection(ctx, activeDBServices); err != nil { - return err - } - cloudbeaverUser, exist, err := cu.repo.GetCloudbeaverUserByID(ctx, cloudbeaverUserId) if err != nil { return err @@ -534,52 +1379,112 @@ func (cu *CloudbeaverUsecase) connectManagement(ctx context.Context, cloudbeaver if !exist { return fmt.Errorf("cloudbeaver user: %s not eixst", cloudbeaverUserId) } - if err = cu.grantAccessConnection(ctx, cloudbeaverUser, dmsUser, dbServiceIds); err != nil { + + if err = cu.operateConnection(ctx, cloudbeaverUser, dmsUser, activeDBServices); err != nil { + return err + } + + if err = cu.grantAccessConnection(ctx, cloudbeaverUser, dmsUser, activeDBServices); err != nil { return err } return nil } -func (cu *CloudbeaverUsecase) createConnection(ctx context.Context, activeDBServices []*DBService) error { - dbServiceIds := make([]string, 0, len(activeDBServices)) +// 判断连接是否唯一的条件:dbServiceId : purpose : userUid +func getDBPrimaryKey(dbUid, purpose, userUid string) string { + // service.UID:service.AccountPurpose:userId + return fmt.Sprint(dbUid, ":", purpose, ":", userUid) +} + +type UserConnectionsResp struct { + Connections []*struct { + Id string `json:"id"` + Template bool `json:"template"` + } `json:"connections"` +} + +// 获取用户当前数据库连接ID +func (cu *CloudbeaverUsecase) getUserConnectionIds(ctx context.Context, cloudbeaverUser *CloudbeaverUser, dmsUser *User) ([]string, error) { + // 使用3次重试,因为这个接口有时会出现不稳定的情况 + client, err := cu.getGraphQLClient(cloudbeaverUser.CloudbeaverUserID, dmsUser.Password, 3) + if err != nil { + return nil, err + } + + var userConnectionsResp UserConnectionsResp + + variables := map[string]interface{}{"projectId": cloudbeaverProjectId} + err = client.Run(ctx, cloudbeaver.NewRequest(cu.graphQl.GetUserConnectionsQuery(), variables), &userConnectionsResp) + if err != nil { + return nil, err + } + + ret := make([]string, 0, len(userConnectionsResp.Connections)) + for _, connection := range userConnectionsResp.Connections { + if !connection.Template { + ret = append(ret, connection.Id) + } + } + + return ret, nil +} + +func (cu *CloudbeaverUsecase) operateConnection(ctx context.Context, cloudbeaverUser *CloudbeaverUser, dmsUser *User, activeDBServices []*DBService) error { dbServiceMap := map[string]*DBService{} - namespaceMap := map[string]string{} + projectMap := map[string]string{} for _, service := range activeDBServices { - dbServiceIds = append(dbServiceIds, service.UID) - dbServiceMap[service.UID] = service + dbServiceMap[getDBPrimaryKey(service.UID, service.AccountPurpose, dmsUser.UID)] = service - namespace, err := cu.dbServiceUsecase.namespaceUsecase.GetNamespace(ctx, service.NamespaceUID) + project, err := cu.dbServiceUsecase.projectUsecase.GetProject(ctx, service.ProjectUID) if err != nil { - namespaceMap[service.UID] = "unknown" - cu.log.Errorf("get db service namespace %s failed, err: %v", service.NamespaceUID, err) + projectMap[service.UID] = "unknown" + cu.log.Errorf("get db service project %s failed, err: %v", service.ProjectUID, err) } else { - namespaceMap[service.UID] = namespace.Name + projectMap[service.UID] = project.Name } } - cloudbeaverConnections, err := cu.repo.GetCloudbeaverConnectionByDMSDBServiceIds(ctx, dbServiceIds) + // 获取当前用户所有已创建的连接 + localCloudbeaverConnections, err := cu.repo.GetCloudbeaverConnectionsByUserId(ctx, dmsUser.UID) if err != nil { return err } + // cloudbeaver连接数为空则重置缓存 + if userConnectionIds, err := cu.getUserConnectionIds(ctx, cloudbeaverUser, dmsUser); err != nil { + return err + } else if len(userConnectionIds) == 0 { + localCloudbeaverConnections = []*CloudbeaverConnection{} + } + + var deleteConnections []*CloudbeaverConnection + cloudbeaverConnectionMap := map[string]*CloudbeaverConnection{} - for _, service := range cloudbeaverConnections { - cloudbeaverConnectionMap[service.DMSDBServiceID] = service + for _, connection := range localCloudbeaverConnections { + // 删除用户关联的连接 + if connection.DMSUserId == dmsUser.UID { + cloudbeaverConnectionMap[connection.PrimaryKey()] = connection + if _, ok := dbServiceMap[connection.PrimaryKey()]; !ok { + deleteConnections = append(deleteConnections, connection) + } + } } - var createConnection []string - var updateConnection []string + var createConnections []*CloudbeaverConnection + var updateConnections []*CloudbeaverConnection - for dbServiceId, dbService := range dbServiceMap { - if cloudbeaverConnection, ok := cloudbeaverConnectionMap[dbServiceId]; !ok { - createConnection = append(createConnection, dbService.UID) - } else if cloudbeaverConnection.DMSDBServiceFingerprint != cu.dbServiceUsecase.GetDBServiceFingerprint(dbService) { - updateConnection = append(updateConnection, dbService.UID) + for _, dbService := range dbServiceMap { + if cloudbeaverConnection, ok := cloudbeaverConnectionMap[getDBPrimaryKey(dbService.UID, dbService.AccountPurpose, dmsUser.UID)]; ok { + if cloudbeaverConnection.DMSDBServiceFingerprint != cu.dbServiceUsecase.GetDBServiceFingerprint(dbService) { + updateConnections = append(updateConnections, &CloudbeaverConnection{DMSDBServiceID: dbService.UID, CloudbeaverConnectionID: cloudbeaverConnection.CloudbeaverConnectionID, Purpose: dbService.AccountPurpose, DMSUserId: dmsUser.UID}) + } + } else { + createConnections = append(createConnections, &CloudbeaverConnection{DMSDBServiceID: dbService.UID, Purpose: dbService.AccountPurpose, DMSUserId: dmsUser.UID}) } } - if len(createConnection) == 0 && len(updateConnection) == 0 { + if len(createConnections) == 0 && len(updateConnections) == 0 && len(deleteConnections) == 0 { return nil } @@ -590,61 +1495,89 @@ func (cu *CloudbeaverUsecase) createConnection(ctx context.Context, activeDBServ } // 同步实例连接信息 - for _, dbServiceId := range createConnection { - if err = cu.createCloudbeaverConnection(ctx, cloudbeaverClient, dbServiceMap[dbServiceId], namespaceMap[dbServiceId]); err != nil { - cu.log.Errorf("create dnServerId %s connection failed: %v", dbServiceId, err) + for _, createConnection := range createConnections { + if err = cu.createCloudbeaverConnection(ctx, cloudbeaverClient, dbServiceMap[getDBPrimaryKey(createConnection.DMSDBServiceID, createConnection.Purpose, dmsUser.UID)], + projectMap[createConnection.DMSDBServiceID], dmsUser.UID); err != nil { + cu.log.Errorf("create connection %v failed: %v", createConnection, err) + } + } + + for _, updateConnection := range updateConnections { + if err = cu.updateCloudbeaverConnection(ctx, cloudbeaverClient, updateConnection.CloudbeaverConnectionID, dbServiceMap[getDBPrimaryKey(updateConnection.DMSDBServiceID, updateConnection.Purpose, dmsUser.UID)], projectMap[updateConnection.DMSDBServiceID], dmsUser.UID); err != nil { + cu.log.Errorf("update dnServerId %s to connection failed: %v", updateConnection, err) } } - for _, dbServiceId := range updateConnection { - if err = cu.updateCloudbeaverConnection(ctx, cloudbeaverClient, cloudbeaverConnectionMap[dbServiceId].CloudbeaverConnectionID, dbServiceMap[dbServiceId], namespaceMap[dbServiceId]); err != nil { - cu.log.Errorf("update dnServerId %s to connection failed: %v", dbServiceId, err) + for _, deleteConnection := range deleteConnections { + if err = cu.deleteCloudbeaverConnection(ctx, cloudbeaverClient, deleteConnection.CloudbeaverConnectionID, deleteConnection.DMSDBServiceID, dmsUser.UID, deleteConnection.Purpose); err != nil { + cu.log.Errorf("delete connection %v failed: %v", deleteConnection, err) } } return nil } -func (cu *CloudbeaverUsecase) grantAccessConnection(ctx context.Context, cloudbeaverUser *CloudbeaverUser, dmsUser *User, dbServiceIds []string) error { - if cloudbeaverUser.DMSFingerprint != cu.userUsecase.GetUserFingerprint(dmsUser) { - return fmt.Errorf("user information is not synchronized, unable to update connection information") +// 删除DMS已知待删除的连接 +func (cu *CloudbeaverUsecase) clearConnection(ctx context.Context) error { + cloudbeaverConnections, err := cu.repo.GetAllCloudbeaverConnections(ctx) + if err != nil { + return err } - cloudbeaverConnections, err := cu.repo.GetCloudbeaverConnectionByDMSDBServiceIds(ctx, dbServiceIds) + // 获取管理员链接 + cloudbeaverClient, err := cu.getGraphQLClientWithRootUser() if err != nil { return err } - // 从缓存中获取需要同步的CloudBeaver实例 - cloudbeaverConnectionMap := map[string]*CloudbeaverConnection{} - for _, cloudbeaverConnection := range cloudbeaverConnections { - cloudbeaverConnectionMap[cloudbeaverConnection.CloudbeaverConnectionID] = cloudbeaverConnection + for _, item := range cloudbeaverConnections { + if err = cu.deleteCloudbeaverConnection(ctx, cloudbeaverClient, item.CloudbeaverConnectionID, item.DMSDBServiceID, "", ""); err != nil { + cu.log.Errorf("delete dbServerId %s to connection failed: %v", item.DMSDBServiceID, err) + + return fmt.Errorf("delete dbServerId %s to connection failed: %v", item.DMSDBServiceID, err) + } } - // 获取用户当前实例列表 - connResp := &struct { - Connections []*struct { - Id string `json:"id"` - } `json:"connections"` - }{} + return nil +} + +func (cu *CloudbeaverUsecase) grantAccessConnection(ctx context.Context, cloudbeaverUser *CloudbeaverUser, dmsUser *User, activeDBServices []*DBService) error { + if cloudbeaverUser.DMSFingerprint != cu.userUsecase.GetUserFingerprint(dmsUser) { + return fmt.Errorf("user information is not synchronized, unable to update connection information") + } + + // 清空绑定能访问的数据库连接 + if len(activeDBServices) == 0 { + return cu.bindUserAccessConnection(ctx, []*CloudbeaverConnection{}, cloudbeaverUser.CloudbeaverUserID) + } - client, err := cu.getGraphQLClient(cloudbeaverUser.CloudbeaverUserID, dmsUser.Password) + dbServiceIds := make([]string, 0, len(activeDBServices)) + for _, dbService := range activeDBServices { + dbServiceIds = append(dbServiceIds, dbService.UID) + } + localCloudbeaverConnections, err := cu.repo.GetCloudbeaverConnectionsByUserIdAndDBServiceIds(ctx, dmsUser.UID, dbServiceIds) if err != nil { return err } - err = client.Run(ctx, cloudbeaver.NewRequest(cu.graphQl.GetUserConnectionsQuery(), nil), connResp) + // 从缓存中获取需要同步的CloudBeaver实例 + cloudbeaverConnectionMap := map[string]*CloudbeaverConnection{} + for _, connection := range localCloudbeaverConnections { + cloudbeaverConnectionMap[connection.CloudbeaverConnectionID] = connection + } + + cloudbeaverConnectionIds, err := cu.getUserConnectionIds(ctx, cloudbeaverUser, dmsUser) if err != nil { return err } - if len(connResp.Connections) != len(cloudbeaverConnections) { - return cu.bindUserAccessConnection(ctx, cloudbeaverConnections, cloudbeaverUser.CloudbeaverUserID) + if len(cloudbeaverConnectionIds) != len(localCloudbeaverConnections) { + return cu.bindUserAccessConnection(ctx, localCloudbeaverConnections, cloudbeaverUser.CloudbeaverUserID) } - for _, connection := range connResp.Connections { - if _, ok := cloudbeaverConnectionMap[connection.Id]; !ok { - return cu.bindUserAccessConnection(ctx, cloudbeaverConnections, cloudbeaverUser.CloudbeaverUserID) + for _, connectionId := range cloudbeaverConnectionIds { + if _, ok := cloudbeaverConnectionMap[connectionId]; !ok { + return cu.bindUserAccessConnection(ctx, localCloudbeaverConnections, cloudbeaverUser.CloudbeaverUserID) } } @@ -652,11 +1585,15 @@ func (cu *CloudbeaverUsecase) grantAccessConnection(ctx context.Context, cloudbe } func (cu *CloudbeaverUsecase) bindUserAccessConnection(ctx context.Context, cloudbeaverDBServices []*CloudbeaverConnection, cloudBeaverUserID string) error { - var cloudbeaverConnectionIds []string + cu.log.Infof("Binding CloudBeaver connections to user: %s, connection count: %d", cloudBeaverUserID, len(cloudbeaverDBServices)) + + cloudbeaverConnectionIds := make([]string, 0, len(cloudbeaverDBServices)) for _, service := range cloudbeaverDBServices { cloudbeaverConnectionIds = append(cloudbeaverConnectionIds, service.CloudbeaverConnectionID) } + cu.log.Debugf("CloudBeaver connection IDs for user %s: %v", cloudBeaverUserID, cloudbeaverConnectionIds) + cloudbeaverConnReq := cloudbeaver.NewRequest(cu.graphQl.SetUserConnectionsQuery(), map[string]interface{}{ "userId": cloudBeaverUserID, "connections": cloudbeaverConnectionIds, @@ -664,15 +1601,27 @@ func (cu *CloudbeaverUsecase) bindUserAccessConnection(ctx context.Context, clou rootClient, err := cu.getGraphQLClientWithRootUser() if err != nil { + cu.log.Errorf("Failed to get GraphQL client with root user for binding connections to user %s: %v", cloudBeaverUserID, err) return err } - return rootClient.Run(ctx, cloudbeaverConnReq, nil) + err = rootClient.Run(ctx, cloudbeaverConnReq, nil) + if err != nil { + cu.log.Errorf("Failed to bind CloudBeaver connections to user %s: %v", cloudBeaverUserID, err) + return err + } + + cu.log.Infof("Successfully bound %d CloudBeaver connections to user: %s", len(cloudbeaverConnectionIds), cloudBeaverUserID) + return nil } -func (cu *CloudbeaverUsecase) createCloudbeaverConnection(ctx context.Context, client *cloudbeaver.Client, dbService *DBService, namespace string) error { - params, err := cu.GenerateCloudbeaverConnectionParams(dbService, namespace) +func (cu *CloudbeaverUsecase) createCloudbeaverConnection(ctx context.Context, client *cloudbeaver.Client, dbService *DBService, project, userId string) error { + cu.log.Infof("Creating CloudBeaver connection for DB service: %s, project: %s, user: %s, purpose: %s", + dbService.UID, project, userId, dbService.AccountPurpose) + + params, err := cu.GenerateCloudbeaverConnectionParams(dbService, project, dbService.AccountPurpose) if err != nil { + cu.log.Errorf("Failed to generate connection params for DB service %s: %v", dbService.UID, err) return fmt.Errorf("%s unsupported", dbService.DBType) } @@ -686,26 +1635,40 @@ func (cu *CloudbeaverUsecase) createCloudbeaverConnection(ctx context.Context, c err = client.Run(ctx, req, &resp) if err != nil { + cu.log.Errorf("Failed to create CloudBeaver connection for DB service %s: %v", dbService.UID, err) return err } + cu.log.Infof("Successfully created CloudBeaver connection: %s for DB service: %s", resp.Connection.ID, dbService.UID) + // 同步缓存 - return cu.repo.UpdateCloudbeaverConnectionCache(ctx, &CloudbeaverConnection{ + err = cu.repo.UpdateCloudbeaverConnectionCache(ctx, &CloudbeaverConnection{ DMSDBServiceID: dbService.UID, + DMSUserId: userId, DMSDBServiceFingerprint: cu.dbServiceUsecase.GetDBServiceFingerprint(dbService), + Purpose: dbService.AccountPurpose, CloudbeaverConnectionID: resp.Connection.ID, }) + if err != nil { + cu.log.Errorf("Failed to update CloudBeaver connection cache for DB service %s: %v", dbService.UID, err) + } + return err } // UpdateCloudbeaverConnection 更新完毕后会同步缓存 -func (cu *CloudbeaverUsecase) updateCloudbeaverConnection(ctx context.Context, client *cloudbeaver.Client, cloudbeaverConnectionId string, dbService *DBService, namespace string) error { - params, err := cu.GenerateCloudbeaverConnectionParams(dbService, namespace) +func (cu *CloudbeaverUsecase) updateCloudbeaverConnection(ctx context.Context, client *cloudbeaver.Client, cloudbeaverConnectionId string, dbService *DBService, project, userId string) error { + cu.log.Infof("Updating CloudBeaver connection: %s for DB service: %s, project: %s, user: %s, purpose: %s", + cloudbeaverConnectionId, dbService.UID, project, userId, dbService.AccountPurpose) + + params, err := cu.GenerateCloudbeaverConnectionParams(dbService, project, dbService.AccountPurpose) if err != nil { + cu.log.Errorf("Failed to generate connection params for DB service %s: %v", dbService.UID, err) return fmt.Errorf("%s unsupported", dbService.DBType) } config, ok := params["config"].(map[string]interface{}) if !ok { + cu.log.Errorf("Failed to assert connection params for DB service %s", dbService.UID) return errors.New("assert connection params failed") } @@ -720,55 +1683,114 @@ func (cu *CloudbeaverUsecase) updateCloudbeaverConnection(ctx context.Context, c err = client.Run(ctx, req, &resp) if err != nil { + cu.log.Errorf("Failed to update CloudBeaver connection %s for DB service %s: %v", cloudbeaverConnectionId, dbService.UID, err) return err } - return cu.repo.UpdateCloudbeaverConnectionCache(ctx, &CloudbeaverConnection{ + cu.log.Infof("Successfully updated CloudBeaver connection: %s for DB service: %s", resp.Connection.ID, dbService.UID) + + err = cu.repo.UpdateCloudbeaverConnectionCache(ctx, &CloudbeaverConnection{ DMSDBServiceID: dbService.UID, + DMSUserId: userId, DMSDBServiceFingerprint: cu.dbServiceUsecase.GetDBServiceFingerprint(dbService), + Purpose: dbService.AccountPurpose, CloudbeaverConnectionID: resp.Connection.ID, }) + if err != nil { + cu.log.Errorf("Failed to update CloudBeaver connection cache for DB service %s: %v", dbService.UID, err) + } + return err } -func (cu *CloudbeaverUsecase) generateCommonCloudbeaverConfigParams(dbService *DBService, namespace string) map[string]interface{} { +func (cu *CloudbeaverUsecase) deleteCloudbeaverConnection(ctx context.Context, client *cloudbeaver.Client, cloudbeaverConnectionId, dbServiceId, userId, purpose string) error { + cu.log.Infof("Deleting CloudBeaver connection: %s for DB service: %s, user: %s, purpose: %s", + cloudbeaverConnectionId, dbServiceId, userId, purpose) + + variables := make(map[string]interface{}) + variables["connectionId"] = cloudbeaverConnectionId + variables["projectId"] = cloudbeaverProjectId + + req := cloudbeaver.NewRequest(cu.graphQl.DeleteConnectionQuery(), variables) + resp := struct { + DeleteConnection bool `json:"deleteConnection"` + }{} + + if err := client.Run(ctx, req, &resp); err != nil { + cu.log.Errorf("Failed to delete CloudBeaver connection %s for DB service %s: %v", cloudbeaverConnectionId, dbServiceId, err) + return err + } + + cu.log.Infof("Successfully deleted CloudBeaver connection: %s for DB service: %s", cloudbeaverConnectionId, dbServiceId) + + err := cu.repo.DeleteCloudbeaverConnectionCache(ctx, dbServiceId, userId, purpose) + if err != nil { + cu.log.Errorf("Failed to delete CloudBeaver connection cache for DB service %s: %v", dbServiceId, err) + } + return err +} + +func (cu *CloudbeaverUsecase) generateCommonCloudbeaverConfigParams(dbService *DBService, project, purpose string) map[string]interface{} { + name := fmt.Sprintf("%s:%s", project, dbService.Name) + if purpose != "" { + name = fmt.Sprintf("%s:%s", name, purpose) + } return map[string]interface{}{ "configurationType": "MANUAL", - "name": fmt.Sprintf("%v: %v", namespace, dbService.Name), - "template": false, - "host": dbService.Host, - "port": dbService.Port, - "databaseName": nil, - "description": nil, - "authModelId": "native", - "saveCredentials": true, + "name": name, + // "template": false, + "host": dbService.Host, + "port": dbService.Port, + "databaseName": nil, + "description": nil, + "authModelId": "native", + "saveCredentials": true, "credentials": map[string]interface{}{ - "userName": dbService.AdminUser, - "userPassword": dbService.AdminPassword, + "userName": dbService.User, + "userPassword": dbService.Password, }, } } -func (cu *CloudbeaverUsecase) GenerateCloudbeaverConnectionParams(dbService *DBService, namespace string) (map[string]interface{}, error) { +const cloudbeaverProjectId = "g_GlobalConfiguration" + +func (cu *CloudbeaverUsecase) GenerateCloudbeaverConnectionParams(dbService *DBService, project string, purpose string) (map[string]interface{}, error) { var err error - config := cu.generateCommonCloudbeaverConfigParams(dbService, namespace) + config := cu.generateCommonCloudbeaverConfigParams(dbService, project, purpose) - switch dbService.DBType { - case constant.DBTypeMySQL: + dbType, err := constant.ParseDBType(dbService.DBType) + if err != nil { + return nil, err + } + switch dbType { + case constant.DBTypeMySQL, constant.DBTypeTDSQLForInnoDB: err = cu.fillMySQLParams(config) - case constant.DBTypePostgreSQL: + case constant.DBTypeTiDB: + err = cu.fillTiDBParams(config) + case constant.DBTypePostgreSQL, constant.DBTypeTBase: err = cu.fillPGSQLParams(config) case constant.DBTypeSQLServer: err = cu.fillMSSQLParams(config) case constant.DBTypeOracle: err = cu.fillOracleParams(dbService, config) + case constant.DBTypeDB2: + err = cu.fillDB2Params(dbService, config) case constant.DBTypeOceanBaseMySQL: err = cu.fillOceanBaseParams(dbService, config) + case constant.DBTypeGoldenDB: + err = cu.fillGoldenDBParams(config) + case constant.DBTypeHive: + err = cu.fillHive4Params(config) + case constant.DBTypeDM: + err = cu.fillDMParams(config) + case constant.DBTypeGaussDB: + err = cu.fillGaussDBParams(config) + default: return nil, fmt.Errorf("temporarily unsupported instance types") } resp := map[string]interface{}{ - "projectId": "g_GlobalConfiguration", + "projectId": cloudbeaverProjectId, "config": config, } return resp, err @@ -776,6 +1798,13 @@ func (cu *CloudbeaverUsecase) GenerateCloudbeaverConnectionParams(dbService *DBS func (cu *CloudbeaverUsecase) fillMySQLParams(config map[string]interface{}) error { config["driverId"] = "mysql:mysql8" + // https://github.com/actiontech/dms-ee/issues/276 + config["properties"] = map[string]interface{}{"allowPublicKeyRetrieval": "TRUE"} + return nil +} + +func (cu *CloudbeaverUsecase) fillTiDBParams(config map[string]interface{}) error { + config["driverId"] = "mysql:tidb" return nil } @@ -787,6 +1816,7 @@ func (cu *CloudbeaverUsecase) fillMSSQLParams(config map[string]interface{}) err func (cu *CloudbeaverUsecase) fillPGSQLParams(config map[string]interface{}) error { config["driverId"] = "postgresql:postgres-jdbc" + config["databaseName"] = "postgres" config["providerProperties"] = map[string]interface{}{ "@dbeaver-show-non-default-db@": true, "@dbeaver-show-unavailable-db@": true, @@ -804,49 +1834,98 @@ func (cu *CloudbeaverUsecase) fillOracleParams(inst *DBService, config map[strin config["driverId"] = "oracle:oracle_thin" config["authModelId"] = "oracle_native" config["databaseName"] = serviceName.Value - config["providerProperties"] = map[string]interface{}{ - "@dbeaver-sid-service@": "SID", + + providerProperties := map[string]interface{}{ + "@dbeaver-sid-service@": "SERVICE", "oracle.logon-as": "Normal", } + // sys用户不能用normal角色登陆,根据用户名做特殊处理 + if inst.User == "sys" { + providerProperties["oracle.logon-as"] = "SYSDBA" + } + + config["providerProperties"] = providerProperties + + // 默认关闭timezoneAsRegion,防止连接Oracle11g报错 + config["properties"] = map[string]interface{}{ + "oracle.jdbc.timezoneAsRegion": false, + } return nil } -func (cu *CloudbeaverUsecase) fillOceanBaseParams(inst *DBService, config map[string]interface{}) error { - tenant := inst.AdditionalParams.GetParam("tenant_name") - if tenant == nil { - return fmt.Errorf("the tenant name of oceanbase cannot be empty") +func (cu *CloudbeaverUsecase) fillDB2Params(inst *DBService, config map[string]interface{}) error { + dbName := inst.AdditionalParams.GetParam("database_name") + if dbName == nil { + return fmt.Errorf("the database name of DB2 cannot be empty") } - config["driverId"] = "oceanbase:alipay_oceanbase" - config["authModelId"] = "oceanbase_native" + config["driverId"] = "db2:db2" + config["databaseName"] = dbName.Value + return nil +} - credentials := config["credentials"] - credentialConfig, ok := credentials.(map[string]interface{}) - if !ok { - return errors.New("assert oceanbase connection params failed") +func (cu *CloudbeaverUsecase) fillOceanBaseParams(inst *DBService, config map[string]interface{}) error { + // 获取租户, 在用户名处指定连接的租户: user@tenant + tenant := inst.AdditionalParams.GetParam("tenant_name").String() + if !strings.Contains(inst.User, "@") && tenant != "" { + inst.User = fmt.Sprintf("%s@%s", inst.User, tenant) } - credentialConfig["userName"] = fmt.Sprintf("%v@%v", inst.AdminUser, tenant) - config["credentials"] = credentialConfig + // OB MySQL本身支持使用MySQL客户端连接, 此处复用MySQL driver + // https://github.com/actiontech/dms/issues/365 + config["driverId"] = "mysql:mysql8" + return nil +} + +func (cu *CloudbeaverUsecase) fillGoldenDBParams(config map[string]interface{}) error { + config["driverId"] = "mysql:mysql8" + return nil +} + +func (cu *CloudbeaverUsecase) fillHive4Params(config map[string]interface{}) error { + config["driverId"] = "hive:apache_hive4" + return nil +} + +func (cu *CloudbeaverUsecase) fillDMParams(config map[string]interface{}) error { + config["driverId"] = "generic:dameng_jdbc" + return nil +} + +func (cu *CloudbeaverUsecase) fillGaussDBParams(config map[string]interface{}) error { + config["driverId"] = "generic:gaussdb_jdbc" return nil } func (cu *CloudbeaverUsecase) getGraphQLClientWithRootUser() (*cloudbeaver.Client, error) { - cookies, err := cu.loginCloudbeaverServer(cu.cloudbeaverCfg.AdminUser, cu.cloudbeaverCfg.AdminPassword) + adminUser := cu.cloudbeaverCfg.AdminUser + + cookies, err := cu.getAuthCookies(adminUser, cu.cloudbeaverCfg.AdminPassword) if err != nil { return nil, err } - return cloudbeaver.NewGraphQlClient(cu.getGraphQLServerURI(), cloudbeaver.WithCookie(cookies)), nil + return cloudbeaver.NewGraphQlClient(cu.getGraphQLServerURI(), cloudbeaver.WithCookie(cookies), cloudbeaver.WithLogger(cu.log)), nil } // 这个客户端会用指定用户操作, 请求会直接发到CB -func (cu *CloudbeaverUsecase) getGraphQLClient(username, password string) (*cloudbeaver.Client, error) { - cookies, err := cu.loginCloudbeaverServer(username, password) +// maxRetries 为可选参数,默认为0(不重试) +func (cu *CloudbeaverUsecase) getGraphQLClient(username, password string, maxRetries ...int) (*cloudbeaver.Client, error) { + cookies, err := cu.getAuthCookies(username, password) if err != nil { return nil, err } - return cloudbeaver.NewGraphQlClient(cu.getGraphQLServerURI(), cloudbeaver.WithCookie(cookies)), nil + opts := []cloudbeaver.ClientOption{ + cloudbeaver.WithCookie(cookies), + cloudbeaver.WithLogger(cu.log), + } + + // 如果提供了重试次数参数,则添加重试配置 + if len(maxRetries) > 0 && maxRetries[0] > 0 { + opts = append(opts, cloudbeaver.WithMaxRetries(maxRetries[0])) + } + + return cloudbeaver.NewGraphQlClient(cu.getGraphQLServerURI(), opts...), nil } func (cu *CloudbeaverUsecase) loginCloudbeaverServer(user, pwd string) (cookie []*http.Cookie, err error) { @@ -855,7 +1934,7 @@ func (cu *CloudbeaverUsecase) loginCloudbeaverServer(user, pwd string) (cookie [ if response != nil { cookie = response.Cookies() } - })) + }), cloudbeaver.WithLogger(cu.log)) req := cloudbeaver.NewRequest(cu.graphQl.LoginQuery(), map[string]interface{}{ "credentials": model.JSON{ "user": user, @@ -869,8 +1948,426 @@ func (cu *CloudbeaverUsecase) loginCloudbeaverServer(user, pwd string) (cookie [ } `json:"authInfo"` }{} if err = client.Run(context.TODO(), req, &res); err != nil { - return cookie, fmt.Errorf("cloudbeaver login failed: %v", err) + return cookie, fmt.Errorf("cloudbeaver login failed: %v,req: %v,res %v", err, req, res) } return cookie, nil } + +type GraphQLResponse struct { + Data json.RawMessage `json:"data"` + Errors []GraphQLError `json:"errors"` +} + +func (g *GraphQLResponse) Bytes() ([]byte, error) { + return json.Marshal(g) +} + +type GraphQLError struct { + Message string `json:"message"` + Locations []map[string]int `json:"locations"` + Path []interface{} `json:"path"` + Extensions map[string]interface{} `json:"extensions"` +} + +func UnmarshalGraphQLResponse(body []byte, taskInfo *TaskInfo) error { + var gqlResp GraphQLResponse + if err := json.Unmarshal(body, &gqlResp); err != nil { + return err // 真正 JSON 格式错误时才报错 + } + + if len(gqlResp.Errors) > 0 { + // GraphQL 执行错误 + return fmt.Errorf("GraphQL error: %s", gqlResp.Errors[0].Message) + } + + // 再解析 Data 成真正结构 + if err := json.Unmarshal(body, taskInfo); err != nil { + return err + } + if taskInfo == nil || taskInfo.Data.TaskInfo == nil { + return fmt.Errorf("GraphQL error: %v", gqlResp) + } + return nil +} + +type ExecutionContextInfo struct { + ID string `json:"id"` + ProjectID string `json:"projectId"` + ConnectionID string `json:"connectionId"` + DefaultCatalog *string `json:"defaultCatalog"` + DefaultSchema *string `json:"defaultSchema"` +} + +type ExecutionContextListRes struct { + Contexts []ExecutionContextInfo `json:"contexts"` +} + +func (cu *CloudbeaverUsecase) getContextSchema(c echo.Context, connectionId, contextId string) (string, error) { + if contextId == "" { + return "", nil + } + + var cookies []*http.Cookie + for _, cookie := range c.Cookies() { + if cookie.Name == CloudbeaverCookieName { + cookies = append(cookies, cookie) + } + } + + if len(cookies) == 0 { + return "", fmt.Errorf("no cloudbeaver session cookie found") + } + + client := cloudbeaver.NewGraphQlClient(cu.getGraphQLServerURI(), cloudbeaver.WithCookie(cookies)) + client.Log = func(s string) { + cu.log.Debugf("getContextSchema CB GraphQL: %s", s) + } + req := cloudbeaver.NewRequest(cu.graphQl.GetExecutionContextListQuery(), map[string]interface{}{ + "projectId": cloudbeaverProjectId, + "connectionId": connectionId, + "contextId": contextId, + }) + req.SetOperationName("executionContextList") + + var res ExecutionContextListRes + if err := client.Run(c.Request().Context(), req, &res); err != nil { + cu.log.Errorf("query execution context failed: %v, connectionId: %s, contextId: %s", err, connectionId, contextId) + return "", fmt.Errorf("query execution context failed: %v", err) + } + + cu.log.Debugf("execution context response: %+v", res) + + if len(res.Contexts) == 0 { + cu.log.Warnf("no contexts found in response, connectionId: %s, contextId: %s", connectionId, contextId) + return "", nil + } + + contextInfo := res.Contexts[0] + if contextInfo.DefaultCatalog != nil && *contextInfo.DefaultCatalog != "" { + return *contextInfo.DefaultCatalog, nil + } + if contextInfo.DefaultSchema != nil && *contextInfo.DefaultSchema != "" { + return *contextInfo.DefaultSchema, nil + } + + return "", nil +} + +// checkWorkflowPermission 校验用户是否有数据源上的"创建、审批、上线工单"的权限 +// 权限可以是项目级别的(项目管理员)或数据源级别的(直接针对数据源的工单权限) +func (cu *CloudbeaverUsecase) checkWorkflowPermission(ctx context.Context, userUid string, dbService *DBService) (bool, error) { + if userUid == constant.UIDOfUserAdmin { + return true, nil + } + opPermissions, err := cu.opPermissionVerifyUsecase.GetUserOpPermissionInProject(ctx, userUid, dbService.ProjectUID) + if err != nil { + return false, fmt.Errorf("get user op permission in project err: %v", err) + } + + // 需要检查的三个工单权限 + requiredPermissions := map[string]struct{}{ + constant.UIDOfOpPermissionCreateWorkflow: {}, + constant.UIDOfOpPermissionAuditWorkflow: {}, + constant.UIDOfOpPermissionExecuteWorkflow: {}, + } + + // 当前数据源已拥有的工单权限 + dbServicePermissions := make(map[string]struct{}) + + for _, opPermission := range opPermissions { + // 项目管理员权限 + if opPermission.OpRangeType == OpRangeTypeProject && opPermission.OpPermissionUID == constant.UIDOfOpPermissionProjectAdmin { + return true, nil + } + + // 数据源级别的工单权限,只关注当前数据源 + if opPermission.OpRangeType == OpRangeTypeDBService { + // 检查是否是必需的工单权限 + if _, isRequired := requiredPermissions[opPermission.OpPermissionUID]; isRequired { + // 检查是否包含当前数据源 + for _, rangeUid := range opPermission.RangeUIDs { + if rangeUid == dbService.UID { + dbServicePermissions[opPermission.OpPermissionUID] = struct{}{} + // 如果已收集到所有必需的权限,提前返回 + if len(dbServicePermissions) == len(requiredPermissions) { + return true, nil + } + break + } + } + } + } + } + + // 检查是否拥有所有必需的工单权限 + return len(dbServicePermissions) == len(requiredPermissions), nil +} + +// shouldExecuteByWorkflow 判断是否需要通过工单执行(非 DQL 语句) +func (cu *CloudbeaverUsecase) shouldExecuteByWorkflow(dbService *DBService, auditResults []cloudbeaver.AuditSQLResV2) bool { + if !cu.isEnableSQLAudit(dbService) || !cu.isEnableWorkflowExec(dbService) { + return false + } + + for _, result := range auditResults { + if result.SQLType != "" && result.SQLType != "dql" { + return true + } + } + return false +} + +// checkMaintenanceTime 检查运维时间管控(CloudBeaver工作台) +// 返回 blocked=true 表示已构造拦截响应,调用方应立即返回 +func (cu *CloudbeaverUsecase) checkMaintenanceTime(c echo.Context, auditResults []cloudbeaver.AuditSQLResV2, dbService *DBService) (blocked bool, err error) { + if cu.maintenanceTimeUsecase == nil { + return false, fmt.Errorf("maintenance time usecase is nil") + } + + currentUserUid, _ := c.Get(dmsUserIdKey).(string) + if currentUserUid == "" { + return false, fmt.Errorf("current user uid is empty") + } + + sqlTypes := make([]string, 0, len(auditResults)) + for _, r := range auditResults { + sqlTypes = append(sqlTypes, r.SQLType) + } + + var sqlQueryConfig *SQLQueryConfig + if dbService != nil && dbService.SQLEConfig != nil { + sqlQueryConfig = dbService.SQLEConfig.SQLQueryConfig + } + + allowed, message, checkErr := cu.maintenanceTimeUsecase.CheckSQLExecutionAllowed( + c.Request().Context(), + currentUserUid, + sqlTypes, + time.Now(), + sqlQueryConfig, + ) + if checkErr != nil { + cu.log.Errorf("check maintenance time failed: %v", checkErr) + return false, checkErr + } + if !allowed { + return true, c.JSON(http.StatusOK, + newResp(c.Request().Context(), "Maintenance Time Blocked", CBErrorCode, message)) + } + return false, nil +} + +// workflowExecParams 工单执行所需的参数 +type workflowExecParams struct { + contextIdStr string + connectionIdStr string + query string + instanceSchema string +} + +// getWorkflowExecParams 从 GraphQL 参数中提取工单执行所需的参数 +func (cu *CloudbeaverUsecase) getWorkflowExecParams(c echo.Context, params *graphql.RawParams) (*workflowExecParams, error) { + contextIdStr, ok := params.Variables["contextId"].(string) + if !ok { + return nil, fmt.Errorf("missing contextId in params") + } + + connectionIdStr, ok := params.Variables["connectionId"].(string) + if !ok { + return nil, fmt.Errorf("missing connectionId in params") + } + + query, ok := params.Variables["query"].(string) + if !ok { + return nil, fmt.Errorf("missing query in params") + } + + instanceSchema, err := cu.getContextSchema(c, connectionIdStr, contextIdStr) + if err != nil { + return nil, fmt.Errorf("get context schema failed: %v", err) + } + + return &workflowExecParams{ + contextIdStr: contextIdStr, + connectionIdStr: connectionIdStr, + query: query, + instanceSchema: instanceSchema, + }, nil +} + +// executeNonDQLByWorkflow 通过工单执行非 DQL 语句 +func (cu *CloudbeaverUsecase) executeNonDQLByWorkflow(ctx context.Context, c echo.Context, dbService *DBService, params *graphql.RawParams, auditResults cloudbeaver.AuditResults) ([]byte, error) { + // 1. 获取当前用户 ID + currentUserUid, _ := c.Get(dmsUserIdKey).(string) + if currentUserUid == "" { + return nil, c.JSON(http.StatusOK, newResp(ctx, "get dms user id", "failed", "get dms user id failed")) + } + + // 2. 校验工单权限 + hasPermission, err := cu.checkWorkflowPermission(ctx, currentUserUid, dbService) + if err != nil { + return nil, c.JSON(http.StatusOK, newResp(ctx, "check workflow permission", "failed", err.Error())) + } + if !hasPermission { + return nil, c.JSON(http.StatusOK, newResp(ctx, "check workflow permission", "failed", "用户没有数据源上的创建、审批、上线工单权限")) + } + + // 3. 获取项目信息 + project, err := cu.projectUsecase.GetProject(ctx, dbService.ProjectUID) + if err != nil { + return nil, c.JSON(http.StatusOK, newResp(ctx, "get project", "failed", err.Error())) + } + + // 4. 提取工单执行参数 + execParams, err := cu.getWorkflowExecParams(c, params) + if err != nil { + return nil, c.JSON(http.StatusOK, newResp(ctx, "get workflow exec params", "failed", err.Error())) + } + + // 5. 执行工单上线流程 + workflowRes, err := cu.AutoCreateAndExecuteWorkflow(ctx, project.Name, dbService, execParams.query, execParams.instanceSchema) + if err != nil { + err = fmt.Errorf("auto create and execute workflow failed: %w", err) + cu.log.Error(err) + return nil, c.JSON(http.StatusOK, newResp(ctx, "auto create and execute workflow", "failed", err.Error())) + } + cu.log.Infof("auto create and execute workflow, workflow_id: %s, status: %s", workflowRes.Data.WorkflowID, workflowRes.Data.WorkFlowStatus) + + // 6. 判断执行结果 + isExecFailed := !strings.Contains(workflowRes.Data.WorkFlowStatus, "finished") + + // 7. 保存操作日志 + if err := cu.SaveCbOpLogForWorkflow(c, dbService, params, auditResults.Results, auditResults.IsSuccess, workflowRes.Data.WorkflowID, isExecFailed); err != nil { + cu.log.Errorf("save cb operation log for workflow failed: %v", err) + } + + // 8. 返回执行结果 + if isExecFailed { + return nil, c.JSON(http.StatusOK, newResp(ctx, "auto create and execute workflow", "workflow_failed", + fmt.Sprintf("workflow_id:%s, workflow_status:%s", workflowRes.Data.WorkflowID, workflowRes.Data.WorkFlowStatus))) + } + + return nil, c.JSON(http.StatusOK, newResp(ctx, "auto create and execute workflow", "workflow_success", + fmt.Sprintf("workflow_id:%s, workflow_status:%s", workflowRes.Data.WorkflowID, workflowRes.Data.WorkFlowStatus))) +} + +type InstanceForCreatingTask struct { + InstanceName string `json:"instance_name"` + InstanceSchema string `json:"instance_schema"` +} + +type AutoCreateAndExecuteWorkflowReq struct { + Instances []*InstanceForCreatingTask `json:"instances"` + ExecMode string `json:"exec_mode"` + FileOrderMethod string `json:"file_order_method"` + Sql string `json:"sql"` + Subject string `json:"workflow_subject"` + Desc string `json:"desc"` +} + +type AutoCreateAndExecuteWorkflowRes struct { + Code int `json:"code"` + Message string `json:"message"` + Data struct { + WorkflowID string `json:"workflow_id"` + WorkFlowStatus string `json:"workflow_status"` + } `json:"data"` +} + +func (cu *CloudbeaverUsecase) AutoCreateAndExecuteWorkflow(ctx context.Context, projectName string, dbService *DBService, sql string, instanceSchema string) (*AutoCreateAndExecuteWorkflowRes, error) { + sqleUrl, err := cu.getSQLEUrl(ctx) + if err != nil { + return nil, fmt.Errorf("get sqle url failed: %v", err) + } + + project, err := cu.projectUsecase.GetProject(ctx, dbService.ProjectUID) + if err != nil { + return nil, fmt.Errorf("get project failed: %v", err) + } + + if projectName == "" { + projectName = project.Name + } + + instances := []*InstanceForCreatingTask{ + { + InstanceName: dbService.Name, + InstanceSchema: instanceSchema, + }, + } + + req := AutoCreateAndExecuteWorkflowReq{ + Instances: instances, + ExecMode: "sqls", + FileOrderMethod: "", + Sql: sql, + Subject: fmt.Sprintf("工作台工单_%s_%s", dbService.Name, time.Now().Format("20060102150405")), + Desc: "通过工作台执行非DQL类型的SQL时,自动创建的工单", + } + + instancesJSON, err := json.Marshal(req.Instances) + if err != nil { + return nil, fmt.Errorf("marshal instances failed: %v", err) + } + + var requestBody bytes.Buffer + writer := multipart.NewWriter(&requestBody) + + fields := map[string]string{ + "instances": string(instancesJSON), + "exec_mode": req.ExecMode, + "file_order_method": req.FileOrderMethod, + "sql": req.Sql, + "workflow_subject": req.Subject, + "desc": req.Desc, + } + + for key, value := range fields { + if err := writer.WriteField(key, value); err != nil { + writer.Close() + return nil, fmt.Errorf("write field %s failed: %v", key, err) + } + } + + if err := writer.Close(); err != nil { + return nil, fmt.Errorf("close multipart writer failed: %v", err) + } + + url := fmt.Sprintf("%s/v1/projects/%s/workflows/auto_create_and_execute", sqleUrl, projectName) + headers := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + var reply AutoCreateAndExecuteWorkflowRes + if err := pkgHttp.Call(ctx, http.MethodPost, url, headers, writer.FormDataContentType(), requestBody.Bytes(), &reply); err != nil { + return nil, fmt.Errorf("request sqle failed: %v", err) + } + + if reply.Code != 0 { + return nil, fmt.Errorf("sqle returned error code %d: %s", reply.Code, reply.Message) + } + + return &reply, nil +} + +func UnmarshalGraphQLResponseNavNodeChildren(body []byte, resp *cloudbeaver.NavNodeChildrenResponse) error { + var gqlResp GraphQLResponse + if err := json.Unmarshal(body, &gqlResp); err != nil { + return err // 真正 JSON 格式错误时才报错 + } + + if len(gqlResp.Errors) > 0 { + // GraphQL 执行错误 + return fmt.Errorf("GraphQL error: %s", gqlResp.Errors[0].Message) + } + + // 再解析 Data 成真正结构 + if err := json.Unmarshal(body, resp); err != nil { + return err + } + if resp == nil || resp.Data.NavNodeChildren == nil { + return fmt.Errorf("GraphQL error: %v", gqlResp) + } + return nil +} diff --git a/internal/dms/biz/cloudbeaver_ce.go b/internal/dms/biz/cloudbeaver_ce.go new file mode 100644 index 000000000..440b0810d --- /dev/null +++ b/internal/dms/biz/cloudbeaver_ce.go @@ -0,0 +1,36 @@ +//go:build !enterprise + +package biz + +import ( + "bytes" + "context" + + "github.com/99designs/gqlgen/graphql" + "github.com/actiontech/dms/internal/pkg/cloudbeaver" + "github.com/labstack/echo/v4" +) + +func (cu *CloudbeaverUsecase) ResetDbServiceByAuth(ctx context.Context, activeDBServices []*DBService, userId string) ([]*DBService, error) { + return activeDBServices, nil +} + +func (cu *CloudbeaverUsecase) UpdateCbOpResult(c echo.Context, cloudbeaverResBuf *bytes.Buffer, params *graphql.RawParams, ctx context.Context) error { + return nil +} + +func (cu *CloudbeaverUsecase) SaveCbOpLog(c echo.Context, dbService *DBService, params *graphql.RawParams, auditResult []cloudbeaver.AuditSQLResV2, isAuditPass bool, taskID *string) error { + return nil +} + +func (cu *CloudbeaverUsecase) SaveCbOpLogForWorkflow(c echo.Context, dbService *DBService, params *graphql.RawParams, auditResult []cloudbeaver.AuditSQLResV2, isAuditPass bool, workflowID string, isExecFailed bool) error { + return nil +} + +func (cu *CloudbeaverUsecase) SaveUiOp(c echo.Context, buf *bytes.Buffer, params *graphql.RawParams) error { + return nil +} + +func (cu *CloudbeaverUsecase) SaveCbLogSqlAuditNotEnable(c echo.Context, dbService *DBService, params *graphql.RawParams, cloudbeaverResBuf *bytes.Buffer) error { + return nil +} diff --git a/internal/dms/biz/cluster.go b/internal/dms/biz/cluster.go new file mode 100644 index 000000000..50ce4a4a8 --- /dev/null +++ b/internal/dms/biz/cluster.go @@ -0,0 +1,55 @@ +package biz + +import ( + "context" + "time" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +type ClusterRepo interface { + GetClusterLeader(ctx context.Context) (*ClusterLeader, error) + MaintainClusterLeader(ctx context.Context, serverId string) error + GetClusterNodes(ctx context.Context) ([]*ClusterNodeInfo, error) + RegisterClusterNode(ctx context.Context, params *ClusterNodeInfo) error +} + +type ClusterUsecase struct { + tx TransactionGenerator + repo ClusterRepo + log *utilLog.Helper + serverId string + exitCh chan struct{} + doneCh chan struct{} +} + +func NewClusterUsecase(log utilLog.Logger, tx TransactionGenerator, repo ClusterRepo) *ClusterUsecase { + return &ClusterUsecase{ + tx: tx, + repo: repo, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.cluster")), + exitCh: make(chan struct{}), + doneCh: make(chan struct{}), + } +} + +type ClusterLeader struct { + Anchor int `json:"anchor"` + ServerId string `json:"server_id"` + LastSeenTime time.Time `json:"last_seen_time"` +} + +type ClusterNodeInfo struct { + ServerId string `json:"server_id"` + HardwareSign string `json:"hardware_sign"` +} + +var clusterMode bool = false + +type ClusterImpl interface { + Join(serverId string) error + Leave() + IsLeader() bool + IsClusterMode() bool + SetClusterMode(mode bool) +} diff --git a/internal/dms/biz/cluster_ce.go b/internal/dms/biz/cluster_ce.go new file mode 100644 index 000000000..5fb366ada --- /dev/null +++ b/internal/dms/biz/cluster_ce.go @@ -0,0 +1,22 @@ +//go:build !enterprise +// +build !enterprise + +package biz + +func (c *ClusterUsecase) Join(serverId string) error { + return nil +} + +func (c *ClusterUsecase) Leave() { +} + +func (c *ClusterUsecase) IsLeader() bool { + return false +} + +func (c *ClusterUsecase) IsClusterMode() bool { + return false +} + +func (c *ClusterUsecase) SetClusterMode(mode bool) { +} diff --git a/internal/dms/biz/company_notice.go b/internal/dms/biz/company_notice.go new file mode 100644 index 000000000..17a0f4a2a --- /dev/null +++ b/internal/dms/biz/company_notice.go @@ -0,0 +1,52 @@ +package biz + +import ( + "context" + "time" + + pkgRand "github.com/actiontech/dms/pkg/rand" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +type CompanyNotice struct { + Base + + UID string + CreateUserUID string + NoticeStr string + ReadUserIds []string + StartTime *time.Time + EndTime *time.Time +} + +func initCompanyNotice() (*CompanyNotice, error) { + uid, err := pkgRand.GenStrUid() + if err != nil { + return nil, err + } + return &CompanyNotice{ + UID: uid, + }, nil +} + +type CompanyNoticeRepo interface { + UpdateCompanyNotice(ctx context.Context, configuration *CompanyNotice) error + GetCompanyNotice(ctx context.Context) (*CompanyNotice, error) +} + +type CompanyNoticeUsecase struct { + tx TransactionGenerator + repo CompanyNoticeRepo + userUsecase *UserUsecase + log *utilLog.Helper +} + +func NewCompanyNoticeUsecase(log utilLog.Logger, tx TransactionGenerator, repo CompanyNoticeRepo, userUsecase *UserUsecase) *CompanyNoticeUsecase { + return &CompanyNoticeUsecase{ + tx: tx, + repo: repo, + userUsecase: userUsecase, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.company_notice")), + } +} diff --git a/internal/dms/biz/company_notice_ce.go b/internal/dms/biz/company_notice_ce.go new file mode 100644 index 000000000..5cf64618d --- /dev/null +++ b/internal/dms/biz/company_notice_ce.go @@ -0,0 +1,20 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" + "time" +) + +var errNotSupportCompanyNotice = errors.New("company notice related functions are enterprise version functions") + +func (d *CompanyNoticeUsecase) UpdateCompanyNotice(ctx context.Context, currentUserUID string, noticeStr *string, startTime, endTime *time.Time) error { + + return errNotSupportCompanyNotice +} + +func (d *CompanyNoticeUsecase) GetCompanyNotice(ctx context.Context, userId string, includeLatestOutsidePeriod bool) (notice *CompanyNotice, err error) { + return nil, errNotSupportCompanyNotice +} diff --git a/internal/dms/biz/config.go b/internal/dms/biz/config.go index ce182f2ce..87c7646b7 100644 --- a/internal/dms/biz/config.go +++ b/internal/dms/biz/config.go @@ -12,11 +12,12 @@ import ( type DMSConfig struct { Base - UID string `json:"uid"` - NeedInitOpPermissions bool `json:"need_init_op_permissions"` - NeedInitUsers bool `json:"need_init_users"` - NeedInitRoles bool `json:"need_init_roles"` - NeedInitNamespaces bool `json:"need_init_namespaces"` + UID string `json:"uid"` + NeedInitOpPermissions bool `json:"need_init_op_permissions"` + NeedInitUsers bool `json:"need_init_users"` + NeedInitRoles bool `json:"need_init_roles"` + NeedInitProjects bool `json:"need_init_projects"` + EnableSQLResultSetsDataMasking bool `json:"enable_sql_result_sets_data_masking"` } type DMSConfigRepo interface { @@ -40,11 +41,12 @@ func (n *DMSConfigUseCase) GetDMSConfig(ctx context.Context) (*DMSConfig, error) if errors.Is(err, pkgErr.ErrStorageNoData) { // 如果没有找到,则直接初始化 dms := &DMSConfig{ - UID: pkgConst.UIDOfDMSConfig, - NeedInitOpPermissions: true, - NeedInitUsers: true, - NeedInitRoles: true, - NeedInitNamespaces: true, + UID: pkgConst.UIDOfDMSConfig, + NeedInitOpPermissions: true, + NeedInitUsers: true, + NeedInitRoles: true, + NeedInitProjects: true, + EnableSQLResultSetsDataMasking: false, } if err := n.SaveDMSConfig(ctx, dms); nil != err { return nil, err @@ -63,3 +65,11 @@ func (n *DMSConfigUseCase) SaveDMSConfig(ctx context.Context, dmsConfig *DMSConf func (n *DMSConfigUseCase) UpdateDMSConfig(ctx context.Context, dmsConfig *DMSConfig) error { return n.repo.UpdateDMSConfig(ctx, dmsConfig) } + +func (n *DMSConfigUseCase) IsEnableSQLResultsDataMasking(ctx context.Context) (bool, error) { + conf, err := n.GetDMSConfig(ctx) + if nil != err { + return false, err + } + return conf.EnableSQLResultSetsDataMasking, nil +} diff --git a/internal/dms/biz/cron_task.go b/internal/dms/biz/cron_task.go new file mode 100644 index 000000000..0217cb704 --- /dev/null +++ b/internal/dms/biz/cron_task.go @@ -0,0 +1,60 @@ +package biz + +import ( + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "github.com/robfig/cron/v3" +) + +type CronTaskUsecase struct { + log *utilLog.Helper + cronTask *cronTask + workflowUsecase *DataExportWorkflowUsecase + cbOperationLogUsecase *CbOperationLogUsecase + operationRecordUsecase *OperationRecordUsecase + licenseUsecase *LicenseUsecase + oauth2SessionUsecase *OAuth2SessionUsecase +} +type cronTask struct { + cron *cron.Cron +} + +func NewCronTaskUsecase(log utilLog.Logger, wu *DataExportWorkflowUsecase, cu *CbOperationLogUsecase, oru *OperationRecordUsecase, os *OAuth2SessionUsecase) *CronTaskUsecase { + ctu := &CronTaskUsecase{ + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.cronTask")), + cronTask: &cronTask{cron: cron.New()}, + workflowUsecase: wu, + cbOperationLogUsecase: cu, + operationRecordUsecase: oru, + oauth2SessionUsecase: os, + } + return ctu +} + +func (ctu *CronTaskUsecase) InitialTask() error { + if _, err := ctu.cronTask.cron.AddFunc("@daily", ctu.workflowUsecase.RecycleWorkflow); err != nil { + return err + } + + if _, err := ctu.cronTask.cron.AddFunc("@hourly", ctu.workflowUsecase.RecycleDataExportTask); err != nil { + return err + } + + if _, err := ctu.cronTask.cron.AddFunc("@hourly", ctu.workflowUsecase.RecycleDataExportTaskFiles); err != nil { + return err + } + + if _, err := ctu.cronTask.cron.AddFunc("@hourly", ctu.cbOperationLogUsecase.DoClean); err != nil { + return err + } + + if _, err := ctu.cronTask.cron.AddFunc("@hourly", ctu.operationRecordUsecase.DoClean); err != nil { + return err + } + + if _, err := ctu.cronTask.cron.AddFunc("@hourly", ctu.oauth2SessionUsecase.DeleteExpiredSessions); err != nil { + return err + } + + ctu.cronTask.cron.Start() + return nil +} diff --git a/internal/dms/biz/data_export_task.go b/internal/dms/biz/data_export_task.go new file mode 100644 index 000000000..fe52208ad --- /dev/null +++ b/internal/dms/biz/data_export_task.go @@ -0,0 +1,89 @@ +package biz + +import ( + "context" + "time" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/dms/storage/model" +) + +type DataExportTaskStatus string + +// 导出任务状态常量 +const ( + DataExportTaskStatusInit DataExportTaskStatus = "init" + DataExportTaskStatusExporting DataExportTaskStatus = "exporting" + DataExportTaskStatusFinish DataExportTaskStatus = "finish" + DataExportTaskStatusFailed DataExportTaskStatus = "failed" + DataExportTaskStatusFileDelted DataExportTaskStatus = "file_deleted" +) + +func (dets DataExportTaskStatus) String() string { + return string(dets) +} + +type DataExportTask struct { + Base + + UID string + CreateUserUID string + DBServiceUid string + DatabaseName string + WorkFlowRecordUid string + ExportType string + ExportFileType string + ExportFileName string + ExportSQL string + AuditPassRate float64 + AuditScore int32 + AuditLevel string + + ExportStatus DataExportTaskStatus + ExportStartTime *time.Time + ExportEndTime *time.Time + DbService *DBService + + DataExportTaskRecords []*DataExportTaskRecord +} + +func (t *DataExportTask) InstanceName() string { + if t.DbService != nil { + return t.DbService.Name + } + return "" +} + +type DataExportTaskRecord struct { + Number uint + DataExportTaskId string + ExportSQL string + AuditLevel string + ExportResult string + ExportSQLType string + AuditSQLResults model.AuditResults +} + +type ListDataExportTaskRecordOption struct { + PageNumber uint32 + LimitPerPage uint32 + OrderBy DataExportTaskRecordField + FilterByOptions pkgConst.FilterOptions +} +type ListDataExportTaskOption struct { + PageNumber uint32 + LimitPerPage uint32 + OrderBy DataExportTaskField + FilterByOptions pkgConst.FilterOptions +} + +type DataExportTaskRepo interface { + SaveDataExportTask(ctx context.Context, dataExportDataExportTasks []*DataExportTask) error + GetDataExportTaskByIds(ctx context.Context, ids []string) (dataExportDataExportTasks []*DataExportTask, err error) + ListDataExportTaskRecord(ctx context.Context, opt *ListDataExportTaskRecordOption) (dataExportTaskRecords []*DataExportTaskRecord, total int64, err error) + BatchUpdateDataExportTaskStatusByIds(ctx context.Context, ids []string, status DataExportTaskStatus) (err error) + ListDataExportTasks(ctx context.Context, opt *ListDataExportTaskOption) (exportTasks []*DataExportTask, total int64, err error) + DeleteUnusedDataExportTasks(ctx context.Context) error + BatchUpdateDataExportTaskByIds(ctx context.Context, ids []string, args map[string]interface{}) error + SaveDataExportTaskRecords(ctx context.Context, dataExportTaskRecords []*DataExportTaskRecord) error +} diff --git a/internal/dms/biz/data_export_workflow.go b/internal/dms/biz/data_export_workflow.go new file mode 100644 index 000000000..d7486fcce --- /dev/null +++ b/internal/dms/biz/data_export_workflow.go @@ -0,0 +1,166 @@ +package biz + +import ( + "context" + "errors" + "time" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +var ErrDataExportWorkflowNameDuplicate = errors.New("data export workflow name duplicate") + +type DataExportWorkflowStatus string + +const ( + DataExportWorkflowStatusWaitForApprove DataExportWorkflowStatus = "wait_for_approve" + DataExportWorkflowStatusWaitForExport DataExportWorkflowStatus = "wait_for_export" + DataExportWorkflowStatusWaitForExporting DataExportWorkflowStatus = "exporting" + DataExportWorkflowStatusRejected DataExportWorkflowStatus = "rejected" + DataExportWorkflowStatusCancel DataExportWorkflowStatus = "cancel" + DataExportWorkflowStatusFailed DataExportWorkflowStatus = "failed" + DataExportWorkflowStatusFinish DataExportWorkflowStatus = "finish" +) + +func (dews DataExportWorkflowStatus) String() string { + return string(dews) +} + +type EventType string + +const ( + DataExportWorkflowEventType EventType = "data_export" +) + +func (et EventType) String() string { + return string(et) +} + +type DataExportWorkflowEventAction string + +const ( + DataExportWorkflowEventActionCreate DataExportWorkflowEventAction = "create" + DataExportWorkflowEventActionApprove DataExportWorkflowEventAction = "approve" + DataExportWorkflowEventActionReject DataExportWorkflowEventAction = "reject" + DataExportWorkflowEventActionCancel DataExportWorkflowEventAction = "cancel" + DataExportWorkflowEventActionExport DataExportWorkflowEventAction = "export" +) + +func (et DataExportWorkflowEventAction) String() string { + return string(et) +} + +type Workflow struct { + Base + + UID string + Name string + ProjectUID string + WorkflowType string + Desc string + CreateTime time.Time + CreateUserUID string + Status string + WorkflowRecordUid string + Tasks []Task + TaskIds []string + + WorkflowRecord *WorkflowRecord + DBServiceInfos []*dmsCommonV1.DBServiceUidWithNameInfo // 所属数据源信息 + ProjectInfo *dmsCommonV1.ProjectInfo // 所属项目信息 +} + +func (w *Workflow) FinalStep() *WorkflowStep { + return w.WorkflowRecord.WorkflowSteps[len(w.WorkflowRecord.WorkflowSteps)-1] +} + +type Task struct { + UID string +} + +type WorkflowRecord struct { + UID string + Status DataExportWorkflowStatus + Tasks []Task + CurrentWorkflowStepId uint64 + CurrentStep *WorkflowStep + WorkflowSteps []*WorkflowStep +} + +type WorkflowStep struct { + StepId uint64 + WorkflowRecordUid string + OperationUserUid string + OperateAt *time.Time + State string + Reason string + Assignees []string +} + +type WorkflowRepo interface { + SaveWorkflow(ctx context.Context, dataExportWorkflow *Workflow) error + IsDataExportWorkflowNameDuplicate(ctx context.Context, projectUID, workflowName string) (bool, error) + ListDataExportWorkflows(ctx context.Context, opt *ListWorkflowsOption) ([]*Workflow, int64, error) + GetDataExportWorkflow(ctx context.Context, dataExportWorkflowUid string) (*Workflow, error) + UpdateWorkflowStatusById(ctx context.Context, dataExportWorkflowUid string, status DataExportWorkflowStatus) error + GetDataExportWorkflowsByIds(ctx context.Context, dataExportWorkflowUid []string) ([]*Workflow, error) + CancelWorkflow(ctx context.Context, workflowRecordIds []string, workflowSteps []*WorkflowStep, operateId string) error + AuditWorkflow(ctx context.Context, dataExportWorkflowUid string, status DataExportWorkflowStatus, step *WorkflowStep, operateId, reason string) error + AdvanceWorkflowStep(ctx context.Context, dataExportWorkflowUid string, currentStep *WorkflowStep, nextStepId uint64, operateId string) error + GetDataExportWorkflowsForView(ctx context.Context, userUid string) ([]string, error) + GetProjectDataExportWorkflowsForView(ctx context.Context, projectUid string) ([]string, error) + GetDataExportWorkflowsByStatus(ctx context.Context, status string) ([]string, error) + GetDataExportWorkflowsByAssignUser(ctx context.Context, userUid string) ([]string, error) + GetDataExportWorkflowsByDBService(ctx context.Context, dbUid string) ([]string, error) + GetProjectDataExportWorkflowsByDBServices(ctx context.Context, dbUid []string, projectUid string) ([]string, error) + GetDataExportWorkflowsByDBServices(ctx context.Context, dbUid []string) ([]string, error) + DeleteDataExportWorkflowsByIds(ctx context.Context, dataExportWorkflowUid []string) error + GetGlobalWorkflowsByParameterMap(ctx context.Context, data map[string]interface{}) ([]*Workflow, int64, error) +} + +type DataExportWorkflowUsecase struct { + tx TransactionGenerator + repo WorkflowRepo + dbServiceRepo DBServiceRepo + dataExportTaskRepo DataExportTaskRepo + maskingConfigRepo DataExportMaskingConfigRepo + dmsProxyTargetRepo ProxyTargetRepo + opPermissionVerifyUsecase *OpPermissionVerifyUsecase + projectUsecase *ProjectUsecase + clusterUsecase *ClusterUsecase + webhookUsecase *WebHookConfigurationUsecase + userUsecase *UserUsecase + systemVariableUsecase *SystemVariableUsecase + maskingTaskRepo MaskingTaskRepo + log *utilLog.Helper + reportHost string +} + +func NewDataExportWorkflowUsecase(logger utilLog.Logger, tx TransactionGenerator, repo WorkflowRepo, dataExportTaskRepo DataExportTaskRepo, dbServiceRepo DBServiceRepo, maskingConfigRepo DataExportMaskingConfigRepo, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, projectUsecase *ProjectUsecase, proxyTargetRepo ProxyTargetRepo, clusterUseCase *ClusterUsecase, webhookUsecase *WebHookConfigurationUsecase, userUsecase *UserUsecase, systemVariableUsecase *SystemVariableUsecase, maskingTaskRepo MaskingTaskRepo, reportHost string) *DataExportWorkflowUsecase { + return &DataExportWorkflowUsecase{ + tx: tx, + repo: repo, + dbServiceRepo: dbServiceRepo, + maskingConfigRepo: maskingConfigRepo, + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + projectUsecase: projectUsecase, + dmsProxyTargetRepo: proxyTargetRepo, + dataExportTaskRepo: dataExportTaskRepo, + clusterUsecase: clusterUseCase, + webhookUsecase: webhookUsecase, + userUsecase: userUsecase, + systemVariableUsecase: systemVariableUsecase, + maskingTaskRepo: maskingTaskRepo, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.dataExportWorkflow")), + reportHost: reportHost, + } +} + +type ListWorkflowsOption struct { + PageNumber uint32 + LimitPerPage uint32 + OrderBy WorkflowField + FilterByOptions pkgConst.FilterOptions +} diff --git a/internal/dms/biz/data_export_workflow_ce.go b/internal/dms/biz/data_export_workflow_ce.go new file mode 100644 index 000000000..181b39540 --- /dev/null +++ b/internal/dms/biz/data_export_workflow_ce.go @@ -0,0 +1,67 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" +) + +var errNotDataExportWorkflow = errors.New("data export workflow related functions are enterprise version functions") +var errNotDataExportTask = errors.New("data export task related functions are enterprise version functions") + +func (d *DataExportWorkflowUsecase) AddDataExportWorkflow(ctx context.Context, currentUserId string, params *Workflow) (string, error) { + return "", errNotDataExportWorkflow +} +func (d *DataExportWorkflowUsecase) ListDataExportWorkflows(ctx context.Context, workflowsOption *ListWorkflowsOption, currentUserId, dbServiceUID, filterCurrentStepAssigneeUserUid, filterByStatus string, projectUid string) ([]*Workflow, int64, error) { + return nil, 0, errNotDataExportWorkflow +} + +func (d *DataExportWorkflowUsecase) GetDataExportWorkflow(ctx context.Context, workflowUid, currentUserId string) (*Workflow, error) { + return nil, errNotDataExportWorkflow +} + +func (d *DataExportWorkflowUsecase) ApproveDataExportWorkflow(ctx context.Context, projectId, workflowId, userId string) error { + return errNotDataExportWorkflow +} + +func (d *DataExportWorkflowUsecase) RejectDataExportWorkflow(ctx context.Context, req *dmsV1.RejectDataExportWorkflowReq, userId string) error { + return errNotDataExportWorkflow +} + +func (d *DataExportWorkflowUsecase) CancelDataExportWorkflow(ctx context.Context, userId string, req *dmsV1.CancelDataExportWorkflowReq) error { + return errNotDataExportWorkflow +} + +func (d *DataExportWorkflowUsecase) ExportDataExportWorkflow(ctx context.Context, projectUid, dataExportWorkflowUid, currentUserUid string) error { + return errNotDataExportWorkflow +} + +func (d *DataExportWorkflowUsecase) DownloadDataExportTask(ctx context.Context, userId string, req *dmsV1.DownloadDataExportTaskReq) (bool, string, error) { + return false, "", errNotDataExportTask +} + +func (d *DataExportWorkflowUsecase) AddDataExportTasks(ctx context.Context, projectUid, currentUserId string, params []*DataExportTask) (taskids []string, err error) { + return nil, errNotDataExportTask +} + +func (d *DataExportWorkflowUsecase) BatchGetDataExportTask(ctx context.Context, taskUids []string) ([]*DataExportTask, error) { + return nil, errNotDataExportTask +} + +func (d *DataExportWorkflowUsecase) ListDataExportTaskRecords(ctx context.Context, options *ListDataExportTaskRecordOption, currentUserId string) ([]*DataExportTaskRecord, int64, error) { + return nil, 0, errNotDataExportTask +} +func (d *DataExportWorkflowUsecase) DownloadDataExportTaskSQLs(ctx context.Context, req *dmsV1.DownloadDataExportTaskSQLsReq, userId string) (string, []byte, error) { + return "", nil, errNotDataExportTask +} + +func (d *DataExportWorkflowUsecase) RecycleWorkflow() {} +func (d *DataExportWorkflowUsecase) RecycleDataExportTask() {} +func (d *DataExportWorkflowUsecase) RecycleDataExportTaskFiles() {} + +func (d *DataExportWorkflowUsecase) GetGlobalWorkflowsList(ctx context.Context, req *dmsV1.FilterGlobalDataExportWorkflowReq, limit, offset int) ([]*Workflow, int64, error) { + return nil, 0, errNotDataExportWorkflow +} diff --git a/internal/dms/biz/data_mask_ce.go b/internal/dms/biz/data_mask_ce.go new file mode 100644 index 000000000..c9c5492d8 --- /dev/null +++ b/internal/dms/biz/data_mask_ce.go @@ -0,0 +1,5 @@ +//go:build !enterprise + +package biz + +type DataExportMaskingConfigRepo interface{} diff --git a/internal/dms/biz/db_service.go b/internal/dms/biz/db_service.go index 575564317..782a56d3e 100644 --- a/internal/dms/biz/db_service.go +++ b/internal/dms/biz/db_service.go @@ -3,46 +3,88 @@ package biz import ( "context" "fmt" + "sync" + "time" + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" - "github.com/actiontech/dms/internal/dms/pkg/database" + "github.com/actiontech/dms/internal/pkg/locale" + v1Base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + "github.com/actiontech/dms/pkg/dms-common/pkg/config" + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" pkgParams "github.com/actiontech/dms/pkg/params" pkgPeriods "github.com/actiontech/dms/pkg/periods" pkgRand "github.com/actiontech/dms/pkg/rand" + "github.com/go-openapi/strfmt" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" "github.com/actiontech/dms/pkg/dms-common/pkg/aes" ) type SQLEConfig struct { + // DB Service audit enabled + AuditEnabled bool `json:"audit_enabled"` // DB Service rule template name RuleTemplateName string `json:"rule_template_name"` // DB Service rule template id RuleTemplateID string `json:"rule_template_id"` + // DB Service data export rule template name + DataExportRuleTemplateName string `json:"data_export_rule_template_name"` + // DB Service data export rule template id + DataExportRuleTemplateID string `json:"data_export_rule_template_id"` // DB Service SQL query config SQLQueryConfig *SQLQueryConfig `json:"sql_query_config"` } +type LastConnectionStatus string + +const ( + LastConnectionStatusSuccess LastConnectionStatus = "connect_success" + LastConnectionStatusFailed LastConnectionStatus = "connect_failed" +) + // 数据源 type DBService struct { Base - UID string - Name string - Desc string - DBType pkgConst.DBType - Host string - Port string - AdminUser string - AdminPassword string - EncryptedAdminPassword string - Business string - AdditionalParams pkgParams.Params - NamespaceUID string - MaintenancePeriod pkgPeriods.Periods - Source string + UID string `json:"uid"` + Name string `json:"name"` + Desc string `json:"desc"` + DBType string `json:"db_type"` + Host string `json:"host"` + Port string `json:"port"` + User string `json:"user"` + Password string `json:"password"` + EnvironmentTag *dmsCommonV1.EnvironmentTag `json:"environment_tag"` + AdditionalParams pkgParams.Params `json:"additional_params"` + ProjectUID string `json:"project_uid"` + MaintenancePeriod pkgPeriods.Periods `json:"maintenance_period"` + Source string `json:"source"` + + // db service connection + LastConnectionStatus *LastConnectionStatus `json:"last_connection_status"` + LastConnectionTime *time.Time `json:"last_connection_time"` + LastConnectionErrorMsg *string `json:"last_connection_error_msg"` // sqle config - SQLEConfig *SQLEConfig + SQLEConfig *SQLEConfig `json:"sqle_config"` + // PROV config + AccountPurpose string `json:"account_purpose"` + // audit plan types + AuditPlanTypes []*dmsCommonV1.AuditPlanTypes `json:"audit_plan_types"` + // instance audit plan id + InstanceAuditPlanID uint `json:"instance_audit_plan_id"` + EnableBackup bool `json:"enable_backup"` + BackupMaxRows uint64 `json:"backup_max_rows"` +} + +type DBTypeCount struct { + DBType string `json:"db_type"` + Count int64 `json:"count"` } func (d *DBService) GetUID() string { @@ -58,6 +100,13 @@ func (d *DBService) GetRuleTemplateName() string { return "" } +func (d *DBService) GetAllowQueryWhenLessThanAuditLevel() string { + if d.SQLEConfig == nil || d.SQLEConfig.SQLQueryConfig == nil { + return "" + } + return d.SQLEConfig.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel +} + const ( DBServiceAdditionalParam_RuleTemplateName = "rule_template_name" ) @@ -75,86 +124,132 @@ func newDBService(args *BizDBServiceArgs) (*DBService, error) { DBType: args.DBType, Host: args.Host, Port: args.Port, - AdminUser: args.AdminUser, - AdminPassword: *args.AdminPassword, + User: args.User, + Password: *args.Password, AdditionalParams: args.AdditionalParams, - NamespaceUID: args.NamespaceUID, - Business: args.Business, + ProjectUID: args.ProjectUID, + Source: args.Source, MaintenancePeriod: args.MaintenancePeriod, + SQLEConfig: &SQLEConfig{}, + EnableBackup: args.EnableBackup, + BackupMaxRows: args.BackupMaxRows, + } + + if args.AuditEnabled { + dbService.SQLEConfig.AuditEnabled = args.AuditEnabled + dbService.SQLEConfig.RuleTemplateID = args.RuleTemplateID + dbService.SQLEConfig.RuleTemplateName = args.RuleTemplateName + dbService.SQLEConfig.DataExportRuleTemplateName = args.DataExportRuleTemplateName + dbService.SQLEConfig.DataExportRuleTemplateID = args.DataExportRuleTemplateID } - if args.SQLQueryConfig != nil && args.RuleTemplateName != "" { - dbService.SQLEConfig = &SQLEConfig{ - SQLQueryConfig: args.SQLQueryConfig, - RuleTemplateName: args.RuleTemplateName, - RuleTemplateID: args.RuleTemplateID, + if args.EnvironmentTagUID != "" { + dbService.EnvironmentTag = &dmsCommonV1.EnvironmentTag{ + UID: args.EnvironmentTagUID, } } + + if args.SQLQueryConfig != nil { + dbService.SQLEConfig.SQLQueryConfig = args.SQLQueryConfig + } + return dbService, nil } type AdditionalParams pkgParams.Param type DBServiceRepo interface { - SaveDBService(ctx context.Context, dbService *DBService) error + SaveDBServices(ctx context.Context, dbService []*DBService) error GetDBServicesByIds(ctx context.Context, dbServiceIds []string) (services []*DBService, err error) ListDBServices(ctx context.Context, opt *ListDBServicesOption) (services []*DBService, total int64, err error) DelDBService(ctx context.Context, dbServiceUid string) error GetDBService(ctx context.Context, dbServiceUid string) (*DBService, error) + GetDBServices(ctx context.Context, conditions []pkgConst.FilterCondition) (services []*DBService, err error) CheckDBServiceExist(ctx context.Context, dbServiceUids []string) (exists bool, err error) UpdateDBService(ctx context.Context, dbService *DBService) error + CountDBService(ctx context.Context) ([]DBTypeCount, error) + GetBusinessByProjectUID(ctx context.Context, projectUid string) ([]string, error) + GetFieldDistinctValue(ctx context.Context, field DBServiceField, results interface{}) error +} + +type MaskingTaskRepo interface { + CheckMaskingTaskExist(ctx context.Context, dbServiceUID string) (bool, error) + ListMaskingTaskStatus(ctx context.Context, dbServiceUIDs []string) (map[string]bool, error) } type DBServiceUsecase struct { repo DBServiceRepo + maskingTaskRepo MaskingTaskRepo + dmsProxyTargetRepo ProxyTargetRepo pluginUsecase *PluginUsecase opPermissionVerifyUsecase *OpPermissionVerifyUsecase - namespaceUsecase *NamespaceUsecase + projectUsecase *ProjectUsecase + environmentTagUsecase *EnvironmentTagUsecase + log *utilLog.Helper } -func NewDBServiceUsecase(repo DBServiceRepo, pluginUsecase *PluginUsecase, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, namespaceUsecase *NamespaceUsecase) *DBServiceUsecase { +func NewDBServiceUsecase(log utilLog.Logger, repo DBServiceRepo, maskingTaskRepo MaskingTaskRepo, pluginUsecase *PluginUsecase, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, + projectUsecase *ProjectUsecase, proxyTargetRepo ProxyTargetRepo, environmentTagUsecase *EnvironmentTagUsecase) *DBServiceUsecase { return &DBServiceUsecase{ repo: repo, + maskingTaskRepo: maskingTaskRepo, opPermissionVerifyUsecase: opPermissionVerifyUsecase, pluginUsecase: pluginUsecase, - namespaceUsecase: namespaceUsecase, + projectUsecase: projectUsecase, + dmsProxyTargetRepo: proxyTargetRepo, + environmentTagUsecase: environmentTagUsecase, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.dbService")), } } type BizDBServiceArgs struct { - Name string - Desc *string - DBType pkgConst.DBType - Host string - Port string - AdminUser string - AdminPassword *string - Business string - AdditionalParams pkgParams.Params - NamespaceUID string - MaintenancePeriod pkgPeriods.Periods + Name string + Desc *string + DBType string + Host string + Port string + User string + Password *string + EnvironmentTagUID string + EnvironmentTagName string + Source string + AdditionalParams pkgParams.Params + ProjectUID string + MaintenancePeriod pkgPeriods.Periods // sqle config - RuleTemplateName string - RuleTemplateID string - SQLQueryConfig *SQLQueryConfig + AuditEnabled bool + RuleTemplateName string + RuleTemplateID string + DataExportRuleTemplateName string + DataExportRuleTemplateID string + SQLQueryConfig *SQLQueryConfig + EnableBackup bool + BackupMaxRows uint64 } type SQLQueryConfig struct { - MaxPreQueryRows int `json:"max_pre_query_rows"` - QueryTimeoutSecond int `json:"query_timeout_second"` - AuditEnabled bool `json:"audit_enabled"` - AllowQueryWhenLessThanAuditLevel string `json:"allow_query_when_less_than_audit_level"` + MaxPreQueryRows int `json:"max_pre_query_rows"` + QueryTimeoutSecond int `json:"query_timeout_second"` + AuditEnabled bool `json:"audit_enabled"` + WorkflowExecEnabled bool `json:"workflow_exec_enabled"` + AllowQueryWhenLessThanAuditLevel string `json:"allow_query_when_less_than_audit_level"` + RuleTemplateID string `json:"rule_template_id"` + RuleTemplateName string `json:"rule_template_name"` + MaintenancePeriods pkgPeriods.Periods `json:"maintenance_periods"` } func (d *DBServiceUsecase) CreateDBService(ctx context.Context, args *BizDBServiceArgs, currentUserUid string) (uid string, err error) { - // 检查空间是否归档/删除 - if err := d.namespaceUsecase.isNamespaceActive(ctx, args.NamespaceUID); err != nil { + // 检查项目是否归档/删除 + if err := d.projectUsecase.isProjectActive(ctx, args.ProjectUID); err != nil { return "", fmt.Errorf("create db service error: %v", err) } - // 检查当前用户有空间管理员权限 - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, currentUserUid, args.NamespaceUID); err != nil { - return "", fmt.Errorf("check user is namespace admin failed: %v", err) - } else if !isAdmin { - return "", fmt.Errorf("user is not namespace admin") + // 检查当前用户有项目管理员权限或者数据源管理权限 + hasPermission, err := d.opPermissionVerifyUsecase.HasManagePermission(ctx, currentUserUid, args.ProjectUID, pkgConst.UIdOfOpPermissionManageProjectDataSource) + if err != nil { + return "", fmt.Errorf("check user has permission manageDataSource: %v", err) + } + + if !hasPermission { + return "", fmt.Errorf("user is not admin or data source management permission") } ds, err := newDBService(args) @@ -162,38 +257,280 @@ func (d *DBServiceUsecase) CreateDBService(ctx context.Context, args *BizDBServi return "", fmt.Errorf("new db service failed: %w", err) } + err = d.createDBService(ctx, ds) + if err != nil { + return "", err + } + return ds.UID, nil +} + +func (d *DBServiceUsecase) createDBService(ctx context.Context, dbService *DBService) error { + // 数据源名称格式校验,命名不规范会造成的问题:https://github.com/actiontech/sqle/issues/2810 + if !config.DbNameFormatPattern.MatchString(dbService.Name) { + return fmt.Errorf("db service name %s is not valid", dbService.Name) + } + // 调用其他服务对数据源进行预检查 - if err := d.pluginUsecase.AddDBServicePreCheck(ctx, ds); err != nil { - return "", fmt.Errorf("precheck db service failed: %w", err) + if err := d.pluginUsecase.AddDBServicePreCheck(ctx, dbService); err != nil { + return fmt.Errorf("precheck db service failed: %w", err) } - return ds.UID, d.repo.SaveDBService(ctx, ds) + if err := d.repo.SaveDBServices(ctx, []*DBService{dbService}); err != nil { + return err + } + + err := d.pluginUsecase.AddDBServiceAfterHandle(ctx, dbService.UID) + if err != nil { + return fmt.Errorf("plugin handle after craete db_service err: %v", err) + } + return nil } type ListDBServicesOption struct { - PageNumber uint32 - LimitPerPage uint32 - OrderBy DBServiceField - FilterBy []pkgConst.FilterCondition -} - -func (d *DBServiceUsecase) ListDBService(ctx context.Context, option *ListDBServicesOption, namespaceUid, currentUserUid string) (dbServices []*DBService, total int64, err error) { - // 只允许系统用户查询所有数据源,同步数据到其他服务(provision) - // 检查空间是否归档/删除 - if namespaceUid != "" { - if err := d.namespaceUsecase.isNamespaceActive(ctx, namespaceUid); err != nil { - return nil, 0, fmt.Errorf("list db service error: %v", err) - } - } else if currentUserUid != pkgConst.UIDOfUserSys { - return nil, 0, fmt.Errorf("list db service error: namespace is empty") - } + PageNumber uint32 + LimitPerPage uint32 + OrderBy DBServiceField + FilterByOptions pkgConst.FilterOptions +} + +func (d *DBServiceUsecase) ListDBService(ctx context.Context, option *ListDBServicesOption, projectUid, currentUserUid string) (dbServices []*DBService, total int64, err error) { services, total, err := d.repo.ListDBServices(ctx, option) if err != nil { return nil, 0, fmt.Errorf("list db services failed: %w", err) } + // 只允许系统用户和平台管理/查看权限用户查询所有数据源,同步数据到其他服务(provision) + if projectUid == "" { + canViewProject, err := d.opPermissionVerifyUsecase.CanViewProject(ctx, currentUserUid, projectUid, pkgConst.UIdOfOpPermissionManageProjectDataSource) + if err != nil { + return nil, 0, err + } + + if !(currentUserUid == pkgConst.UIDOfUserSys || canViewProject) { + return nil, 0, fmt.Errorf("user is not sys user or global management or view permission user") + } + } else { + err = d.AddInstanceAuditPlanForDBServiceFromSqle(ctx, projectUid, services) + if err != nil { + d.log.Warn("get instance audit Plan from sqle: %w", err) + } + } + return services, total, nil } +func (d *DBServiceUsecase) TestDbServiceConnections(ctx context.Context, DBServiceList []*DBService, currentUserUid string) []dmsV1.DBServiceIsConnectableReply { + connectionResp := make([]dmsV1.DBServiceIsConnectableReply, len(DBServiceList)) + concurrencyLimit := make(chan int, 3) + var wg sync.WaitGroup + var respMu sync.Mutex + + for i, dbService := range DBServiceList { + wg.Add(1) + + go func(dbService *DBService, index int) { + defer func() { + if r := recover(); r != nil { + d.log.Errorf("CheckDBServiceIsConnectableByIds panic: %v", r) + } + }() + defer wg.Done() + + if dbService == nil { + return + } + + concurrencyLimit <- 1 + + connectionResult, err := d.TestDbServiceConnection(ctx, dbService) + if err != nil { + d.log.Errorf("db connectionResult uid: %v,TestDBServiceConnection err: %v", connectionResult.DBServiceUid, err) + } + + dbService.LastConnectionStatus = &connectionResult.ConnectionStatus + dbService.LastConnectionTime = &connectionResult.TestConnectionTime + dbService.LastConnectionErrorMsg = &connectionResult.ConnectErrorMessage + + err = d.UpdateDBService(ctx, dbService, currentUserUid) + if err != nil { + d.log.Errorf("dbService name: %v,UpdateDBServiceByBiz err: %v", dbService.Name, err) + } + + respMu.Lock() + connectionResp[index] = dmsV1.DBServiceIsConnectableReply{ + DBServiceUid: connectionResult.DBServiceUid, + ConnectionStatus: dmsCommonV1.LastConnectionTestStatus(connectionResult.ConnectionStatus), + TestConnectionTime: strfmt.DateTime(connectionResult.TestConnectionTime), + ConnectErrorMessage: connectionResult.ConnectErrorMessage, + } + respMu.Unlock() + + <-concurrencyLimit + }(dbService, i) + } + + wg.Wait() + + return connectionResp +} + +type instanceAuditPlanReply struct { + Code int `json:"code" example:"0"` + Message string `json:"message" example:"ok"` + Data []InstanceAuditPlan `json:"data"` +} + +type InstanceAuditPlan struct { + InstanceAuditPlanId uint `json:"instance_audit_plan_id"` + InstanceName string `json:"instance_name"` + Business string `json:"business"` + InstanceType string `json:"instance_type"` + AuditPlanTypes []*dmsCommonV1.AuditPlanTypes `json:"audit_plan_types"` +} + +// TODO 临时实现, 当前请求获取扫描任务的url和参数写死 +func (d *DBServiceUsecase) AddInstanceAuditPlanForDBServiceFromSqle(ctx context.Context, projectUid string, dbServices []*DBService) error { + project, err := d.projectUsecase.GetProject(ctx, projectUid) + if err != nil { + return fmt.Errorf("get project failed: %v", err) + } + target, err := d.dmsProxyTargetRepo.GetProxyTargetByName(ctx, _const.SqleComponentName) + if err != nil { + return fmt.Errorf("get proxy target by name failed: %v", err) + } + sqleAddr := fmt.Sprintf("%s/v2/projects/%s/instance_audit_plans", target.URL.String(), project.Name) + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + i18nPkg.AcceptLanguageKey: locale.Bundle.GetLangTagFromCtx(ctx).String(), + } + reqBody := struct { + PageIndex uint32 `json:"page_index"` + PageSize uint32 `json:"page_size"` + }{ + PageIndex: 1, + PageSize: 999, + } + reply := &instanceAuditPlanReply{} + if err = pkgHttp.Get(ctx, sqleAddr, header, reqBody, reply); err != nil { + return fmt.Errorf("get instance audit plan from sqle failed: %v", err) + } + if reply.Code != 0 { + return fmt.Errorf("get instance audit plan from sqle reply code(%v) error: %v", reply.Code, reply.Message) + } + + for _, dbService := range dbServices { + for _, instAuditPlan := range reply.Data { + if dbService.Name == instAuditPlan.InstanceName && dbService.DBType == instAuditPlan.InstanceType { + dbService.InstanceAuditPlanID = instAuditPlan.InstanceAuditPlanId + dbService.AuditPlanTypes = instAuditPlan.AuditPlanTypes + } + } + } + return nil +} + +func (d *DBServiceUsecase) ListDBServiceTips(ctx context.Context, req *dmsV1.ListDBServiceTipsReq, userId string) ([]*DBService, error) { + conditions := []pkgConst.FilterCondition{ + { + Field: string(DBServiceFieldProjectUID), + Operator: pkgConst.FilterOperatorEqual, + Value: req.ProjectUid, + }, + } + + if req.FilterDBType != "" { + conditions = append(conditions, pkgConst.FilterCondition{ + Field: string(DBServiceFieldDBType), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterDBType, + }) + } + + dbServices, err := d.repo.GetDBServices(ctx, conditions) + if err != nil { + return nil, fmt.Errorf("list db service tips failed: %w", err) + } + + if req.FunctionalModule == "" { + return dbServices, nil + } + dbServices = filterExportSupportedDb(dbServices, dmsCommonV1.OpPermissionType(req.FunctionalModule)) + isAdmin, err := d.opPermissionVerifyUsecase.CanViewProject(ctx, userId, req.ProjectUid, "") + if err != nil { + return nil, fmt.Errorf("check user is project admin or golobal view permission failed: %v", err) + } + + if isAdmin { + return dbServices, nil + } + + permissions, err := d.opPermissionVerifyUsecase.GetUserOpPermissionInProject(ctx, userId, req.ProjectUid) + if err != nil { + return nil, err + } + + ret := make([]*DBService, 0) + for _, item := range dbServices { + permissionId, err := pkgConst.ConvertPermissionTypeToId(dmsCommonV1.OpPermissionType(req.FunctionalModule)) + if err != nil { + return nil, err + } + + if d.opPermissionVerifyUsecase.UserCanOpDB(permissions, []string{permissionId}, item.UID) { + ret = append(ret, item) + } + } + + return ret, nil +} + +func filterExportSupportedDb(dbServices []*DBService, opPermissionType dmsCommonV1.OpPermissionType) []*DBService { + if opPermissionType != dmsCommonV1.OpPermissionTypeExportCreate { + return dbServices + } + ret := make([]*DBService, 0) + for _, item := range dbServices { + if pkgConst.CheckDBTypeIfDataExportSupported(item.DBType) { + ret = append(ret, item) + } + } + return ret +} + +func (d *DBServiceUsecase) ListDBServiceDriverOption(ctx context.Context) ([]*dmsV1.DatabaseDriverOption, error) { + options, err := d.pluginUsecase.GetDatabaseDriverOptionsCache(ctx) + if err != nil { + return nil, err + } + return options, nil +} + +func (d *DBServiceUsecase) GetDriverParamsByDBType(ctx context.Context, dbType string) (pkgParams.Params, error) { + databaseOptions, err := d.ListDBServiceDriverOption(ctx) + if err != nil { + return nil, err + } + for _, driverOptions := range databaseOptions { + if driverOptions.DBType == dbType { + return convertAdditionParamsToParams(driverOptions.Params), nil + } + + } + return nil, fmt.Errorf("db type %v is not support", dbType) +} + +func convertAdditionParamsToParams(additionalParam []*dmsV1.DatabaseDriverAdditionalParam) pkgParams.Params { + params := make(pkgParams.Params, len(additionalParam)) + for i, item := range additionalParam { + params[i] = &pkgParams.Param{ + Key: item.Name, + Value: item.Value, + Desc: item.Description, + Type: pkgParams.ParamType(item.Type), + } + } + return params +} + func (d *DBServiceUsecase) GetActiveDBServices(ctx context.Context, dbServiceIds []string) (dbServices []*DBService, err error) { services, err := d.repo.GetDBServicesByIds(ctx, dbServiceIds) if err != nil { @@ -201,7 +538,7 @@ func (d *DBServiceUsecase) GetActiveDBServices(ctx context.Context, dbServiceIds } for _, service := range services { - if err = d.namespaceUsecase.isNamespaceActive(ctx, service.NamespaceUID); err == nil { + if err = d.projectUsecase.isProjectActive(ctx, service.ProjectUID); err == nil { dbServices = append(dbServices, service) } } @@ -219,7 +556,7 @@ func (d *DBServiceUsecase) GetDBServiceFingerprint(dbService *DBService) string "password":"%s", "params":"%v" } -`, dbService.UID, dbService.Host, dbService.Port, dbService.AdminUser, aes.Md5(dbService.AdminPassword), dbService.AdditionalParams) +`, dbService.UID, dbService.Host, dbService.Port, dbService.User, aes.Md5(dbService.Password), dbService.AdditionalParams) } func (d *DBServiceUsecase) DelDBService(ctx context.Context, dbServiceUid, currentUserUid string) (err error) { @@ -227,25 +564,30 @@ func (d *DBServiceUsecase) DelDBService(ctx context.Context, dbServiceUid, curre if err != nil { return fmt.Errorf("get db service failed: %v", err) } - // 检查空间是否归档/删除 - if err := d.namespaceUsecase.isNamespaceActive(ctx, ds.NamespaceUID); err != nil { + // 检查项目是否归档/删除 + if err := d.projectUsecase.isProjectActive(ctx, ds.ProjectUID); err != nil { return fmt.Errorf("delete db service error: %v", err) } - // 检查当前用户有空间管理员权限 - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, currentUserUid, ds.NamespaceUID); err != nil { - return fmt.Errorf("check user is namespace admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not namespace admin") + if canOpProject, err := d.opPermissionVerifyUsecase.HasManagePermission(ctx, currentUserUid, ds.ProjectUID, pkgConst.UIdOfOpPermissionManageProjectDataSource); err != nil { + return fmt.Errorf("check user is project admin or golobal op permission failed: %v", err) + } else if !canOpProject { + return fmt.Errorf("user is not project admin or golobal op permission user") } - // 调用其他服务对数据源进行预检查 - if err := d.pluginUsecase.DelDBServicePreCheck(ctx, ds.GetUID()); err != nil { - return fmt.Errorf("precheck del db service failed: %v", err) + err = d.pluginUsecase.DelDBServicePreCheck(ctx, ds.UID) + if err != nil { + return fmt.Errorf("plugin handle before delete db_service err: %v", err) } if err := d.repo.DelDBService(ctx, dbServiceUid); nil != err { return fmt.Errorf("delete data service error: %v", err) } + + err = d.pluginUsecase.DelDBServiceAfterHandle(ctx, ds.UID) + if err != nil { + return fmt.Errorf("plugin handle after delete db_service err: %v", err) + } + return nil } @@ -257,20 +599,98 @@ func (d *DBServiceUsecase) GetDBService(ctx context.Context, dbServiceUid string return d.repo.GetDBService(ctx, dbServiceUid) } -func (d *DBServiceUsecase) UpdateDBService(ctx context.Context, dbServiceUid string, updateDBService *BizDBServiceArgs, currentUserUid string) (err error) { +type TestDbServiceConnectionResult struct { + DBServiceUid string + ConnectionStatus LastConnectionStatus + TestConnectionTime time.Time + ConnectErrorMessage string +} + +func (d *DBServiceUsecase) TestDbServiceConnection(ctx context.Context, dbService *DBService) (TestDbServiceConnectionResult, error) { + connectionResult := TestDbServiceConnectionResult{ + DBServiceUid: dbService.UID, + TestConnectionTime: time.Now(), + ConnectionStatus: LastConnectionStatusSuccess, + } + + var additionParams []*dmsCommonV1.AdditionalParam + for _, item := range dbService.AdditionalParams { + additionParams = append(additionParams, &dmsCommonV1.AdditionalParam{ + Name: item.Key, + Value: item.Value, + }) + } + + checkDbConnectableParams := dmsCommonV1.CheckDbConnectable{ + DBType: dbService.DBType, + User: dbService.User, + Host: dbService.Host, + Port: dbService.Port, + Password: dbService.Password, + AdditionalParams: additionParams, + } + + connectable, err := d.IsConnectable(ctx, checkDbConnectableParams) + if err != nil { + connectionResult.ConnectionStatus = LastConnectionStatusFailed + connectionResult.ConnectErrorMessage = err.Error() + return connectionResult, err + } + + if len(connectable) == 0 { + connectionResult.ConnectionStatus = LastConnectionStatusFailed + connectionResult.ConnectErrorMessage = "check db connectable failed" + } else { + for _, c := range connectable { + if !c.IsConnectable { + connectionResult.ConnectionStatus = LastConnectionStatusFailed + connectionResult.ConnectErrorMessage = c.ConnectErrorMessage + break + } + } + } + + return connectionResult, nil +} + +func (d *DBServiceUsecase) UpdateDBService(ctx context.Context, ds *DBService, currentUserUid string) (err error) { + // 检查项目是否归档/删除 + if err := d.projectUsecase.isProjectActive(ctx, ds.ProjectUID); err != nil { + return fmt.Errorf("update db service error: %v", err) + } + + if canOpProject, err := d.opPermissionVerifyUsecase.HasManagePermission(ctx, currentUserUid, ds.ProjectUID, pkgConst.UIdOfOpPermissionManageProjectDataSource); err != nil { + return fmt.Errorf("check user has update data source op permission failed: %v", err) + } else if !canOpProject { + return fmt.Errorf("user has no update data source permission") + } + + if err := d.repo.UpdateDBService(ctx, ds); nil != err { + return fmt.Errorf("update db service error: %v", err) + } + + err = d.pluginUsecase.UpdateDBServiceAfterHandle(ctx, ds.UID) + if err != nil { + return fmt.Errorf("plugin handle after update db_service err: %v", err) + } + + return nil +} + +func (d *DBServiceUsecase) UpdateDBServiceByArgs(ctx context.Context, dbServiceUid string, updateDBService *BizDBServiceArgs, currentUserUid string) (err error) { ds, err := d.repo.GetDBService(ctx, dbServiceUid) if err != nil { return fmt.Errorf("get db service failed: %v", err) } - // 检查空间是否归档/删除 - if err := d.namespaceUsecase.isNamespaceActive(ctx, ds.NamespaceUID); err != nil { + // 检查项目是否归档/删除 + if err := d.projectUsecase.isProjectActive(ctx, ds.ProjectUID); err != nil { return fmt.Errorf("update db service error: %v", err) } - // 检查当前用户有空间管理员权限 - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, currentUserUid, ds.NamespaceUID); err != nil { - return fmt.Errorf("check user is namespace admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not namespace admin") + // 检查当前用户有项目管理员权限 + if canOpProject, err := d.opPermissionVerifyUsecase.HasManagePermission(ctx, currentUserUid, ds.ProjectUID, pkgConst.UIdOfOpPermissionManageProjectDataSource); err != nil { + return fmt.Errorf("check user is project admin or golobal op permission failed: %v", err) + } else if !canOpProject { + return fmt.Errorf("user is not project admin or golobal op permission user") } // check @@ -278,17 +698,14 @@ func (d *DBServiceUsecase) UpdateDBService(ctx context.Context, dbServiceUid str if ds.DBType != updateDBService.DBType { return fmt.Errorf("update db service db type is unsupported") } - source, err := pkgConst.ParseDBServiceSource(ds.Source) - if err != nil { - return fmt.Errorf("parse db service source failed: %v", err) - } - if source != pkgConst.DBServiceSourceNameDMS { - return fmt.Errorf("external db service can not be updated") - } if updateDBService.Host == "" || updateDBService.Port == "" || - updateDBService.AdminUser == "" || updateDBService.Business == "" { - return fmt.Errorf("db service's host,port,user,business can't be empty") + updateDBService.User == "" || updateDBService.EnvironmentTagUID == "" { + return fmt.Errorf("db service's host,port,user,environment can't be empty") + } + _, err := d.environmentTagUsecase.GetEnvironmentTagByUID(ctx, updateDBService.EnvironmentTagUID) + if err != nil { + return fmt.Errorf("check get environment tag by uid failed: %v", err) } } // update @@ -296,58 +713,193 @@ func (d *DBServiceUsecase) UpdateDBService(ctx context.Context, dbServiceUid str if updateDBService.Desc != nil { ds.Desc = *updateDBService.Desc } - if updateDBService.AdminPassword != nil { - if *updateDBService.AdminPassword == "" { + if updateDBService.Password != nil { + if *updateDBService.Password == "" { return fmt.Errorf("password can't be empty") } - ds.AdminPassword = *updateDBService.AdminPassword + ds.Password = *updateDBService.Password } ds.Host = updateDBService.Host ds.Port = updateDBService.Port - ds.AdminUser = updateDBService.AdminUser - ds.Business = updateDBService.Business + ds.User = updateDBService.User ds.AdditionalParams = updateDBService.AdditionalParams ds.MaintenancePeriod = updateDBService.MaintenancePeriod - + ds.EnableBackup = updateDBService.EnableBackup + ds.BackupMaxRows = updateDBService.BackupMaxRows + ds.SQLEConfig = &SQLEConfig{} // 支持新增和更新sqleConfig,不允许删除sqle配置 - if updateDBService.SQLQueryConfig != nil && updateDBService.RuleTemplateName != "" { - ds.SQLEConfig = &SQLEConfig{ - SQLQueryConfig: updateDBService.SQLQueryConfig, - RuleTemplateName: updateDBService.RuleTemplateName, - RuleTemplateID: updateDBService.RuleTemplateID, - } + if updateDBService.RuleTemplateName != "" { + ds.SQLEConfig.AuditEnabled = updateDBService.AuditEnabled + ds.SQLEConfig.RuleTemplateID = updateDBService.RuleTemplateID + ds.SQLEConfig.RuleTemplateName = updateDBService.RuleTemplateName + ds.SQLEConfig.DataExportRuleTemplateName = updateDBService.DataExportRuleTemplateName + ds.SQLEConfig.DataExportRuleTemplateID = updateDBService.DataExportRuleTemplateID + } + ds.EnvironmentTag = &dmsCommonV1.EnvironmentTag{ + UID: updateDBService.EnvironmentTagUID, + } + + if updateDBService.SQLQueryConfig != nil { + ds.SQLEConfig.SQLQueryConfig = updateDBService.SQLQueryConfig } } if err := d.repo.UpdateDBService(ctx, ds); nil != err { return fmt.Errorf("update db service error: %v", err) } + + err = d.pluginUsecase.UpdateDBServiceAfterHandle(ctx, ds.UID) + if err != nil { + return fmt.Errorf("plugin handle after update db_service err: %v", err) + } + return nil } -type IsConnectableParams struct { - DBType pkgConst.DBType - Host string - Port string - User string - Password string - AdditionalParams pkgParams.Params -} - -func (d *DBServiceUsecase) IsConnectable(ctx context.Context, params IsConnectableParams) (bool, error) { - switch params.DBType { - case pkgConst.DBTypeMySQL: - return database.NewMysqlManager(params.Host, params.Port, params.User, params.Password).IsConnectable(ctx) - case pkgConst.DBTypeOracle: - return false, nil - case pkgConst.DBTypeOceanBaseMySQL: - return false, nil - case pkgConst.DBTypePostgreSQL: - return false, nil - case pkgConst.DBTypeSQLServer: - return false, nil - default: - return false, fmt.Errorf("%s does not exist", params.DBType) +type IsConnectableReply struct { + IsConnectable bool `json:"is_connectable"` + Component string `json:"component"` + ConnectErrorMessage string `json:"connect_error_message"` +} + +func (d *DBServiceUsecase) IsConnectable(ctx context.Context, params dmsCommonV1.CheckDbConnectable) ([]*IsConnectableReply, error) { + dmsProxyTargets, err := d.dmsProxyTargetRepo.ListProxyTargetsByScenarios(ctx, []ProxyScenario{ProxyScenarioInternalService}) + if err != nil { + return nil, err + } + + ret := make([]*IsConnectableReply, len(dmsProxyTargets)) + + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + uri := v1.GetDBConnectionAbleRouter() + + var wg = &sync.WaitGroup{} + wg.Add(len(dmsProxyTargets)) + + for i, target := range dmsProxyTargets { + go func(i int, target *ProxyTarget) { + defer wg.Done() + + isConnectableReply := &IsConnectableReply{Component: target.Name} + var reply = &v1Base.GenericResp{} + err = pkgHttp.POST(ctx, fmt.Sprintf("%s%s", target.URL.String(), uri), header, params, reply) + if err != nil { + isConnectableReply.ConnectErrorMessage = err.Error() + } else if reply.Code != 0 { + isConnectableReply.ConnectErrorMessage = reply.Message + } else { + isConnectableReply.IsConnectable = true + } + + ret[i] = isConnectableReply + }(i, target) + } + + wg.Wait() + + return ret, nil +} + +func (d *DBServiceUsecase) CountDBService(ctx context.Context) ([]DBTypeCount, error) { + counts, err := d.repo.CountDBService(ctx) + if err != nil { + return nil, fmt.Errorf("count db services failed: %w", err) + } + return counts, nil +} + +func (d *DBServiceUsecase) GetBizDBWithNameByUids(ctx context.Context, uids []string) []UIdWithName { + if len(uids) == 0 { + return []UIdWithName{} + } + uidWithNameCacheCache.ulock.Lock() + defer uidWithNameCacheCache.ulock.Unlock() + if uidWithNameCacheCache.DBCache == nil { + uidWithNameCacheCache.DBCache = make(map[string]UIdWithName) + } + ret := make([]UIdWithName, 0) + for _, uid := range uids { + dbCache, ok := uidWithNameCacheCache.DBCache[uid] + if !ok { + dbCache = UIdWithName{ + Uid: uid, + } + db, err := d.repo.GetDBService(ctx, uid) + if err == nil { + dbCache.Name = db.Name + uidWithNameCacheCache.DBCache[db.UID] = dbCache + } else { + d.log.Errorf("get db service for cache err: %v", err) + } + } + ret = append(ret, dbCache) + } + return ret +} + +func (d *DBServiceUsecase) GetBusiness(ctx context.Context, projectUid string) ([]string, error) { + business, err := d.repo.GetBusinessByProjectUID(ctx, projectUid) + if err != nil { + return nil, fmt.Errorf("get business failed: %v", err) + } + + return business, nil +} + +type CheckDBServicePrivileges struct { + ComponentPrivilegesResult []*IsConnectableReply +} + +func (d *DBServiceUsecase) CheckDBServiceHasEnoughPrivileges(ctx context.Context, params []dmsCommonV1.CheckDbConnectable) ([]*CheckDBServicePrivileges, error) { + type resultItem struct { + index int + result *CheckDBServicePrivileges + err error } + + ret := make([]*CheckDBServicePrivileges, len(params)) + resultCh := make(chan resultItem, len(params)) + var wg sync.WaitGroup + + maxConcurrency := 8 + semaphore := make(chan struct{}, maxConcurrency) + + for i, v := range params { + wg.Add(1) + go func(i int, param dmsCommonV1.CheckDbConnectable) { + defer wg.Done() + + semaphore <- struct{}{} // acquire slot + defer func() { <-semaphore }() // release slot + + r, err := d.IsConnectable(ctx, param) + if err != nil { + resultCh <- resultItem{index: i, err: fmt.Errorf("check db service privileges failed: %v", err)} + return + } + + resultCh <- resultItem{ + index: i, + result: &CheckDBServicePrivileges{ + ComponentPrivilegesResult: r, + }, + } + }(i, v) + } + + wg.Wait() + close(resultCh) + + for item := range resultCh { + if item.err != nil { + return nil, item.err + } + ret[item.index] = item.result + } + + return ret, nil } diff --git a/internal/dms/biz/db_service_sync_task.go b/internal/dms/biz/db_service_sync_task.go new file mode 100644 index 000000000..04756ac1e --- /dev/null +++ b/internal/dms/biz/db_service_sync_task.go @@ -0,0 +1,64 @@ +package biz + +import ( + "context" + "time" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgParams "github.com/actiontech/dms/pkg/params" + "github.com/robfig/cron/v3" +) + +type DBServiceSyncTaskRepo interface { + SaveDBServiceSyncTask(ctx context.Context, syncTask *DBServiceSyncTask) error + UpdateDBServiceSyncTask(ctx context.Context, syncTask *DBServiceSyncTask) error + GetDBServiceSyncTaskById(ctx context.Context, id string) (*DBServiceSyncTask, error) + ListDBServiceSyncTasks(ctx context.Context) ([]*DBServiceSyncTask, error) + ListDBServiceSyncTaskTips(ctx context.Context) ([]ListDBServiceSyncTaskTips, error) + DeleteDBServiceSyncTask(ctx context.Context, id string) error + UpdateDBServiceSyncTaskByFields(ctx context.Context, id string, fields map[string]interface{}) error +} + +type DBServiceSyncTaskUsecase struct { + log *utilLog.Helper + repo DBServiceSyncTaskRepo + opPermissionVerifyUsecase *OpPermissionVerifyUsecase + dbServiceUsecase *DBServiceUsecase + projectUsecase *ProjectUsecase + environmentTagUsecase *EnvironmentTagUsecase + cron *cron.Cron + lastSyncTime time.Time +} + +func NewDBServiceSyncTaskUsecase(log utilLog.Logger, repo DBServiceSyncTaskRepo, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, + projectUsecase *ProjectUsecase, dbServiceUsecase *DBServiceUsecase, environmentTagUsecase *EnvironmentTagUsecase) *DBServiceSyncTaskUsecase { + return &DBServiceSyncTaskUsecase{ + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.db_service_sync_task")), + repo: repo, + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + projectUsecase: projectUsecase, + dbServiceUsecase: dbServiceUsecase, + environmentTagUsecase: environmentTagUsecase, + } +} + +type DBServiceSyncTask struct { + UID string `json:"uid"` + Name string `json:"name"` + Source string `json:"source"` + URL string `json:"url"` + DbType string `json:"db_type"` + CronExpress string `json:"cron_express"` + LastSyncErr string `json:"last_sync_err"` + LastSyncSuccessTime *time.Time `json:"last_sync_success_time"` + AdditionalParam pkgParams.Params `json:"additional_params"` + SQLEConfig *SQLEConfig `json:"sqle_config"` +} + +type ListDBServiceSyncTaskTips struct { + Type pkgConst.DBServiceSourceName `json:"service_source_name"` + Desc string `json:"description"` + DBTypes []pkgConst.DBType `json:"db_type"` + Params pkgParams.Params `json:"params,omitempty"` +} diff --git a/internal/dms/biz/db_service_sync_task_ce.go b/internal/dms/biz/db_service_sync_task_ce.go new file mode 100644 index 000000000..4c2246bc6 --- /dev/null +++ b/internal/dms/biz/db_service_sync_task_ce.go @@ -0,0 +1,51 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" +) + +var errNotDBServiceSyncTask = errors.New("db service sync task related functions are enterprise version functions") + +func (uc *DBServiceSyncTaskUsecase) AddDBServiceSyncTask(ctx context.Context, syncTask *DBServiceSyncTask, currentUserId string) (string, error) { + return "", errNotDBServiceSyncTask +} + +func (uc *DBServiceSyncTaskUsecase) checkPermission(ctx context.Context, currentUserId string) error { + return errNotDBServiceSyncTask +} + +func (uc *DBServiceSyncTaskUsecase) UpdateDBServiceSyncTask(ctx context.Context, syncTaskId string, updateValues *DBServiceSyncTask, currentUserId string) error { + return errNotDBServiceSyncTask +} + +func (d *DBServiceSyncTaskUsecase) ListDBServiceSyncTasks(ctx context.Context, currentUserId string) ([]*DBServiceSyncTask, error) { + return nil, errNotDBServiceSyncTask +} + +func (d *DBServiceSyncTaskUsecase) ListDBServiceSyncTaskTips(ctx context.Context) ([]ListDBServiceSyncTaskTips, error) { + return nil, errNotDBServiceSyncTask +} + +func (d *DBServiceSyncTaskUsecase) GetDBServiceSyncTask(ctx context.Context, syncTaskId, currentUserId string) (*DBServiceSyncTask, error) { + return nil, errNotDBServiceSyncTask +} + +func (uc *DBServiceSyncTaskUsecase) DeleteDBServiceSyncTask(ctx context.Context, syncTaskId, currentUserId string) error { + return errNotDBServiceSyncTask +} + +func (uc *DBServiceSyncTaskUsecase) SyncDBServices(ctx context.Context, syncTaskId, currentUserId string) error { + return errNotDBServiceSyncTask +} + +func (d *DBServiceSyncTaskUsecase) RestartSyncDBServiceSyncTask() { +} + +func (d *DBServiceSyncTaskUsecase) StartSyncDBServiceSyncTask() { +} + +func (d *DBServiceSyncTaskUsecase) StopSyncDBServiceSyncTask() { +} diff --git a/internal/dms/biz/environment_tag.go b/internal/dms/biz/environment_tag.go new file mode 100644 index 000000000..5c981adbd --- /dev/null +++ b/internal/dms/biz/environment_tag.go @@ -0,0 +1,220 @@ +package biz + +import ( + "context" + "fmt" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" +) + +type EnvironmentTagRepo interface { + CreateEnvironmentTag(ctx context.Context, environmentTag *EnvironmentTag) error + UpdateEnvironmentTag(ctx context.Context, environmentTagName, environmentTagUID string) error + DeleteEnvironmentTag(ctx context.Context, environmentTagUID string) error + GetEnvironmentTagByName(ctx context.Context, projectUid, name string) (bool, *EnvironmentTag, error) + GetEnvironmentTagByUID(ctx context.Context, uid string) (*EnvironmentTag, error) + ListEnvironmentTags(ctx context.Context, options *ListEnvironmentTagsOption) ([]*EnvironmentTag, int64, error) +} + +type EnvironmentTagUsecase struct { + environmentTagRepo EnvironmentTagRepo + projectUsecase *ProjectUsecase + opPermissionVerifyUsecase *OpPermissionVerifyUsecase + log *utilLog.Helper +} + +func NewEnvironmentTagUsecase(environmentTagRepo EnvironmentTagRepo, logger utilLog.Logger, + projectUsecase *ProjectUsecase, + opPermissionVerifyUsecase *OpPermissionVerifyUsecase) *EnvironmentTagUsecase { + return &EnvironmentTagUsecase{ + environmentTagRepo: environmentTagRepo, + projectUsecase: projectUsecase, + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.environment_tag")), + } +} + +type EnvironmentTag struct { + UID string + Name string + ProjectUID string +} + +func (uc *EnvironmentTagUsecase) newEnvironmentTag(projectUid, tagName string) (*EnvironmentTag, error) { + uid, err := pkgRand.GenStrUid() + if err != nil { + return nil, err + } + if tagName == "" { + return nil, fmt.Errorf("environment tag name or project is empty") + } + return &EnvironmentTag{ + UID: uid, + Name: tagName, + ProjectUID: projectUid, + }, nil +} + +func (uc *EnvironmentTagUsecase) InitDefaultEnvironmentTags(ctx context.Context, projectUid, currentUserUid string) (err error) { + defaultEnvironmentTags := []string{ + "DEV", + "TEST", + "UAT", + "PROD", + "OUTSIDE", + } + + for _, environmentTag := range defaultEnvironmentTags { + err = uc.CreateEnvironmentTag(ctx, projectUid, currentUserUid, environmentTag) + if err != nil { + uc.log.Errorf("create environment tag failed: %v", err) + return fmt.Errorf("create environment tag failed: %w", err) + } + } + return nil +} + +func (uc *EnvironmentTagUsecase) CreateEnvironmentTag(ctx context.Context, projectUid, currentUserUid, tagName string) error { + // 检查项目是否归档/删除 + if err := uc.projectUsecase.isProjectActive(ctx, projectUid); err != nil { + return fmt.Errorf("update db service error: %v", err) + } + + // 检查当前用户有项目管理员权限 + if canOpProject, err := uc.opPermissionVerifyUsecase.CanOpProject(ctx, currentUserUid, projectUid); err != nil { + return fmt.Errorf("check user is project admin or golobal op permission failed: %v", err) + } else if !canOpProject { + return fmt.Errorf("user is not project admin or golobal op permission user") + } + // 校验环境标签名称 + exist, _, err := uc.GetEnvironmentTagByName(ctx, projectUid, tagName) + if err != nil { + uc.log.Errorf("get environment tag by name failed: %v", err) + return err + } + if exist { + return fmt.Errorf("the tag %s already exists in the current project", tagName) + } + environmentTag, err := uc.newEnvironmentTag(projectUid, tagName) + if err != nil { + uc.log.Errorf("new environment tag failed: %v", err) + return err + } + err = uc.environmentTagRepo.CreateEnvironmentTag(ctx, environmentTag) + if err != nil { + uc.log.Errorf("create environment tag failed: %v", err) + return err + } + return nil +} + +func (uc *EnvironmentTagUsecase) UpdateEnvironmentTag(ctx context.Context, projectUid, currentUserUid, environmentTagUID, environmentTagName string) error { + // 检查项目是否归档/删除 + if err := uc.projectUsecase.isProjectActive(ctx, projectUid); err != nil { + return fmt.Errorf("update db service error: %v", err) + } + + // 检查当前用户有项目管理员权限 + if canOpProject, err := uc.opPermissionVerifyUsecase.CanOpProject(ctx, currentUserUid, projectUid); err != nil { + return fmt.Errorf("check user is project admin or golobal op permission failed: %v", err) + } else if !canOpProject { + return fmt.Errorf("user is not project admin or golobal op permission user") + } + + if environmentTagUID == "" || environmentTagName == "" { + return fmt.Errorf("environment tag name or uid is empty, please check: id %v, name %v", environmentTagUID, environmentTagName) + } + _, err := uc.environmentTagRepo.GetEnvironmentTagByUID(ctx, environmentTagUID) + if err != nil { + uc.log.Errorf("get environment tag failed: %v", err) + return err + } + err = uc.environmentTagRepo.UpdateEnvironmentTag(ctx, environmentTagUID, environmentTagName) + if err != nil { + uc.log.Errorf("update environment tag failed: %v", err) + return err + } + return nil +} + +func (uc *EnvironmentTagUsecase) DeleteEnvironmentTag(ctx context.Context, projectUid, currentUserUid, environmentTagUID string) error { + // 检查项目是否归档/删除 + if err := uc.projectUsecase.isProjectActive(ctx, projectUid); err != nil { + return fmt.Errorf("update db service error: %v", err) + } + + // 检查当前用户有项目管理员权限 + if canOpProject, err := uc.opPermissionVerifyUsecase.CanOpProject(ctx, currentUserUid, projectUid); err != nil { + return fmt.Errorf("check user is project admin or golobal op permission failed: %v", err) + } else if !canOpProject { + return fmt.Errorf("user is not project admin or golobal op permission user") + } + + _, err := uc.environmentTagRepo.GetEnvironmentTagByUID(ctx, environmentTagUID) + if err != nil { + uc.log.Errorf("get environment tag failed: %v", err) + return err + } + err = uc.environmentTagRepo.DeleteEnvironmentTag(ctx, environmentTagUID) + if err != nil { + uc.log.Errorf("delete environment tag failed: %v", err) + return err + } + return nil +} + +type ListEnvironmentTagsOption struct { + Limit int + Offset int + ProjectUID string +} + +func (uc *EnvironmentTagUsecase) ListEnvironmentTags(ctx context.Context, options *ListEnvironmentTagsOption) ([]*EnvironmentTag, int64, error) { + environmentTags, count, err := uc.environmentTagRepo.ListEnvironmentTags(ctx, options) + if err != nil { + uc.log.Errorf("list environment tags failed: %v", err) + return nil, 0, err + } + return environmentTags, count, nil +} + +func (uc *EnvironmentTagUsecase) GetEnvironmentTagByName(ctx context.Context, projectUid, tagName string) (bool, *EnvironmentTag, error) { + exist, environmentTag, err := uc.environmentTagRepo.GetEnvironmentTagByName(ctx, projectUid, tagName) + if err != nil { + uc.log.Errorf("get environment tag failed: %v", err) + return false, nil, err + } + return exist, environmentTag, nil +} + +func (uc *EnvironmentTagUsecase) GetEnvironmentTagByUID(ctx context.Context, uid string) (*EnvironmentTag, error) { + environmentTag, err := uc.environmentTagRepo.GetEnvironmentTagByUID(ctx, uid) + if err != nil { + uc.log.Errorf("get environment tag failed: %v", err) + return nil, err + } + return environmentTag, nil +} + +func (uc *EnvironmentTagUsecase) GetOrCreateEnvironmentTag(ctx context.Context, projectUid, tagName string) (*EnvironmentTag, error) { + exist, environmentTag, err := uc.environmentTagRepo.GetEnvironmentTagByName(ctx, projectUid, tagName) + if err != nil { + uc.log.Errorf("get environment tag failed: %v", err) + return nil, err + } + if exist { + return environmentTag, nil + } + newTag, err := uc.newEnvironmentTag(projectUid, tagName) + if err != nil { + uc.log.Errorf("new environment tag failed: %v", err) + return nil, err + } + err = uc.environmentTagRepo.CreateEnvironmentTag(ctx, newTag) + if err != nil { + uc.log.Errorf("create environment tag failed: %v", err) + return nil, err + } + return newTag, nil +} diff --git a/internal/dms/biz/function_support_registry.go b/internal/dms/biz/function_support_registry.go new file mode 100644 index 000000000..7159d00a7 --- /dev/null +++ b/internal/dms/biz/function_support_registry.go @@ -0,0 +1,48 @@ +package biz + +import ( + "sync" +) + +// FunctionSupportProvider 功能支持提供者接口 +// 各功能模块实现此接口,向注册中心提供自己支持的数据库类型 +type FunctionSupportProvider interface { + // GetFunctionName 返回功能名称,如 "data_masking" + GetFunctionName() string + // GetSupportedDBTypes 返回支持的数据库类型列表 + GetSupportedDBTypes() []string +} + +// FunctionSupportRegistry 功能支持注册中心 +// 管理各功能模块支持的数据库类型,用于全局查询 +type FunctionSupportRegistry struct { + mu sync.RWMutex + providers map[string]FunctionSupportProvider +} + +// NewFunctionSupportRegistry 创建功能支持注册中心 +func NewFunctionSupportRegistry() *FunctionSupportRegistry { + return &FunctionSupportRegistry{ + providers: make(map[string]FunctionSupportProvider), + } +} + +// Register 注册功能支持提供者 +func (r *FunctionSupportRegistry) Register(provider FunctionSupportProvider) { + r.mu.Lock() + defer r.mu.Unlock() + r.providers[provider.GetFunctionName()] = provider +} + +// GetSupportedDBTypes 获取指定功能支持的数据库类型列表 +// 如果功能未注册,返回 nil +func (r *FunctionSupportRegistry) GetSupportedDBTypes(functionName string) []string { + r.mu.RLock() + defer r.mu.RUnlock() + + provider, ok := r.providers[functionName] + if !ok { + return nil + } + return provider.GetSupportedDBTypes() +} diff --git a/internal/dms/biz/gateway.go b/internal/dms/biz/gateway.go new file mode 100644 index 000000000..c36e55a23 --- /dev/null +++ b/internal/dms/biz/gateway.go @@ -0,0 +1,31 @@ +package biz + +import ( + "context" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" +) + +type GatewayRepo interface { + AddGateway(ctx context.Context, u *Gateway) error + DeleteGateway(ctx context.Context, id string) error + UpdateGateway(ctx context.Context, u *Gateway) error + GetGateway(ctx context.Context, id string) (*Gateway, error) + ListGateways(ctx context.Context, opt *ListGatewaysOption) ([]*Gateway, int64, error) + GetGatewayTips(ctx context.Context) ([]*Gateway, error) + SyncGateways(ctx context.Context, s []*Gateway) error +} + +type Gateway struct { + ID string + Name string + Desc string + URL string +} + +type ListGatewaysOption struct { + PageNumber uint32 + LimitPerPage uint32 + OrderBy MemberField + FilterByOptions pkgConst.FilterOptions +} diff --git a/internal/dms/biz/gateway_ce.go b/internal/dms/biz/gateway_ce.go new file mode 100644 index 000000000..325c05797 --- /dev/null +++ b/internal/dms/biz/gateway_ce.go @@ -0,0 +1,60 @@ +//go:build !enterprise + +package biz + +import ( + "context" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" +) + +func NewDmsGatewayUsecase(logger utilLog.Logger, repo GatewayRepo) (*GatewayUsecase, error) { + log := utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.gateway")) + gatewayUsecase := &GatewayUsecase{ + repo: repo, + logger: log, + } + return gatewayUsecase, nil +} + +type GatewayUsecase struct { + repo GatewayRepo + logger *utilLog.Helper +} + +func (d *GatewayUsecase) Skipper(c echo.Context) bool { + return true +} + +// AddTarget 实现echo的ProxyBalancer接口,没有实际意义 +func (d *GatewayUsecase) Next(c echo.Context) *middleware.ProxyTarget { + return nil +} + +// AddTarget 实现echo的ProxyBalancer接口,没有实际意义 +func (d *GatewayUsecase) AddTarget(*middleware.ProxyTarget) bool { + return true +} + +// RemoveTarget 实现echo的ProxyBalancer接口,没有实际意义 +func (d *GatewayUsecase) RemoveTarget(string) bool { + return true +} + +func (d *GatewayUsecase) BroadcastAddUser(ctx context.Context, args *CreateUserArgs) error { + return nil +} + +func (d *GatewayUsecase) BroadcastUpdateUser(ctx context.Context, user *User) error { + return nil +} + +func (d *GatewayUsecase) Broadcast() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + return next(c) + } + } +} diff --git a/internal/dms/biz/license.go b/internal/dms/biz/license.go new file mode 100644 index 000000000..4cf137d0f --- /dev/null +++ b/internal/dms/biz/license.go @@ -0,0 +1,41 @@ +package biz + +import ( + "context" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "github.com/robfig/cron/v3" +) + +type LicenseRepo interface { + SaveLicense(ctx context.Context, license interface{}) error + GetLastLicense(ctx context.Context) (interface{}, bool, error) + GetLicenseById(ctx context.Context, id string) (interface{}, bool, error) + UpdateLicense(ctx context.Context, license interface{}) error + DelLicense(ctx context.Context) error +} + +type LicenseUsecase struct { + tx TransactionGenerator + repo LicenseRepo + userUsecase *UserUsecase + DBService *DBServiceUsecase + log *utilLog.Helper + cron *cron.Cron + clusterUsecase *ClusterUsecase +} + +func NewLicenseUsecase(log utilLog.Logger, tx TransactionGenerator, repo LicenseRepo, usecase *UserUsecase, serviceUsecase *DBServiceUsecase, clusterUsecase *ClusterUsecase) *LicenseUsecase { + lu := &LicenseUsecase{ + tx: tx, + repo: repo, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.license")), + userUsecase: usecase, + DBService: serviceUsecase, + clusterUsecase: clusterUsecase, + } + + lu.initial() + + return lu +} diff --git a/internal/dms/biz/license_qa.go b/internal/dms/biz/license_qa.go new file mode 100644 index 000000000..5edf35617 --- /dev/null +++ b/internal/dms/biz/license_qa.go @@ -0,0 +1,91 @@ +//go:build !release +// +build !release + +package biz + +import ( + "context" + e "errors" + + v1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/pkg/locale" +) + +type License struct { +} + +var ErrNoLicenseRequired = e.New("dms-qa version has unlimited resources does not need to set license") + +func (d *LicenseUsecase) GetLicense(ctx context.Context) (*v1.GetLicenseReply, error) { + return &v1.GetLicenseReply{ + License: []v1.LicenseItem{ + { + Description: locale.Bundle.LocalizeMsgByCtx(ctx, locale.LicenseInstanceNum), + Name: "instance_num", + Limit: locale.Bundle.LocalizeMsgByCtx(ctx, locale.LicenseUnlimited), + }, + { + Description: locale.Bundle.LocalizeMsgByCtx(ctx, locale.LicenseUserNum), + Name: "user", + Limit: locale.Bundle.LocalizeMsgByCtx(ctx, locale.LicenseUnlimited), + }, + { + Description: locale.Bundle.LocalizeMsgByCtx(ctx, locale.LicenseAuthorizedDurationDay), + Name: "work duration day", + Limit: locale.Bundle.LocalizeMsgByCtx(ctx, locale.LicenseUnlimited), + }, + }, + }, nil +} + +func (d *LicenseUsecase) GetLicenseInfo(ctx context.Context) ([]byte, error) { + return []byte{}, ErrNoLicenseRequired +} + +func (d *LicenseUsecase) GetLicenseUsage(ctx context.Context) (*v1.GetLicenseUsageReply, error) { + usersTotal, err := d.userUsecase.repo.CountUsers(ctx, nil) + if err != nil { + return nil, err + } + + instanceStatistics, err := d.DBService.CountDBService(ctx) + if err != nil { + return nil, err + } + + dbServicesUsage := make([]v1.LicenseUsageItem, 0, len(instanceStatistics)) + for _, item := range instanceStatistics { + dbServicesUsage = append(dbServicesUsage, v1.LicenseUsageItem{ + ResourceType: item.DBType, + ResourceTypeDesc: item.DBType, + Used: uint(item.Count), + Limit: 0, + IsLimited: false, + }) + } + + return &v1.GetLicenseUsageReply{ + Data: &v1.LicenseUsage{ + UsersUsage: v1.LicenseUsageItem{ + ResourceType: "user", + ResourceTypeDesc: locale.Bundle.LocalizeMsgByCtx(ctx, locale.LicenseResourceTypeUser), + Used: uint(usersTotal), + Limit: 0, + IsLimited: false, + }, + DbServicesUsage: dbServicesUsage, + }, + }, nil +} + +func (d *LicenseUsecase) SetLicense(ctx context.Context, data string) error { + return ErrNoLicenseRequired +} + +func (d *LicenseUsecase) CheckLicense(ctx context.Context, data string) (*v1.CheckLicenseReply, error) { + return nil, ErrNoLicenseRequired +} + +func (d *LicenseUsecase) initial() { + +} diff --git a/internal/dms/biz/login_configuration.go b/internal/dms/biz/login_configuration.go new file mode 100644 index 000000000..4f836d68b --- /dev/null +++ b/internal/dms/biz/login_configuration.go @@ -0,0 +1,46 @@ +package biz + +import ( + "context" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" +) + +type LoginConfiguration struct { + Base + UID string + LoginButtonText string + DisableUserPwdLogin bool +} + +func defaultLoginConfiguration() (*LoginConfiguration, error) { + uid, err := pkgRand.GenStrUid() + if err != nil { + return nil, err + } + return &LoginConfiguration{ + UID: uid, + LoginButtonText: "登录", + DisableUserPwdLogin: false, + }, nil +} + +type LoginConfigurationRepo interface { + UpdateLoginConfiguration(ctx context.Context, configuration *LoginConfiguration) error + GetLastLoginConfiguration(ctx context.Context) (*LoginConfiguration, error) +} + +type LoginConfigurationUsecase struct { + tx TransactionGenerator + repo LoginConfigurationRepo + log *utilLog.Helper +} + +func NewLoginConfigurationUsecase(log utilLog.Logger, tx TransactionGenerator, repo LoginConfigurationRepo) *LoginConfigurationUsecase { + return &LoginConfigurationUsecase{ + tx: tx, + repo: repo, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.Login_configuration")), + } +} diff --git a/internal/dms/biz/login_configuration_ce.go b/internal/dms/biz/login_configuration_ce.go new file mode 100644 index 000000000..f1a3fa841 --- /dev/null +++ b/internal/dms/biz/login_configuration_ce.go @@ -0,0 +1,21 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" +) + +var errNotSupportLoginConfiguration = errors.New("login configuration related functions are enterprise version functions") + +func (d *LoginConfigurationUsecase) UpdateLoginConfiguration(ctx context.Context, LoginButtonText *string, DisableUserPwdLogin *bool) error { + return errNotSupportLoginConfiguration +} + +func (d *LoginConfigurationUsecase) GetLoginConfiguration(ctx context.Context) (loginC *LoginConfiguration, err error) { + return &LoginConfiguration{ + LoginButtonText: "登录", + DisableUserPwdLogin: false, + }, nil +} diff --git a/internal/dms/biz/maintenance_time.go b/internal/dms/biz/maintenance_time.go new file mode 100644 index 000000000..49322e251 --- /dev/null +++ b/internal/dms/biz/maintenance_time.go @@ -0,0 +1,121 @@ +package biz + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/actiontech/dms/internal/pkg/locale" + pkgPeriods "github.com/actiontech/dms/pkg/periods" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +// MaintenanceTimeConfig 运维时间管控配置 +type MaintenanceTimeConfig struct { + Enabled bool + Periods pkgPeriods.Periods +} + +// MaintenanceTimeUsecase 运维时间管控业务逻辑 +type MaintenanceTimeUsecase struct { + opPermissionVerifyUsecase *OpPermissionVerifyUsecase + log *utilLog.Helper +} + +// NewMaintenanceTimeUsecase 创建运维时间管控业务逻辑实例 +func NewMaintenanceTimeUsecase( + log utilLog.Logger, + opPermissionVerifyUsecase *OpPermissionVerifyUsecase, +) *MaintenanceTimeUsecase { + return &MaintenanceTimeUsecase{ + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.maintenance_time")), + } +} + +// MaintenanceTimeConfigFromSQLQuery 从数据源 sql_query_config 解析运维时间管控配置 +func MaintenanceTimeConfigFromSQLQuery(sqlQueryConfig *SQLQueryConfig) *MaintenanceTimeConfig { + cfg := &MaintenanceTimeConfig{} + if sqlQueryConfig == nil { + return cfg + } + cfg.Enabled = len(sqlQueryConfig.MaintenancePeriods) > 0 + if cfg.Enabled { + cfg.Periods = sqlQueryConfig.MaintenancePeriods.Copy() + } + return cfg +} + +// CheckSQLExecutionAllowed 检查SQL执行是否被运维时间管控允许 +// 参数: +// - userUid: 当前执行SQL的用户UID +// - sqlTypes: SQLE审核返回的sql_type列表(每条SQL对应一个) +// - currentTime: 当前时间(参数化便于测试) +// - sqlQueryConfig: 数据源上的 SQL 查询配置(含运维时间窗口) +// +// 返回值: +// - allowed: 是否允许执行 +// - message: 拦截时的提示消息(allowed=true时为空) +// - err: 内部错误 +func (m *MaintenanceTimeUsecase) CheckSQLExecutionAllowed( + ctx context.Context, + userUid string, + sqlTypes []string, + currentTime time.Time, + sqlQueryConfig *SQLQueryConfig, +) (allowed bool, message string, err error) { + // 1. 获取配置 + config := MaintenanceTimeConfigFromSQLQuery(sqlQueryConfig) + + // 2. 如果开关关闭,直接允许执行 + if !config.Enabled { + return true, "", nil + } + + // 3. 检查 sqlTypes 中是否有非DQL语句 + hasNonDQL := false + for _, sqlType := range sqlTypes { + if sqlType != "dql" { // 空字符串("")也视为非DQL(保守策略) + hasNonDQL = true + break + } + } + if !hasNonDQL { + return true, "", nil + } + + // 4. 检查用户是否为管理员 + isAdmin, err := m.opPermissionVerifyUsecase.CanOpGlobal(ctx, userUid) + if err != nil { + return false, "", fmt.Errorf("failed to check user admin permission: %v", err) + } + if isAdmin { + m.log.Warnf("user %s is admin, skip cloudbeaver maintenance time check", userUid) + return true, "", nil + } + + // 5. 检查当前时间是否在配置的运维时间段内 + if config.Periods.IsWithinScope(currentTime) { + return true, "", nil + } + + // 6. 构造拦截消息 + periodsStr := formatPeriodsToReadableString(config.Periods) + message = fmt.Sprintf(locale.Bundle.LocalizeMsgByCtx(ctx, locale.SqlWorkbenchMaintenanceTimeBlocked), periodsStr) + + // 7. 返回拦截结果 + return false, message, nil +} + +// formatPeriodsToReadableString 将时间段格式化为可读字符串 +// 例如: "01:00-06:00, 22:00-02:00" +func formatPeriodsToReadableString(ps pkgPeriods.Periods) string { + parts := make([]string, 0, len(ps)) + for _, p := range ps { + parts = append(parts, fmt.Sprintf("%02d:%02d-%02d:%02d", + p.StartHour, p.StartMinute, p.EndHour, p.EndMinute)) + } + return strings.Join(parts, ", ") +} diff --git a/internal/dms/biz/member.go b/internal/dms/biz/member.go index c465f1bf0..d9008e284 100644 --- a/internal/dms/biz/member.go +++ b/internal/dms/biz/member.go @@ -14,9 +14,12 @@ type Member struct { Base UID string - NamespaceUID string + ProjectUID string UserUID string + Projects []string + PlatformRoles []string RoleWithOpRanges []MemberRoleWithOpRange + OpPermissions []OpPermission } func (u *Member) GetUID() string { @@ -29,7 +32,7 @@ type MemberRoleWithOpRange struct { RangeUIDs []string // Range描述操作权限的权限范围,如涉及哪些数据源 } -func newMember(userUid, namespaceUid string, opPermissions []MemberRoleWithOpRange) (*Member, error) { +func newMember(userUid, projectUid string, opPermissions []MemberRoleWithOpRange) (*Member, error) { uid, err := pkgRand.GenStrUid() if err != nil { @@ -38,7 +41,7 @@ func newMember(userUid, namespaceUid string, opPermissions []MemberRoleWithOpRan return &Member{ UID: uid, - NamespaceUID: namespaceUid, + ProjectUID: projectUid, UserUID: userUid, RoleWithOpRanges: opPermissions, }, nil @@ -52,6 +55,7 @@ type MemberRepo interface { CheckMemberExist(ctx context.Context, memberUids []string) (exists bool, err error) DelMember(ctx context.Context, memberUid string) error DelRoleFromAllMembers(ctx context.Context, roleUid string) error + ReplaceOpPermissionsInMember(ctx context.Context, memberUid string, opPermissionUids []string) error } type MemberUsecase struct { @@ -61,7 +65,8 @@ type MemberUsecase struct { roleUsecase *RoleUsecase dbServiceUsecase *DBServiceUsecase opPermissionVerifyUsecase *OpPermissionVerifyUsecase - namespaceUsecase *NamespaceUsecase + projectUsecase *ProjectUsecase + pluginUsecase *PluginUsecase log *utilLog.Helper } @@ -70,7 +75,8 @@ func NewMemberUsecase(log utilLog.Logger, tx TransactionGenerator, repo MemberRe roleUsecase *RoleUsecase, dbServiceUsecase *DBServiceUsecase, opPermissionVerifyUsecase *OpPermissionVerifyUsecase, - namespaceUsecase *NamespaceUsecase) *MemberUsecase { + projectUsecase *ProjectUsecase, + pluginUsecase *PluginUsecase) *MemberUsecase { return &MemberUsecase{ tx: tx, repo: repo, @@ -78,25 +84,20 @@ func NewMemberUsecase(log utilLog.Logger, tx TransactionGenerator, repo MemberRe roleUsecase: roleUsecase, dbServiceUsecase: dbServiceUsecase, opPermissionVerifyUsecase: opPermissionVerifyUsecase, - namespaceUsecase: namespaceUsecase, + projectUsecase: projectUsecase, + pluginUsecase: pluginUsecase, log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.member")), } } -func (m *MemberUsecase) CreateMember(ctx context.Context, currentUserUid string, memberUserUid string, namespaceUid string, isNamespaceAdmin bool, - roleAndOpRanges []MemberRoleWithOpRange) (memberUid string, err error) { +func (m *MemberUsecase) CreateMember(ctx context.Context, currentUserUid string, memberUserUid string, projectUid string, isProjectAdmin bool, + roleAndOpRanges []MemberRoleWithOpRange, projectManagePermissions []string) (memberUid string, err error) { // check { - // 检查空间是否归档/删除 - if err := m.namespaceUsecase.isNamespaceActive(ctx, namespaceUid); err != nil { + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, projectUid); err != nil { return "", fmt.Errorf("create member error: %v", err) } - // 检查当前用户有空间管理员权限 - if isAdmin, err := m.opPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, currentUserUid, namespaceUid); err != nil { - return "", fmt.Errorf("check user is namespace admin failed: %v", err) - } else if !isAdmin { - return "", fmt.Errorf("user is not namespace admin") - } // 检查成员用户存在 if exist, err := m.userUsecase.CheckUserExist(ctx, []string{memberUserUid}); err != nil { @@ -109,37 +110,39 @@ func (m *MemberUsecase) CreateMember(ctx context.Context, currentUserUid string, return "", err } - // 检查空间内成员之间的用户不同 + // 检查项目内成员之间的用户不同 if _, total, err := m.ListMember(ctx, &ListMembersOption{ PageNumber: 0, LimitPerPage: 10, - FilterBy: []pkgConst.FilterCondition{ - { - Field: string(MemberFieldUserUID), - Operator: pkgConst.FilterOperatorEqual, - Value: memberUserUid, - }, - { - Field: string(MemberFieldNamespaceUID), - Operator: pkgConst.FilterOperatorEqual, - Value: namespaceUid, - }, - }, - }, namespaceUid); err != nil { + FilterByOptions: pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd, + pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(MemberFieldUserUID), + Operator: pkgConst.FilterOperatorEqual, + Value: memberUserUid, + }, + pkgConst.FilterCondition{ + Field: string(MemberFieldProjectUID), + Operator: pkgConst.FilterOperatorEqual, + Value: projectUid, + }, + ), + ), + }, projectUid); err != nil { return "", fmt.Errorf("check member exist failed: %v", err) } else if total > 0 { - return "", fmt.Errorf("user already in namespace") + return "", fmt.Errorf("user already in project") } } - member, err := newMember(memberUserUid, namespaceUid, roleAndOpRanges) + member, err := newMember(memberUserUid, projectUid, roleAndOpRanges) if err != nil { return "", fmt.Errorf("new member failed: %v", err) } - // 如果是空间管理员,则自动添加内置的空间管理员角色 - if isNamespaceAdmin { - m.FixMemberWithNamespaceAdmin(ctx, member, namespaceUid) + // 如果是项目管理员,则自动添加内置的项目管理员角色 + if isProjectAdmin { + m.FixMemberWithProjectAdmin(ctx, member, projectUid) } tx := m.tx.BeginTX(ctx) @@ -153,6 +156,10 @@ func (m *MemberUsecase) CreateMember(ctx context.Context, currentUserUid string, return "", fmt.Errorf("save member failed: %v", err) } + if err := m.repo.ReplaceOpPermissionsInMember(tx, member.UID, projectManagePermissions); err != nil { + return "", fmt.Errorf("replace op permissions in member failed: %v", err) + } + if err := tx.Commit(m.log); err != nil { return "", fmt.Errorf("commit tx failed: %v", err) } @@ -160,38 +167,40 @@ func (m *MemberUsecase) CreateMember(ctx context.Context, currentUserUid string, } -// AddUserToNamespaceAdmin 将指定用户加入空间成员,并赋予空间管理员权限 -func (m *MemberUsecase) AddUserToNamespaceAdminMember(ctx context.Context, userUid string, namespaceUid string) (memberUid string, err error) { +// AddUserToProjectAdmin 将指定用户加入项目成员,并赋予项目管理员权限 +func (m *MemberUsecase) AddUserToProjectAdminMember(ctx context.Context, userUid string, projectUid string) (memberUid string, err error) { // check { - // 检查空间是否归档/删除 - if err := m.namespaceUsecase.isNamespaceActive(ctx, namespaceUid); err != nil { - return "", fmt.Errorf("add user to namespace admin member error: %v", err) + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, projectUid); err != nil { + return "", fmt.Errorf("add user to project admin member error: %v", err) } // 如果已存在则报错 if _, total, err := m.ListMember(ctx, &ListMembersOption{ PageNumber: 0, LimitPerPage: 10, - FilterBy: []pkgConst.FilterCondition{ - { + FilterByOptions: pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd, + pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ Field: string(MemberFieldUserUID), Operator: pkgConst.FilterOperatorEqual, Value: userUid, }, - { - Field: string(MemberFieldNamespaceUID), + pkgConst.FilterCondition{ + Field: string(MemberFieldProjectUID), Operator: pkgConst.FilterOperatorEqual, - Value: namespaceUid, + Value: projectUid, }, - }, - }, namespaceUid); err != nil { + ), + ), + }, projectUid); err != nil { return "", fmt.Errorf("check member exist failed: %v", err) } else if total > 0 { - return "", fmt.Errorf("user already in namespace") + return "", fmt.Errorf("user already in project") } } - member, err := newMember(userUid, namespaceUid, []MemberRoleWithOpRange{m.GetNamespaceAdminRoleWithOpRange(namespaceUid)}) + member, err := newMember(userUid, projectUid, []MemberRoleWithOpRange{m.GetProjectAdminRoleWithOpRange(projectUid)}) if err != nil { return "", fmt.Errorf("new member failed: %v", err) } @@ -232,7 +241,7 @@ func (m *MemberUsecase) CheckRoleAndOpRanges(ctx context.Context, roleAndOpRange return fmt.Errorf("db service not exist") } // 角色目前与成员绑定,只支持配置数据源范围的权限 - case OpRangeTypeNamespace, OpRangeTypeGlobal: + case OpRangeTypeProject, OpRangeTypeGlobal: return fmt.Errorf("role currently only support the db service op range type, but got type: %v", op.RangeType) default: return fmt.Errorf("unsupported range type: %v", op.RangeType) @@ -242,30 +251,30 @@ func (m *MemberUsecase) CheckRoleAndOpRanges(ctx context.Context, roleAndOpRange return nil } -func (m *MemberUsecase) IsMemberNamespaceAdmin(ctx context.Context, memberUid string) (bool, error) { +func (m *MemberUsecase) IsMemberProjectAdmin(ctx context.Context, memberUid string) (bool, error) { member, err := m.repo.GetMember(ctx, memberUid) if err != nil { return false, fmt.Errorf("get member failed: %v", err) } for _, r := range member.RoleWithOpRanges { - if r.RoleUID == pkgConst.UIDOfRoleNamespaceAdmin { + if r.RoleUID == pkgConst.UIDOfRoleProjectAdmin { return true, nil } } return false, nil } -// FixMemberWithNamespaceAdmin 自动修改成员的角色和操作权限范围,如果是空间管理员,则自动添加内置的空间管理员角色 -func (m *MemberUsecase) FixMemberWithNamespaceAdmin(ctx context.Context, member *Member, namespaceUid string) { - member.RoleWithOpRanges = append(member.RoleWithOpRanges, m.GetNamespaceAdminRoleWithOpRange(namespaceUid)) +// FixMemberWithProjectAdmin 自动修改成员的角色和操作权限范围,如果是项目管理员,则自动添加内置的项目管理员角色 +func (m *MemberUsecase) FixMemberWithProjectAdmin(ctx context.Context, member *Member, projectUid string) { + member.RoleWithOpRanges = append(member.RoleWithOpRanges, m.GetProjectAdminRoleWithOpRange(projectUid)) } -func (m *MemberUsecase) GetNamespaceAdminRoleWithOpRange(namespaceUid string) MemberRoleWithOpRange { +func (m *MemberUsecase) GetProjectAdminRoleWithOpRange(projectUid string) MemberRoleWithOpRange { return MemberRoleWithOpRange{ - RoleUID: pkgConst.UIDOfRoleNamespaceAdmin, - OpRangeType: OpRangeTypeNamespace, - RangeUIDs: []string{namespaceUid}, + RoleUID: pkgConst.UIDOfRoleProjectAdmin, + OpRangeType: OpRangeTypeProject, + RangeUIDs: []string{projectUid}, } } @@ -278,17 +287,13 @@ func (m *MemberUsecase) GetMemberRoleWithOpRange(ctx context.Context, memberUid } type ListMembersOption struct { - PageNumber uint32 - LimitPerPage uint32 - OrderBy MemberField - FilterBy []pkgConst.FilterCondition + PageNumber uint32 + LimitPerPage uint32 + OrderBy MemberField + FilterByOptions pkgConst.FilterOptions } -func (m *MemberUsecase) ListMember(ctx context.Context, option *ListMembersOption, namespaceUid string) (members []*Member, total int64, err error) { - // 检查空间是否归档/删除 - if err := m.namespaceUsecase.isNamespaceActive(ctx, namespaceUid); err != nil { - return nil, 0, fmt.Errorf("list member error: %v", err) - } +func (m *MemberUsecase) ListMember(ctx context.Context, option *ListMembersOption, projectUid string) (members []*Member, total int64, err error) { members, total, err = m.repo.ListMembers(ctx, option) if err != nil { return nil, 0, fmt.Errorf("list members failed: %v", err) @@ -305,20 +310,14 @@ func (m *MemberUsecase) CheckMemberExist(ctx context.Context, memberUids []strin return m.repo.CheckMemberExist(ctx, memberUids) } -func (m *MemberUsecase) UpdateMember(ctx context.Context, currentUserUid, updateMemberUid, namespaceUid string, isNamespaceAdmin bool, - roleAndOpRanges []MemberRoleWithOpRange) error { +func (m *MemberUsecase) UpdateMember(ctx context.Context, currentUserUid, updateMemberUid, projectUid string, isProjectAdmin bool, + roleAndOpRanges []MemberRoleWithOpRange, projectManagePermissions []string) error { // check { - // 检查空间是否归档/删除 - if err := m.namespaceUsecase.isNamespaceActive(ctx, namespaceUid); err != nil { + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, projectUid); err != nil { return fmt.Errorf("update member error: %v", err) } - // 检查当前用户有空间管理员权限 - if isAdmin, err := m.opPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, currentUserUid, namespaceUid); err != nil { - return fmt.Errorf("check user is namespace admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not namespace admin") - } if err := m.CheckRoleAndOpRanges(ctx, roleAndOpRanges); err != nil { return err @@ -331,9 +330,13 @@ func (m *MemberUsecase) UpdateMember(ctx context.Context, currentUserUid, update } member.RoleWithOpRanges = roleAndOpRanges - // 如果是空间管理员,则自动添加内置的空间管理员角色 - if isNamespaceAdmin { - m.FixMemberWithNamespaceAdmin(ctx, member, namespaceUid) + // 如果是项目管理员,则自动添加内置的项目管理员角色 + if isProjectAdmin { + m.FixMemberWithProjectAdmin(ctx, member, projectUid) + } + + if err := m.repo.ReplaceOpPermissionsInMember(ctx, updateMemberUid, projectManagePermissions); err != nil { + return fmt.Errorf("replace op permissions in member failed: %v", err) } tx := m.tx.BeginTX(ctx) @@ -360,17 +363,10 @@ func (m *MemberUsecase) DelMember(ctx context.Context, currentUserUid, memberUid if err != nil { return fmt.Errorf("get member failed: %v", err) } - // 检查空间是否归档/删除 - if err := m.namespaceUsecase.isNamespaceActive(ctx, member.NamespaceUID); err != nil { + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, member.ProjectUID); err != nil { return fmt.Errorf("delete member error: %v", err) } - - // 检查当前用户有空间管理员权限 - if isAdmin, err := m.opPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, currentUserUid, member.NamespaceUID); err != nil { - return fmt.Errorf("check user is namespace admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not namespace admin") - } } tx := m.tx.BeginTX(ctx) diff --git a/internal/dms/biz/member_group.go b/internal/dms/biz/member_group.go new file mode 100644 index 000000000..d1652cd74 --- /dev/null +++ b/internal/dms/biz/member_group.go @@ -0,0 +1,232 @@ +package biz + +import ( + "context" + "fmt" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" +) + +type MemberGroup struct { + Base + + IsProjectAdmin bool + UID string + Name string + ProjectUID string + UserUids []string + Users []UIdWithName + RoleWithOpRanges []MemberRoleWithOpRange + OpPermissions []OpPermission + ProjectManagePermissions []string +} + +type MemberGroupRepo interface { + ListMemberGroups(ctx context.Context, opt *ListMemberGroupsOption) (memberGroups []*MemberGroup, total int64, err error) + GetMemberGroup(ctx context.Context, memberGroupId string) (*MemberGroup, error) + CreateMemberGroup(ctx context.Context, mg *MemberGroup) error + UpdateMemberGroup(ctx context.Context, mg *MemberGroup) error + DeleteMemberGroup(ctx context.Context, memberGroupId string) error + GetMemberGroupsByUserIDAndProjectID(ctx context.Context, userID, projectID string) ([]*MemberGroup, error) + ReplaceOpPermissionsInMemberGroup(ctx context.Context, memberUid string, opPermissionUids []string) error +} + +type MemberGroupUsecase struct { + tx TransactionGenerator + repo MemberGroupRepo + userUsecase *UserUsecase + roleUsecase *RoleUsecase + dbServiceUsecase *DBServiceUsecase + opPermissionVerifyUsecase *OpPermissionVerifyUsecase + projectUsecase *ProjectUsecase + memberUsecase *MemberUsecase + pluginUsecase *PluginUsecase + log *utilLog.Helper +} + +func NewMemberGroupUsecase(log utilLog.Logger, tx TransactionGenerator, repo MemberGroupRepo, + userUsecase *UserUsecase, + roleUsecase *RoleUsecase, + dbServiceUsecase *DBServiceUsecase, + opPermissionVerifyUsecase *OpPermissionVerifyUsecase, + projectUsecase *ProjectUsecase, + memberUsecase *MemberUsecase, + pluginUsecase *PluginUsecase) *MemberGroupUsecase { + return &MemberGroupUsecase{ + tx: tx, + repo: repo, + userUsecase: userUsecase, + roleUsecase: roleUsecase, + dbServiceUsecase: dbServiceUsecase, + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + projectUsecase: projectUsecase, + pluginUsecase: pluginUsecase, + memberUsecase: memberUsecase, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.member_group")), + } +} + +type ListMemberGroupsOption struct { + PageNumber uint32 + LimitPerPage uint32 + OrderBy MemberGroupField + FilterByOptions pkgConst.FilterOptions +} + +func (m *MemberGroupUsecase) ListMemberGroups(ctx context.Context, option *ListMemberGroupsOption, projectUid string) ([]*MemberGroup, int64, error) { + members, total, err := m.repo.ListMemberGroups(ctx, option) + if err != nil { + return nil, 0, fmt.Errorf("list member groups failed: %v", err) + } + + return members, total, nil +} + +func (m *MemberGroupUsecase) IsMemberGroupProjectAdmin(ctx context.Context, memberGroupUid string) (bool, error) { + member, err := m.repo.GetMemberGroup(ctx, memberGroupUid) + if err != nil { + return false, fmt.Errorf("get member group failed: %v", err) + } + + for _, r := range member.RoleWithOpRanges { + if r.RoleUID == pkgConst.UIDOfRoleProjectAdmin { + return true, nil + } + } + + return false, nil +} + +func (m *MemberGroupUsecase) GetMemberGroup(ctx context.Context, memberGroupUid, projectUid string) (*MemberGroup, error) { + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, projectUid); err != nil { + return nil, fmt.Errorf("get member groups error: %v", err) + } + + return m.repo.GetMemberGroup(ctx, memberGroupUid) +} + +func (m *MemberGroupUsecase) CreateMemberGroup(ctx context.Context, currentUserUid string, mg *MemberGroup) (string, error) { + // check + if err := m.checkMemberGroupBeforeUpsert(ctx, currentUserUid, mg); err != nil { + return "", fmt.Errorf("create member group error: %v", err) + } + + uid, err := pkgRand.GenStrUid() + if err != nil { + return "", err + } + mg.UID = uid + + if mg.IsProjectAdmin { + mg.RoleWithOpRanges = append(mg.RoleWithOpRanges, MemberRoleWithOpRange{ + RoleUID: pkgConst.UIDOfRoleProjectAdmin, + OpRangeType: OpRangeTypeProject, + RangeUIDs: []string{mg.ProjectUID}, + }) + } + + if err = m.repo.CreateMemberGroup(ctx, mg); err != nil { + return "", fmt.Errorf("save member group failed: %v", err) + } + if err = m.repo.ReplaceOpPermissionsInMemberGroup(ctx, uid, mg.ProjectManagePermissions); err != nil { + return "", fmt.Errorf("replace op permissions in member group failed: %v", err) + } + + return uid, nil + +} + +func (m *MemberGroupUsecase) checkMemberGroupBeforeUpsert(ctx context.Context, currentUserUid string, mg *MemberGroup) error { + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, mg.ProjectUID); err != nil { + return fmt.Errorf("create member error: %v", err) + } + // 检查成员组成员用户存在 + if exist, err := m.userUsecase.CheckUserExist(ctx, mg.UserUids); err != nil { + return fmt.Errorf("check user exist failed: %v", err) + } else if !exist { + return fmt.Errorf("user not exist") + } + + return m.memberUsecase.CheckRoleAndOpRanges(ctx, mg.RoleWithOpRanges) +} + +func (m *MemberGroupUsecase) UpdateMemberGroup(ctx context.Context, currentUserUid string, mg *MemberGroup) error { + // check + if err := m.checkMemberGroupBeforeUpsert(ctx, currentUserUid, mg); err != nil { + return fmt.Errorf("update member group error: %v", err) + } + + memberGroup, err := m.GetMemberGroup(ctx, mg.UID, mg.ProjectUID) + if err != nil { + return err + } + + if mg.IsProjectAdmin { + mg.RoleWithOpRanges = append(mg.RoleWithOpRanges, MemberRoleWithOpRange{ + RoleUID: pkgConst.UIDOfRoleProjectAdmin, + OpRangeType: OpRangeTypeProject, + RangeUIDs: []string{mg.ProjectUID}, + }) + } + + mg.UID = memberGroup.UID + mg.Name = memberGroup.Name + mg.CreatedAt = memberGroup.CreatedAt + tx := m.tx.BeginTX(ctx) + defer func() { + if err != nil { + err = tx.RollbackWithError(m.log, err) + } + }() + if err := m.repo.ReplaceOpPermissionsInMemberGroup(ctx, memberGroup.UID, mg.ProjectManagePermissions); err != nil { + return fmt.Errorf("replace op permissions in member failed: %v", err) + } + if err = m.repo.UpdateMemberGroup(tx, mg); err != nil { + return fmt.Errorf("update member group failed: %v", err) + } + // 调用其他服务对成员组进行更新后处理 + if err := m.pluginUsecase.UpdateMemberGroupAfterHandle(tx, mg.UID, mg.UserUids); err != nil { + return err + } + + if err := tx.Commit(m.log); err != nil { + return fmt.Errorf("commit tx failed: %v", err) + } + return nil +} + +func (m *MemberGroupUsecase) DeleteMemberGroup(ctx context.Context, currentUserUid, memberGroupUid, projectUid string) (err error) { + // check + { + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, projectUid); err != nil { + return fmt.Errorf("update member error: %v", err) + } + } + err = m.repo.DeleteMemberGroup(ctx, memberGroupUid) + if err != nil { + return err + } + // 调用其他服务对成员组进行删除后处理 + if err := m.pluginUsecase.DelMemberGroupAfterHandle(ctx, memberGroupUid); err != nil { + return err + } + return nil +} + +func (m *MemberGroupUsecase) GetMemberGroupsByUserIDAndProjectID(ctx context.Context, userID, projectID string) ([]*MemberGroup, error) { + // 检查项目是否归档/删除 + if err := m.projectUsecase.isProjectActive(ctx, projectID); err != nil { + return nil, fmt.Errorf("get member groups error: %v", err) + } + memberGroups, err := m.repo.GetMemberGroupsByUserIDAndProjectID(ctx, userID, projectID) + if err != nil { + return nil, fmt.Errorf("get member groups failed: %v", err) + } + + return memberGroups, err +} diff --git a/internal/dms/biz/namespace.go b/internal/dms/biz/namespace.go deleted file mode 100644 index 8b99eff36..000000000 --- a/internal/dms/biz/namespace.go +++ /dev/null @@ -1,129 +0,0 @@ -package biz - -import ( - "context" - "errors" - "fmt" - "time" - - pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" - pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" - pkgRand "github.com/actiontech/dms/pkg/rand" - - utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" -) - -type NamespaceStatus string - -const ( - NamespaceStatusArchived NamespaceStatus = "archived" - NamespaceStatusActive NamespaceStatus = "active" - NamespaceStatusUnknown NamespaceStatus = "unknown" -) - -type Namespace struct { - Base - - UID string - Name string - Desc string - CreateUserUID string - CreateTime time.Time - Status NamespaceStatus -} - -func NewNamespace(createUserUID, name, desc string) (*Namespace, error) { - uid, err := pkgRand.GenStrUid() - if err != nil { - return nil, err - } - return &Namespace{ - UID: uid, - Name: name, - Desc: desc, - Status: NamespaceStatusActive, - CreateUserUID: createUserUID, - }, nil -} - -func initNamespaces() []*Namespace { - return []*Namespace{ - { - UID: pkgConst.UIDOfNamespaceDefault, - Name: "default", - Desc: "default namespace", - Status: NamespaceStatusActive, - CreateUserUID: pkgConst.UIDOfUserAdmin, - }, - } -} - -type NamespaceRepo interface { - SaveNamespace(ctx context.Context, namespace *Namespace) error - ListNamespaces(ctx context.Context, opt *ListNamespacesOption, currentUserUID string) (namespaces []*Namespace, total int64, err error) - GetNamespace(ctx context.Context, namespaceUid string) (*Namespace, error) - GetNamespaceByName(ctx context.Context, namespaceName string) (*Namespace, error) - UpdateNamespace(ctx context.Context, u *Namespace) error - DelNamespace(ctx context.Context, namespaceUid string) error -} - -type NamespaceUsecase struct { - tx TransactionGenerator - repo NamespaceRepo - memberUsecase *MemberUsecase - opPermissionVerifyUsecase *OpPermissionVerifyUsecase - pluginUsecase *PluginUsecase - log *utilLog.Helper -} - -func NewNamespaceUsecase(log utilLog.Logger, tx TransactionGenerator, repo NamespaceRepo, memberUsecase *MemberUsecase, - opPermissionVerifyUsecase *OpPermissionVerifyUsecase, pluginUsecase *PluginUsecase) *NamespaceUsecase { - return &NamespaceUsecase{ - tx: tx, - repo: repo, - log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.namespace")), - memberUsecase: memberUsecase, - pluginUsecase: pluginUsecase, - opPermissionVerifyUsecase: opPermissionVerifyUsecase, - } -} - -type ListNamespacesOption struct { - PageNumber uint32 - LimitPerPage uint32 - OrderBy NamespaceField - FilterBy []pkgConst.FilterCondition -} - -func (d *NamespaceUsecase) ListNamespace(ctx context.Context, option *ListNamespacesOption, currentUserUid string) (namespaces []*Namespace, total int64, err error) { - namespaces, total, err = d.repo.ListNamespaces(ctx, option, currentUserUid) - if err != nil { - return nil, 0, fmt.Errorf("list namespaces failed: %v", err) - } - - return namespaces, total, nil -} - -func (d *NamespaceUsecase) InitNamespaces(ctx context.Context) (err error) { - for _, n := range initNamespaces() { - - _, err := d.GetNamespace(ctx, n.UID) - // already exist - if err == nil { - continue - } - - // error, return directly - if !errors.Is(err, pkgErr.ErrStorageNoData) { - return fmt.Errorf("failed to get namespace: %v", err) - } - - // not exist, then create it. - if err := d.CreateNamespace(ctx, n, pkgConst.UIDOfUserAdmin); err != nil { - return fmt.Errorf("failed to init namespace: %v", err) - } - - } - d.log.Debug("init namespace success") - return nil -} diff --git a/internal/dms/biz/namespace_ce.go b/internal/dms/biz/namespace_ce.go deleted file mode 100644 index 89e07ef25..000000000 --- a/internal/dms/biz/namespace_ce.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build !enterprise - -package biz - -import ( - "context" - "errors" -) - -var errNotSupportNamespace = errors.New("namespace related functions are enterprise version functions") - -func (d *NamespaceUsecase) CreateNamespace(ctx context.Context, namespace *Namespace, createUserUID string) (err error) { - return errNotSupportNamespace -} - -func (d *NamespaceUsecase) GetNamespace(ctx context.Context, namespaceUid string) (*Namespace, error) { - return nil, errNotSupportNamespace -} - -func (d *NamespaceUsecase) GetNamespaceByName(ctx context.Context, namespaceName string) (*Namespace, error) { - return nil, errNotSupportNamespace -} - -func (d *NamespaceUsecase) UpdateNamespaceDesc(ctx context.Context, currentUserUid, namespaceUid string, desc *string) (err error) { - - return errNotSupportNamespace -} - -func (d *NamespaceUsecase) ArchivedNamespace(ctx context.Context, currentUserUid, namespaceUid string, archived bool) (err error) { - - return errNotSupportNamespace -} - -func (d *NamespaceUsecase) DeleteNamespace(ctx context.Context, currentUserUid, namespaceUid string) (err error) { - return errNotSupportNamespace -} - -func (d *NamespaceUsecase) isNamespaceActive(ctx context.Context, namespaceUid string) error { - return nil -} diff --git a/internal/dms/biz/node.go b/internal/dms/biz/node.go index 52750e2ff..738978ad1 100644 --- a/internal/dms/biz/node.go +++ b/internal/dms/biz/node.go @@ -1,8 +1,25 @@ package biz -import "time" +import ( + "sync" + "time" +) type Base struct { CreatedAt time.Time UpdatedAt time.Time } + +type UIdWithName struct { + Uid string `json:"uid"` + Name string `json:"name"` +} + +// 数据源、用户缓存 +var uidWithNameCacheCache UidWithNameCacheCache + +type UidWithNameCacheCache struct { + ulock sync.Mutex + UserCache map[string] /*uid*/ UIdWithName + DBCache map[string] /*uid*/ UIdWithName +} diff --git a/internal/dms/biz/notification.go b/internal/dms/biz/notification.go index 10ea80a36..d002292eb 100644 --- a/internal/dms/biz/notification.go +++ b/internal/dms/biz/notification.go @@ -76,8 +76,9 @@ func (n *EmailNotifier) Notify(ctx context.Context, notificationSubject, notific port, _ := strconv.Atoi(smtpC.Port) dialer := gomail.NewDialer(smtpC.Host, port, smtpC.Username, smtpC.Password) - dialer.TLSConfig = &tls.Config{InsecureSkipVerify: smtpC.IsSkipVerify} - + if smtpC.IsSkipVerify { + dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true} + } if err := dialer.DialAndSend(message); err != nil { return fmt.Errorf("send email to %v error: %v", emails, err) } diff --git a/internal/dms/biz/notify_config.go b/internal/dms/biz/notify_config.go index 7b53caaf0..37b73b282 100644 --- a/internal/dms/biz/notify_config.go +++ b/internal/dms/biz/notify_config.go @@ -440,8 +440,8 @@ func (d *WebHookConfigurationUsecase) TestWebHookConfiguration(ctx context.Conte if !webhookC.Enable { return fmt.Errorf("webhook notice is not enabled") } - // TODO 测试webhook配置可用性 - return err + + return d.webhookSendRequest(ctx, "hello") } func (d *WebHookConfigurationUsecase) SendWebHookMessage(ctx context.Context, triggerEventType string /*TODO validate TriggerEventType*/, message string) error { diff --git a/internal/dms/biz/oauth2_configuration.go b/internal/dms/biz/oauth2_configuration.go index 0e15f026f..2c77bbb05 100644 --- a/internal/dms/biz/oauth2_configuration.go +++ b/internal/dms/biz/oauth2_configuration.go @@ -2,31 +2,50 @@ package biz import ( "context" + "fmt" + "net/url" + "strconv" + "strings" + "time" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" pkgRand "github.com/actiontech/dms/pkg/rand" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + jsoniter "github.com/json-iterator/go" ) +const BackChannelLogoutUri = "/backchannel_logout" + type Oauth2Configuration struct { Base - UID string - EnableOauth2 bool - ClientID string - ClientKey string - ClientSecret string - ClientHost string - ServerAuthUrl string - ServerTokenUrl string - ServerUserIdUrl string - Scopes []string - AccessTokenTag string - UserIdTag string - LoginTip string -} - -func initOauth2Configuration() (*Oauth2Configuration, error) { + UID string + EnableOauth2 bool + SkipCheckState bool + EnableManuallyBind bool + AutoBindSameNameUser bool + AutoCreateUser bool + AutoCreateUserPWD string + AutoCreateUserSecret string + ClientID string + ClientKey string + ClientSecret string + ClientHost string + ServerAuthUrl string + ServerTokenUrl string + ServerUserIdUrl string + ServerLogoutUrl string + Scopes []string + AccessTokenTag string + UserIdTag string + UserEmailTag string + UserWeChatTag string + LoginPermExpr string + LoginTip string +} + +func initOauth2Configuration() (*Oauth2Configuration, error) { //nolint uid, err := pkgRand.GenStrUid() if err != nil { return nil, err @@ -42,17 +61,125 @@ type Oauth2ConfigurationRepo interface { } type Oauth2ConfigurationUsecase struct { - tx TransactionGenerator - repo Oauth2ConfigurationRepo - userUsecase *UserUsecase - log *utilLog.Helper + tx TransactionGenerator + repo Oauth2ConfigurationRepo + userUsecase *UserUsecase + oauth2SessionUsecase *OAuth2SessionUsecase + log *utilLog.Helper } -func NewOauth2ConfigurationUsecase(log utilLog.Logger, tx TransactionGenerator, repo Oauth2ConfigurationRepo, userUsecase *UserUsecase) *Oauth2ConfigurationUsecase { +func NewOauth2ConfigurationUsecase(log utilLog.Logger, tx TransactionGenerator, repo Oauth2ConfigurationRepo, userUsecase *UserUsecase, oauth2SessionUsecase *OAuth2SessionUsecase) *Oauth2ConfigurationUsecase { return &Oauth2ConfigurationUsecase{ - tx: tx, - repo: repo, - userUsecase: userUsecase, - log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.oauth2_configuration")), + tx: tx, + repo: repo, + userUsecase: userUsecase, + oauth2SessionUsecase: oauth2SessionUsecase, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.oauth2_configuration")), + } +} + +// the path should formate like path.to.parameter or path.to.slice.0.parameter +func ParseJsonByPath(jsonBytes []byte, jsonPath string) (jsoniter.Any, error) { + pathSlice := strings.Split(jsonPath, ".") + if len(pathSlice) == 0 { + return nil, fmt.Errorf("empty json path") + } + var jsonObject jsoniter.Any = jsoniter.Get(jsonBytes) + for _, path := range pathSlice { + if index, err := strconv.Atoi(path); err == nil { + jsonObject = jsonObject.Get(index) + } else { + jsonObject = jsonObject.Get(path) + } + if jsonObject.LastError() != nil { + return nil, jsonObject.LastError() + } + } + return jsonObject, nil +} + +type CallbackRedirectData struct { + UserExist bool + DMSToken string + Oauth2Token string + RefreshToken string + Error string + State string + uri string +} + +var oauthRedirectPrefixState = "target=" + +func (c CallbackRedirectData) Generate() string { + redirectUrl := fmt.Sprintf("%v/user/bind", c.uri) + params := url.Values{} + params.Set("user_exist", strconv.FormatBool(c.UserExist)) + if c.DMSToken != "" { + params.Set("dms_token", c.DMSToken) + } + if c.Oauth2Token != "" { + params.Set("oauth2_token", c.Oauth2Token) + } + if c.RefreshToken != "" { + params.Set("refresh_token", c.RefreshToken) + } + if c.Error != "" { + params.Set("error", c.Error) } + // Extract the original target path from the OAuth2 State parameter for post-login redirection + // Scenario Description: The State parameter stores the original access path before login (in the format "target=/project/700300/exec-workflow/1934557787224805376") + // Processing Logic: + // 1. Split the State string using the prefix separator `oauthRedirectPrefixState` + // 2. If there is valid content after splitting (the part at index 1), extract it as the target path + // 3. Store the extracted path in `params` so that the front-end can read the parameter and implement automatic redirection to the original page after login + if val := strings.Split(c.State, oauthRedirectPrefixState); len(val) > 1 { + params.Set("target", val[1]) + } + return fmt.Sprintf("%v?%v", redirectUrl, params.Encode()) +} + +type ClaimsInfo struct { + UserId string `json:"user_id"` // dms用户ID + Iat float64 `json:"iat"` // 第三方AccessToken 签发时间 (Issued At),Unix 时间戳 + Exp float64 `json:"exp"` // 第三方AccessToken 过期时间 (Expiration Time),Unix 时间戳 + Sub string `json:"sub"` // 第三方AccessToken 主题 (Subject),通常是用户ID或唯一标识符 + Sid string `json:"sid"` // 第三方AccessToken 会话ID (Session ID),用于跟踪用户会话 + RefreshIat float64 `json:"refresh_iat"` // 第三方RefreshToken 签发时间 (Issued At),Unix 时间戳 + RefreshExp float64 `json:"refresh_exp"` // 第三方RefreshToken 过期时间 (Expiration Time),Unix 时间戳 +} + +func (c *ClaimsInfo) DmsToken() (token string, cookieExp time.Duration, err error) { + c.setDefaults() + // 为了在第三方会话“快过期”时去刷新第三方token,故此时(通过OAuth2登录)签发的DmsToken有效期为第三方平台的0.9 + cookieExp = time.Duration((c.Exp-c.Iat)*0.9) * time.Second + token, err = jwt.GenJwtToken(jwt.WithUserId(c.UserId), jwt.WithExpiredTime(cookieExp), jwt.WithSub(c.Sub), jwt.WithSid(c.Sid)) + return +} + +func (c *ClaimsInfo) DmsRefreshToken() (token string, cookieExp time.Duration, err error) { + c.setDefaults() + // cookie有效期更久,和第三方refresh token有效期保持一致 + // 这样在DmsRefreshToken过期时,cookie仍可获取,用于注销第三方会话 + cookieExp = time.Duration(c.RefreshExp-c.RefreshIat) * time.Second + token, err = jwt.GenRefreshToken(jwt.WithUserId(c.UserId), jwt.WithExpiredTime(time.Duration(c.Exp-c.Iat)*time.Second), jwt.WithSub(c.Sub), jwt.WithSid(c.Sid)) + return +} + +func (c *ClaimsInfo) setDefaults() { + now := time.Now() + + if c.Iat == 0 { + c.Iat = float64(now.Unix()) + } + if c.Exp == 0 { + c.Exp = float64(now.Add(jwt.DefaultDmsTokenExpHours * time.Hour).Unix()) + } + if c.RefreshIat == 0 { + c.RefreshIat = c.Iat + } + if c.RefreshExp == 0 { + c.RefreshExp = c.Exp + } + + return } diff --git a/internal/dms/biz/oauth2_configuration_ce.go b/internal/dms/biz/oauth2_configuration_ce.go index 5576e97af..e0f6bbfea 100644 --- a/internal/dms/biz/oauth2_configuration_ce.go +++ b/internal/dms/biz/oauth2_configuration_ce.go @@ -5,12 +5,15 @@ package biz import ( "context" "errors" + + "github.com/labstack/echo/v4" + + v1 "github.com/actiontech/dms/api/dms/service/v1" ) var errNotSupportOauth2 = errors.New("oauth2 related functions are enterprise version functions") -func (d *Oauth2ConfigurationUsecase) UpdateOauth2Configuration(ctx context.Context, enableOauth2 *bool, clientID, clientKey, clientHost, serverAuthUrl, serverTokenUrl, serverUserIdUrl, - accessTokenTag, userIdTag, loginTip *string, scopes *[]string) error { +func (d *Oauth2ConfigurationUsecase) UpdateOauth2Configuration(ctx context.Context, conf v1.Oauth2Configuration) error { return errNotSupportOauth2 } @@ -19,18 +22,39 @@ func (d *Oauth2ConfigurationUsecase) GetOauth2Configuration(ctx context.Context) return nil, false, errNotSupportOauth2 } -func (d *Oauth2ConfigurationUsecase) GenOauth2LinkURI(ctx context.Context) (uri string, err error) { +func (d *Oauth2ConfigurationUsecase) GenOauth2LinkURI(ctx context.Context, target string) (uri string, err error) { return "", errNotSupportOauth2 } -func (d *Oauth2ConfigurationUsecase) GenerateCallbackUri(ctx context.Context, state, code string) (string, error) { - return "", errNotSupportOauth2 +func (d *Oauth2ConfigurationUsecase) GenerateCallbackUri(ctx context.Context, state, code string) (data *CallbackRedirectData, claims *ClaimsInfo, err error) { + return nil, nil, errNotSupportOauth2 } -func (d *Oauth2ConfigurationUsecase) getOauth2UserID(conf *Oauth2Configuration, token string) (userID string, err error) { - return "", errNotSupportOauth2 +func (d *Oauth2ConfigurationUsecase) BindOauth2User(ctx context.Context, oauth2Token, idToken, userName, password string) (claims *ClaimsInfo, err error) { + return nil, errNotSupportOauth2 } -func (d *Oauth2ConfigurationUsecase) BindOauth2User(ctx context.Context, oauth2Token, userName, password string) (token string, err error) { - return "", errNotSupportOauth2 +func (d *Oauth2ConfigurationUsecase) Logout(ctx context.Context, sub, sid string) (string, error) { + return "", nil +} + +func (d *Oauth2ConfigurationUsecase) BackendLogout(ctx context.Context, sub, sid string) error { + return nil +} + +func (d *Oauth2ConfigurationUsecase) RefreshOauth2Token(ctx context.Context, userUid, sub, sid string) (claims *ClaimsInfo, err error) { + return nil, errNotSupportOauth2 +} + +func (d *Oauth2ConfigurationUsecase) BackChannelLogout(ctx context.Context, logoutToken string) (err error) { + return errNotSupportOauth2 +} + +func (d *Oauth2ConfigurationUsecase) CheckBackChannelLogoutEvent() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + // do nothing + return next(c) + } + } } diff --git a/internal/dms/biz/oauth2_configuration_test.go b/internal/dms/biz/oauth2_configuration_test.go new file mode 100644 index 000000000..462499dc4 --- /dev/null +++ b/internal/dms/biz/oauth2_configuration_test.go @@ -0,0 +1,49 @@ +package biz + +import "testing" + +func TestParseJsonByPath(t *testing.T) { + + // Sample JSON + json := `{"name":"John", "age":30, "Hobbies":["football","tennis"], "children":[{"Name":"Emma","age":5},{"Name":"Michael","age":2}]}` + + // Test parsing simple field + value, err := ParseJsonByPath([]byte(json), "name") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if value.ToString() != "John" { + t.Errorf("Expected name to be John, got %s", value.ToString()) + } + + // Test parsing array element + value, err = ParseJsonByPath([]byte(json), "Hobbies.0") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if value.ToString() != "football" { + t.Errorf("Expected first hobby to be football, got %s", value.ToString()) + } + + // Test parsing nested object + value, err = ParseJsonByPath([]byte(json), "children.0.Name") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + if value.ToString() != "Emma" { + t.Errorf("Expected first child name to be Emma, got %s", value.ToString()) + } + + // Test invalid path + _, err = ParseJsonByPath([]byte(json), "invalidField") + if err == nil { + t.Error("Expected error for invalid path") + } + + // Test empty path + _, err = ParseJsonByPath([]byte(json), "") + if err == nil { + t.Error("Expected error for empty path") + } + +} diff --git a/internal/dms/biz/oauth2_session.go b/internal/dms/biz/oauth2_session.go new file mode 100644 index 000000000..55f23c435 --- /dev/null +++ b/internal/dms/biz/oauth2_session.go @@ -0,0 +1,66 @@ +package biz + +import ( + "context" + "time" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" +) + +type OAuth2Session struct { + Base + + UID string + UserUID string + Sub string + Sid string + IdToken string + RefreshToken string + LastLogoutEvent string // 记录第三方注销事件的时间戳,有值意味着该会话被注销过 + DeleteAfter time.Time // 记录保留时间,在此时间之后将删除该记录 +} + +func newOAuth2Session(UserUID, Sub, Sid, IdToken, RefreshToken string, deleteAfter time.Time) (*OAuth2Session, error) { + uid, err := pkgRand.GenStrUid() + if err != nil { + return nil, err + } + return &OAuth2Session{ + UID: uid, + UserUID: UserUID, + Sub: Sub, + Sid: Sid, + IdToken: IdToken, + RefreshToken: RefreshToken, + DeleteAfter: deleteAfter, + }, nil +} + +func (u *OAuth2Session) GetUID() string { + return u.UID +} + +type OAuth2SessionRepo interface { + SaveSession(ctx context.Context, s *OAuth2Session) error + GetSessions(ctx context.Context, conditions []pkgConst.FilterCondition) ([]*OAuth2Session, error) + GetSessionBySubSid(ctx context.Context, sub, sid string) (session *OAuth2Session, exist bool, err error) + UpdateUserUidBySub(ctx context.Context, userid, sub string) error + UpdateLogoutEvent(ctx context.Context, Sub, Sid, logoutIat string) error + DeleteExpiredSessions(ctx context.Context) error +} + +type OAuth2SessionUsecase struct { + tx TransactionGenerator + repo OAuth2SessionRepo + log *utilLog.Helper +} + +func NewOAuth2SessionUsecase(log utilLog.Logger, tx TransactionGenerator, repo OAuth2SessionRepo) *OAuth2SessionUsecase { + return &OAuth2SessionUsecase{ + tx: tx, + repo: repo, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.OAuth2Session")), + } +} diff --git a/internal/dms/biz/oauth2_session_ce.go b/internal/dms/biz/oauth2_session_ce.go new file mode 100644 index 000000000..529de85e7 --- /dev/null +++ b/internal/dms/biz/oauth2_session_ce.go @@ -0,0 +1,7 @@ +//go:build !enterprise + +package biz + +func (d *OAuth2SessionUsecase) DeleteExpiredSessions() { + return +} diff --git a/internal/dms/biz/op_permission.go b/internal/dms/biz/op_permission.go index 2cb2a15fb..2a236d82f 100644 --- a/internal/dms/biz/op_permission.go +++ b/internal/dms/biz/op_permission.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + v1 "github.com/actiontech/dms/api/dms/service/v1" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" @@ -16,8 +17,10 @@ type OpPermission struct { UID string Name string + Module Module RangeType OpRangeType Desc string + Service v1.Service } func (o *OpPermission) GetUID() string { @@ -32,93 +35,331 @@ func (o OpRangeType) String() string { const ( OpRangeTypeGlobal OpRangeType = "global" - OpRangeTypeNamespace OpRangeType = "namespace" + OpRangeTypeProject OpRangeType = "project" OpRangeTypeDBService OpRangeType = "db_service" ) +type Module string + +const ( + SQLWorkflow Module = "SQL工单" + SQLManage = "SQL管控" + SQLDataSource = "数据源管理" + SQLWorkBench = "SQL工作台" + DataExport = "数据导出" + QuickAudit = "快捷审核" + VersionManage = "版本管理" + CICDIntegration = "CI/CD集成" + IDEAudit = "IDE审核" + SQLOptimization = "SQL优化" + AuditRuleTemplate = "审核规则模板" + ApprovalFlowTemplate = "审批流模板管理" + MemberMange = "成员与权限" + PushRule = "推送规则" + AuditSQLWhiteList = "审核SQL例外" + SQLMangeWhiteList = "管控SQL例外" + RoleMange = "角色管理" + DesensitizationRule = "脱敏规则" + AccountManagement = "账号管理" +) + func ParseOpRangeType(t string) (OpRangeType, error) { switch t { case OpRangeTypeGlobal.String(): return OpRangeTypeGlobal, nil - case OpRangeTypeNamespace.String(): - return OpRangeTypeNamespace, nil + case OpRangeTypeProject.String(): + return OpRangeTypeProject, nil case OpRangeTypeDBService.String(): return OpRangeTypeDBService, nil default: - return "", errors.New("invalid op range type") + return "", nil } } func initOpPermission() []*OpPermission { return []*OpPermission{ { - UID: pkgConst.UIDOfOpPermissionCreateNamespace, - Name: "创建空间", + UID: pkgConst.UIDOfOpPermissionGlobalView, + Name: "审计管理员", + RangeType: OpRangeTypeGlobal, + Desc: "负责系统操作审计、数据合规检查等工作", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionGlobalManagement, + Name: "系统管理员", + RangeType: OpRangeTypeGlobal, + Desc: "具备系统最高权限,可进行系统配置、用户管理等操作", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionCreateProject, + Name: "项目总监", // todo i18n 返回时会根据uid国际化,name、desc已弃用;数据库name字段是唯一键,故暂时保留 + RangeType: OpRangeTypeGlobal, + Desc: "创建项目、配置项目资源", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOrdinaryUser, + Name: "普通用户", // todo i18n 返回时会根据uid国际化,name、desc已弃用;数据库name字段是唯一键,故暂时保留 RangeType: OpRangeTypeGlobal, - Desc: "创建空间;创建空间的用户自动拥有该空间管理权限", + Desc: "基础功能操作权限,可进行日常业务操作", + Service: v1.ServiceSQLE, }, { - UID: pkgConst.UIDOfOpPermissionNamespaceAdmin, - Name: "空间管理", - RangeType: OpRangeTypeNamespace, - Desc: "空间管理;拥有该权限的用户可以管理空间下的所有资源", + UID: pkgConst.UIDOfOpPermissionProjectAdmin, + Name: "项目管理", + RangeType: OpRangeTypeProject, + Desc: "项目管理;拥有该权限的用户可以管理项目下的所有资源", + Service: v1.ServiceSQLE, }, { UID: pkgConst.UIDOfOpPermissionCreateWorkflow, - Name: "创建/编辑工单", + Name: "创建上线工单", RangeType: OpRangeTypeDBService, + Module: SQLWorkflow, Desc: "创建/编辑工单;拥有该权限的用户可以创建/编辑工单", + Service: v1.ServiceSQLE, }, { UID: pkgConst.UIDOfOpPermissionAuditWorkflow, - Name: "审核/驳回工单", + Name: "审批上线工单", RangeType: OpRangeTypeDBService, + Module: SQLWorkflow, Desc: "审核/驳回工单;拥有该权限的用户可以审核/驳回工单", - }, - { - UID: pkgConst.UIDOfOpPermissionAuthDBServiceData, - Name: "授权数据源数据权限", - RangeType: OpRangeTypeDBService, - Desc: "授权数据源数据权限;拥有该权限的用户可以授权数据源数据权限", + Service: v1.ServiceSQLE, }, { UID: pkgConst.UIDOfOpPermissionExecuteWorkflow, - Name: "上线工单", + Name: "执行上线工单", RangeType: OpRangeTypeDBService, + Module: SQLWorkflow, Desc: "上线工单;拥有该权限的用户可以上线工单", + Service: v1.ServiceSQLE, }, { UID: pkgConst.UIDOfOpPermissionViewOthersWorkflow, - Name: "查看他人创建的工单", + Name: "查看所有工单", RangeType: OpRangeTypeDBService, + Module: SQLWorkflow, Desc: "查看他人创建的工单;拥有该权限的用户可以查看他人创建的工单", + Service: v1.ServiceSQLE, }, { UID: pkgConst.UIDOfOpPermissionSaveAuditPlan, - Name: "创建/编辑扫描任务", + Name: "配置SQL管控", RangeType: OpRangeTypeDBService, + Module: SQLManage, Desc: "创建/编辑扫描任务;拥有该权限的用户可以创建/编辑扫描任务", + Service: v1.ServiceSQLE, }, { UID: pkgConst.UIDOfOpPermissionViewOthersAuditPlan, - Name: "查看他人创建的扫描任务", + Name: "访问所有管控SQL", RangeType: OpRangeTypeDBService, + Module: SQLManage, Desc: "查看他人创建的扫描任务;拥有该权限的用户可以查看他人创建的扫描任务", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionViewSQLInsight, + Name: "查看性能洞察", + RangeType: OpRangeTypeDBService, + Module: SQLManage, + Desc: "查看性能洞察;拥有该权限的用户可以查看性能洞察的数据", + Service: v1.ServiceSQLE, }, { UID: pkgConst.UIDOfOpPermissionSQLQuery, - Name: "SQL查询", + Name: "SQL工作台操作权限", RangeType: OpRangeTypeDBService, + Module: SQLWorkBench, Desc: "SQL查询;拥有该权限的用户可以执行SQL查询", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionExportApprovalReject, + Name: "审批导出工单", + RangeType: OpRangeTypeDBService, + Module: DataExport, + Desc: "审批/驳回数据导出工单;拥有该权限的用户可以执行审批导出数据工单或者驳回导出数据工单", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionExportCreate, + Name: "创建导出工单", + RangeType: OpRangeTypeDBService, + Module: DataExport, + Desc: "创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionCreateOptimization, + Name: "创建智能调优", + RangeType: OpRangeTypeDBService, + Module: SQLOptimization, + Desc: "创建智能调优;拥有该权限的用户可以创建智能调优", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionViewOthersOptimization, + Name: "查看他人创建的智能调优", + RangeType: OpRangeTypeDBService, + Module: SQLOptimization, + Desc: "查看他人创建的智能调优;拥有该权限的用户可以查看他人创建的智能调优", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionCreatePipeline, + Name: "流水线增删改", + RangeType: OpRangeTypeDBService, + Module: CICDIntegration, + Desc: "配置流水线;拥有该权限的用户可以为数据源配置流水线", + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionViewOperationRecord, + Name: "查看所有操作记录", + RangeType: OpRangeTypeDBService, + Module: SQLWorkBench, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionViewExportTask, + Name: "查看所有导出任务", + RangeType: OpRangeTypeDBService, + Module: DataExport, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfPermissionViewQuickAuditRecord, + Name: "查看所有快捷审核记录", + RangeType: OpRangeTypeDBService, + Module: QuickAudit, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionViewIDEAuditRecord, + Name: "查看所有IDE审核记录", + RangeType: OpRangeTypeDBService, + Module: IDEAudit, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionViewVersionManage, + Name: "查看他人创建的版本记录", + RangeType: OpRangeTypeDBService, + Module: VersionManage, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIDOfOpPermissionVersionManage, + Name: "配置版本", + RangeType: OpRangeTypeDBService, + Module: VersionManage, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionViewPipeline, + Name: "查看所有流水线", + RangeType: OpRangeTypeDBService, + Module: CICDIntegration, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionManageProjectDataSource, + Name: "管理项目数据源", + RangeType: OpRangeTypeProject, + Module: SQLDataSource, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionManageAuditRuleTemplate, + Name: "管理审核规则模版", + RangeType: OpRangeTypeProject, + Module: AuditRuleTemplate, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionManageApprovalTemplate, + Name: "管理审批流程模版", + RangeType: OpRangeTypeProject, + Module: ApprovalFlowTemplate, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionManageMember, + Name: "管理成员与权限", + RangeType: OpRangeTypeProject, + Module: MemberMange, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionPushRule, + Name: "管理推送规则", + RangeType: OpRangeTypeProject, + Module: PushRule, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionMangeAuditSQLWhiteList, + Name: "审核SQL例外", + RangeType: OpRangeTypeProject, + Module: AuditSQLWhiteList, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionManageSQLMangeWhiteList, + Name: "管控SQL例外", + RangeType: OpRangeTypeProject, + Module: SQLMangeWhiteList, + Service: v1.ServiceSQLE, + }, + { + UID: pkgConst.UIdOfOpPermissionManageRoleMange, + Name: "角色管理权限", + RangeType: OpRangeTypeProject, + Module: RoleMange, + Service: v1.ServiceDMS, + }, + { + UID: pkgConst.UIdOfOpPermissionDesensitization, + Name: "配置脱敏任务", + RangeType: OpRangeTypeProject, + Module: DesensitizationRule, + Service: v1.ServiceDMS, + }, + { + UID: pkgConst.UIdOfOpPermissionMaskingAudit, + Name: "脱敏审核", + RangeType: OpRangeTypeProject, + Module: DesensitizationRule, + Service: v1.ServiceDMS, + }, + } +} + +func GetProxyOpPermission() map[string][]*OpPermission { + return map[string][]*OpPermission{ + "provision": { + { + UID: pkgConst.UIDOfOpPermissionAuthDBServiceData, + Name: "账号管理", + RangeType: OpRangeTypeProject, + Desc: "账号管理;拥有该权限的用户可以授权数据源数据权限", + Service: v1.ServiceDMS, + Module: AccountManagement, + }, }, } + } type ListOpPermissionsOption struct { - PageNumber uint32 - LimitPerPage uint32 - OrderBy OpPermissionField - FilterBy []pkgConst.FilterCondition + PageNumber uint32 + LimitPerPage uint32 + OrderBy OpPermissionField + FilterByOptions pkgConst.FilterOptions } type OpPermissionRepo interface { @@ -146,10 +387,10 @@ func NewOpPermissionUsecase(log utilLog.Logger, tx TransactionGenerator, repo Op } } -func (d *OpPermissionUsecase) InitOpPermissions(ctx context.Context) (err error) { - for _, op := range initOpPermission() { +func (d *OpPermissionUsecase) InitOpPermissions(ctx context.Context, opPermissions []*OpPermission) (err error) { + for _, opPermission := range opPermissions { - _, err := d.repo.GetOpPermission(ctx, op.GetUID()) + _, err := d.repo.GetOpPermission(ctx, opPermission.GetUID()) // already exist if err == nil { continue @@ -161,12 +402,12 @@ func (d *OpPermissionUsecase) InitOpPermissions(ctx context.Context) (err error) } // not exist, then create it - if err := d.repo.SaveOpPermission(ctx, op); err != nil { + if err := d.repo.SaveOpPermission(ctx, opPermission); err != nil { return fmt.Errorf("failed to init op permission: %w", err) } } - d.log.Debug("init op permissions success") + d.log.Debug("update op permissions success") return nil } @@ -198,11 +439,14 @@ func (d *OpPermissionUsecase) ListOpPermissions(ctx context.Context, opt *ListOp func (d *OpPermissionUsecase) ListUserOpPermissions(ctx context.Context, opt *ListOpPermissionsOption) (ops []*OpPermission, total int64, err error) { // 用户只能被赋予全局权限 - opt.FilterBy = append(opt.FilterBy, pkgConst.FilterCondition{ - Field: string(OpPermissionFieldRangeType), - Operator: pkgConst.FilterOperatorEqual, - Value: OpRangeTypeGlobal, - }) + opt.FilterByOptions.Groups = append(opt.FilterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(OpPermissionFieldRangeType), + Operator: pkgConst.FilterOperatorEqual, + Value: OpRangeTypeGlobal, + }, + )) ops, total, err = d.repo.ListOpPermissions(ctx, opt) if err != nil { @@ -212,19 +456,25 @@ func (d *OpPermissionUsecase) ListUserOpPermissions(ctx context.Context, opt *Li } func (d *OpPermissionUsecase) ListMemberOpPermissions(ctx context.Context, opt *ListOpPermissionsOption) (ops []*OpPermission, total int64, err error) { - // 成员属于空间,只能被赋予非全局权限 - opt.FilterBy = append(opt.FilterBy, pkgConst.FilterCondition{ - Field: string(OpPermissionFieldRangeType), - Operator: pkgConst.FilterOperatorNotEqual, - Value: OpRangeTypeGlobal, - }) - - // 设置成员权限时,有单独的“空间管理权限”选项代表空间权限,所以这里不返回空间权限 - opt.FilterBy = append(opt.FilterBy, pkgConst.FilterCondition{ - Field: string(OpPermissionFieldRangeType), - Operator: pkgConst.FilterOperatorNotEqual, - Value: OpRangeTypeNamespace, - }) + // 成员属于项目,只能被赋予非全局权限 + opt.FilterByOptions.Groups = append(opt.FilterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(OpPermissionFieldRangeType), + Operator: pkgConst.FilterOperatorNotEqual, + Value: OpRangeTypeGlobal, + }, + )) + + // 设置成员权限时,有单独的“项目管理权限”选项代表项目权限,所以这里不返回项目权限 + opt.FilterByOptions.Groups = append(opt.FilterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(OpPermissionFieldRangeType), + Operator: pkgConst.FilterOperatorNotEqual, + Value: OpRangeTypeProject, + }, + )) ops, total, err = d.repo.ListOpPermissions(ctx, opt) if err != nil { @@ -233,3 +483,25 @@ func (d *OpPermissionUsecase) ListMemberOpPermissions(ctx context.Context, opt * return ops, total, nil } + +func (d *OpPermissionUsecase) ListProjectOpPermissions(ctx context.Context, opt *ListOpPermissionsOption) (ops []*OpPermission, total int64, err error) { + opt.FilterByOptions.Groups = append(opt.FilterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(OpPermissionFieldRangeType), + Operator: pkgConst.FilterOperatorEqual, + Value: OpRangeTypeProject, + }, + pkgConst.FilterCondition{ + Field: string(OpPermissionFieldUID), + Operator: pkgConst.FilterOperatorNotEqual, + Value: pkgConst.UIDOfOpPermissionProjectAdmin, + }, + )) + + ops, total, err = d.repo.ListOpPermissions(ctx, opt) + if err != nil { + return nil, 0, fmt.Errorf("failed to list user op permissions: %v", err) + } + return ops, total, nil +} diff --git a/internal/dms/biz/op_permission_verify.go b/internal/dms/biz/op_permission_verify.go index c0b7b609e..1fde7fc29 100644 --- a/internal/dms/biz/op_permission_verify.go +++ b/internal/dms/biz/op_permission_verify.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" @@ -12,12 +13,17 @@ import ( ) type OpPermissionVerifyRepo interface { - IsUserHasOpPermissionInNamespace(ctx context.Context, userUid, namespaceUid, opPermissionUid string) (has bool, err error) - GetUserOpPermissionInNamespace(ctx context.Context, userUid, namespaceUid string) (opPermissionWithOpRanges []OpPermissionWithOpRange, err error) + IsUserHasOpPermissionInProject(ctx context.Context, userUid, projectUid, opPermissionUid string) (has bool, err error) + GetUserOpPermissionInProject(ctx context.Context, userUid, projectUid string) (opPermissionWithOpRanges []OpPermissionWithOpRange, err error) + GetOneOpPermissionInProject(ctx context.Context, userUid, projectUid, permissionId string) (opPermissionWithOpRanges []OpPermissionWithOpRange, err error) + GetUserProjectOpPermissionInProject(ctx context.Context, userUid, projectUid string) (opPermissionWithOpRanges []OpPermissionWithOpRange, err error) GetUserOpPermission(ctx context.Context, userUid string) (opPermissionWithOpRanges []OpPermissionWithOpRange, err error) + GetUserProjectOpPermission(ctx context.Context, userUid string) (opPermissionWithOpRanges []OpPermissionWithOpRange, err error) GetUserGlobalOpPermission(ctx context.Context, userUid string) (opPermissions []*OpPermission, err error) - GetUserNamespaceWithOpPermissions(ctx context.Context, userUid string) (namespaceWithPermission []NamespaceOpPermissionWithOpRange, err error) - ListMembersOpPermissionInNamespace(ctx context.Context, namespaceUid string, opt *ListMembersOpPermissionOption) (items []ListMembersOpPermissionItem, total int64, err error) + GetUserProjectWithOpPermissions(ctx context.Context, userUid string) (projectWithPermission []ProjectOpPermissionWithOpRange, err error) + ListUsersOpPermissionInProject(ctx context.Context, projectUid string, opt *ListMembersOpPermissionOption) (items []ListMembersOpPermissionItem, total int64, err error) + GetUserProject(ctx context.Context, userUid string) (projects []*Project, err error) + ListUsersInProject(ctx context.Context, projectUid string) (items []ListMembersOpPermissionItem, err error) } type OpPermissionVerifyUsecase struct { @@ -34,16 +40,16 @@ func NewOpPermissionVerifyUsecase(log utilLog.Logger, tx TransactionGenerator, r } } -func (o *OpPermissionVerifyUsecase) IsUserNamespaceAdmin(ctx context.Context, userUid, namespaceUid string) (bool, error) { +func (o *OpPermissionVerifyUsecase) IsUserProjectAdmin(ctx context.Context, userUid, projectUid string) (bool, error) { // 内置用户admin和sys拥有所有权限 switch userUid { case pkgConst.UIDOfUserAdmin, pkgConst.UIDOfUserSys: return true, nil default: } - has, err := o.repo.IsUserHasOpPermissionInNamespace(ctx, userUid, namespaceUid, pkgConst.UIDOfOpPermissionNamespaceAdmin) + has, err := o.repo.IsUserHasOpPermissionInProject(ctx, userUid, projectUid, pkgConst.UIDOfOpPermissionProjectAdmin) if err != nil { - return false, fmt.Errorf("failed to check user is namespace admin: %v", err) + return false, fmt.Errorf("failed to check user is project admin: %v", err) } return has, nil } @@ -58,48 +64,225 @@ func (o *OpPermissionVerifyUsecase) IsUserDMSAdmin(ctx context.Context, userUid } } +func (o *OpPermissionVerifyUsecase) HasGlobalManagementOrViewPermission(ctx context.Context, userUid string) (bool, error) { + ops, err := o.GetUserGlobalOpPermission(ctx, userUid) + if err != nil { + return false, err + } + + for _, op := range ops { + if op.OpPermissionUID == pkgConst.UIDOfOpPermissionGlobalManagement || op.OpPermissionUID == pkgConst.UIDOfOpPermissionGlobalView { + return true, nil + } + } + + return false, nil +} + +func (o *OpPermissionVerifyUsecase) CanOpGlobal(ctx context.Context, userUid string) (bool, error) { + isUserDMSAdmin, err := o.IsUserDMSAdmin(ctx, userUid) + if err != nil { + return false, err + } + if isUserDMSAdmin { + return true, nil + } + + ops, err := o.repo.GetUserGlobalOpPermission(ctx, userUid) + if err != nil { + return false, err + } + + for _, op := range ops { + if op.UID == pkgConst.UIDOfOpPermissionGlobalManagement { + return true, nil + } + } + + return false, nil +} + +func (o *OpPermissionVerifyUsecase) CanOpProject(ctx context.Context, userUid, projectUid string) (bool, error) { + canGlobalOp, err := o.CanOpGlobal(ctx, userUid) + if err != nil { + return false, err + } + if canGlobalOp { + return true, nil + } + + has, err := o.repo.IsUserHasOpPermissionInProject(ctx, userUid, projectUid, pkgConst.UIDOfOpPermissionProjectAdmin) + if err != nil { + return false, fmt.Errorf("failed to check user is project admin: %v", err) + } + + return has, nil +} + +func (o *OpPermissionVerifyUsecase) CanViewProject(ctx context.Context, userUid, projectUid string, uIdOfPermission string) (bool, error) { + canViewGlobal, err := o.CanViewGlobal(ctx, userUid) + if err != nil { + return false, err + } + if canViewGlobal { + return true, nil + } + hasPermission := false + if uIdOfPermission != "" { + hasPermission, err = o.repo.IsUserHasOpPermissionInProject(ctx, userUid, projectUid, uIdOfPermission) + if err != nil { + return false, fmt.Errorf("failed to check user is project admin: %v", err) + } + } + return hasPermission, nil +} + +func (o *OpPermissionVerifyUsecase) HasViewPermission(ctx context.Context, userId, projectUid string, uIdOfPermission string) (bool, error) { + canViewOperationRecord, err := o.HasOpPermissionInProject(ctx, userId, projectUid, uIdOfPermission) + if err != nil { + return false, err + } + isUserProjectAdmin, err := o.IsUserProjectAdmin(ctx, userId, projectUid) + if err != nil { + return false, err + } + canViewProject, err := o.CanViewProject(ctx, userId, projectUid, uIdOfPermission) + if err != nil { + return false, err + } + if canViewOperationRecord || canViewProject || isUserProjectAdmin { + return true, nil + } + return false, nil +} + +func (o *OpPermissionVerifyUsecase) HasManagePermission(ctx context.Context, userId, projectUid string, uIdOfPermission string) (bool, error) { + canViewOperationRecord, err := o.HasOpPermissionInProject(ctx, userId, projectUid, uIdOfPermission) + if err != nil { + return false, err + } + isUserProjectAdmin, err := o.IsUserProjectAdmin(ctx, userId, projectUid) + if err != nil { + return false, err + } + canOpProject, err := o.CanOpProject(ctx, userId, projectUid) + if err != nil { + return false, err + } + if canViewOperationRecord || canOpProject || isUserProjectAdmin { + return true, nil + } + return false, nil +} + +// HasOpPermissionInProject 查看某用户在某项目下是否有某种权限 +func (o *OpPermissionVerifyUsecase) HasOpPermissionInProject(ctx context.Context, userUid, projectUid string, permissionUid string) (bool, error) { + has, err := o.repo.IsUserHasOpPermissionInProject(ctx, userUid, projectUid, permissionUid) + if err != nil { + return false, fmt.Errorf("failed to check user op permission in project: %v", err) + } + return has, nil +} + +func (o *OpPermissionVerifyUsecase) CanViewGlobal(ctx context.Context, userUid string) (bool, error) { + isUserDMSAdmin, err := o.IsUserDMSAdmin(ctx, userUid) + if err != nil { + return false, err + } + if isUserDMSAdmin { + return true, nil + } + + ops, err := o.repo.GetUserGlobalOpPermission(ctx, userUid) + if err != nil { + return false, err + } + + for _, op := range ops { + if op.UID == pkgConst.UIDOfOpPermissionGlobalManagement || op.UID == pkgConst.UIDOfOpPermissionGlobalView { + return true, nil + } + } + + return false, nil +} + type OpPermissionWithOpRange struct { OpPermissionUID string // 操作权限 OpRangeType OpRangeType // OpRangeType描述操作权限的权限范围类型,目前只支持数据源 RangeUIDs []string // Range描述操作权限的权限范围,如涉及哪些数据源 } -func (o *OpPermissionVerifyUsecase) GetUserOpPermissionInNamespace(ctx context.Context, userUid, namespaceUid string) ([]OpPermissionWithOpRange, error) { +func (o *OpPermissionVerifyUsecase) GetUserGlobalOpPermission(ctx context.Context, userUid string) ([]OpPermissionWithOpRange, error) { + opPermissionWithOpRanges, err := o.repo.GetUserGlobalOpPermission(ctx, userUid) + if err != nil { + return nil, fmt.Errorf("failed to get user global op permission : %v", err) + } + + var opPermissionWithOpRangesResult []OpPermissionWithOpRange + for _, permission := range opPermissionWithOpRanges { + opPermissionWithOpRangesResult = append(opPermissionWithOpRangesResult, OpPermissionWithOpRange{ + OpPermissionUID: permission.UID, + OpRangeType: permission.RangeType, + }) + } + + return opPermissionWithOpRangesResult, nil +} + +func (o *OpPermissionVerifyUsecase) GetUserOpPermissionInProject(ctx context.Context, userUid, projectUid string) ([]OpPermissionWithOpRange, error) { - opPermissionWithOpRanges, err := o.repo.GetUserOpPermissionInNamespace(ctx, userUid, namespaceUid) + opPermissionWithOpRanges, err := o.repo.GetUserOpPermissionInProject(ctx, userUid, projectUid) if err != nil { - return nil, fmt.Errorf("failed to get user op permission in namespace: %v", err) + return nil, fmt.Errorf("failed to get user op permission in project: %v", err) } + opProjectPermissionWithOpRanges, err := o.repo.GetUserProjectOpPermissionInProject(ctx, userUid, projectUid) + if err != nil { + return nil, fmt.Errorf("failed to get user project op permission: %v", err) + } + opPermissionWithOpRanges = append(opPermissionWithOpRanges, opProjectPermissionWithOpRanges...) return opPermissionWithOpRanges, nil } +func (o *OpPermissionVerifyUsecase) GetOneOpPermissionInProject(ctx context.Context, userUid, projectUid, permissionId string) ([]OpPermissionWithOpRange, error) { + opPermissionWithOpRanges, err := o.repo.GetOneOpPermissionInProject(ctx, userUid, projectUid, permissionId) + if err != nil { + return nil, fmt.Errorf("failed to get user op permission in project: %v", err) + } + return opPermissionWithOpRanges, nil +} + func (o *OpPermissionVerifyUsecase) GetUserOpPermission(ctx context.Context, userUid string) ([]OpPermissionWithOpRange, error) { opPermissionWithOpRanges, err := o.repo.GetUserOpPermission(ctx, userUid) if err != nil { - return nil, fmt.Errorf("failed to get user op permission in namespace: %v", err) + return nil, fmt.Errorf("failed to get user op permission in project: %v", err) } - + opProjectPermissionWithOpRanges, err := o.repo.GetUserProjectOpPermission(ctx, userUid) + if err != nil { + return nil, fmt.Errorf("failed to get user project op permission: %v", err) + } + opPermissionWithOpRanges = append(opPermissionWithOpRanges, opProjectPermissionWithOpRanges...) return opPermissionWithOpRanges, nil } -type NamespaceOpPermissionWithOpRange struct { - NamespaceUid string - NamespaceName string +type ProjectOpPermissionWithOpRange struct { + ProjectUid string + ProjectName string OpPermissionWithOpRange OpPermissionWithOpRange } -func (o *OpPermissionVerifyUsecase) GetUserNamespaceOpPermission(ctx context.Context, userUid string) ([]NamespaceOpPermissionWithOpRange, error) { +func (o *OpPermissionVerifyUsecase) GetUserProjectOpPermission(ctx context.Context, userUid string) ([]ProjectOpPermissionWithOpRange, error) { - namespaceOpPermissionWithOpRange, err := o.repo.GetUserNamespaceWithOpPermissions(ctx, userUid) + projectOpPermissionWithOpRange, err := o.repo.GetUserProjectWithOpPermissions(ctx, userUid) if err != nil { - return nil, fmt.Errorf("failed to get user namespace with op permission : %v", err) + return nil, fmt.Errorf("failed to get user project with op permission : %v", err) } - return namespaceOpPermissionWithOpRange, nil + return projectOpPermissionWithOpRange, nil } -func (o *OpPermissionVerifyUsecase) GetUserManagerNamespace(ctx context.Context, namespaceWithOpPermissions []NamespaceOpPermissionWithOpRange) (userBindNamespaces []dmsCommonV1.UserBindNamespace) { +func (o *OpPermissionVerifyUsecase) GetUserManagerProject(ctx context.Context, projectWithOpPermissions []ProjectOpPermissionWithOpRange) (userBindProjects []dmsCommonV1.UserBindProject) { /* 结果如下,需要去重 +--------+---------+-------------------+---------------+---------------------+ @@ -107,35 +290,35 @@ func (o *OpPermissionVerifyUsecase) GetUserManagerNamespace(ctx context.Context, +--------+---------+-------------------+---------------+---------------------+ | 700300 | default | 700003 | db_service | 1650760484527280128 | +--------+---------+-------------------+---------------+---------------------+ - | 700300 | default| 700002 | namespace | 700300 | + | 700300 | default| 700002 | project | 700300 | +--------+---------+-------------------+---------------+---------------------+ */ - mapIdUserBindNamespace := make(map[string]dmsCommonV1.UserBindNamespace, 0) - for _, namespaceWithOpPermission := range namespaceWithOpPermissions { - n, ok := mapIdUserBindNamespace[namespaceWithOpPermission.NamespaceUid] + mapIdUserBindProject := make(map[string]dmsCommonV1.UserBindProject, 0) + for _, projectWithOpPermission := range projectWithOpPermissions { + n, ok := mapIdUserBindProject[projectWithOpPermission.ProjectUid] if !ok { - mapIdUserBindNamespace[namespaceWithOpPermission.NamespaceUid] = dmsCommonV1.UserBindNamespace{NamespaceID: namespaceWithOpPermission.NamespaceUid, NamespaceName: namespaceWithOpPermission.NamespaceName, IsManager: namespaceWithOpPermission.OpPermissionWithOpRange.OpPermissionUID == pkgConst.UIDOfOpPermissionNamespaceAdmin} + mapIdUserBindProject[projectWithOpPermission.ProjectUid] = dmsCommonV1.UserBindProject{ProjectID: projectWithOpPermission.ProjectUid, ProjectName: projectWithOpPermission.ProjectName, IsManager: projectWithOpPermission.OpPermissionWithOpRange.OpPermissionUID == pkgConst.UIDOfOpPermissionProjectAdmin} } else { - // 有一个权限为空间管理员即可 - n.IsManager = mapIdUserBindNamespace[namespaceWithOpPermission.NamespaceUid].IsManager || (namespaceWithOpPermission.OpPermissionWithOpRange.OpPermissionUID == pkgConst.UIDOfOpPermissionNamespaceAdmin) - mapIdUserBindNamespace[namespaceWithOpPermission.NamespaceUid] = n + // 有一个权限为项目管理员即可 + n.IsManager = mapIdUserBindProject[projectWithOpPermission.ProjectUid].IsManager || (projectWithOpPermission.OpPermissionWithOpRange.OpPermissionUID == pkgConst.UIDOfOpPermissionProjectAdmin) + mapIdUserBindProject[projectWithOpPermission.ProjectUid] = n } } - for _, userBindNamespace := range mapIdUserBindNamespace { - userBindNamespaces = append(userBindNamespaces, userBindNamespace) + for _, userBindProject := range mapIdUserBindProject { + userBindProjects = append(userBindProjects, userBindProject) } - return userBindNamespaces + return userBindProjects } -func (o *OpPermissionVerifyUsecase) CanCreateNamespace(ctx context.Context, userUid string) (bool, error) { +func (o *OpPermissionVerifyUsecase) CanCreateProject(ctx context.Context, userUid string) (bool, error) { // user admin has all op permission - isUserDMSAdmin, err := o.IsUserDMSAdmin(ctx, userUid) + hasGlobalOpPermission, err := o.CanOpGlobal(ctx, userUid) if err != nil { return false, err } - if isUserDMSAdmin { + if hasGlobalOpPermission { return true, nil } @@ -144,7 +327,7 @@ func (o *OpPermissionVerifyUsecase) CanCreateNamespace(ctx context.Context, user return false, fmt.Errorf("failed to get user global op permission : %v", err) } for _, opPermission := range opPermissions { - if opPermission.UID == pkgConst.UIDOfOpPermissionCreateNamespace { + if opPermission.UID == pkgConst.UIDOfOpPermissionCreateProject { return true, nil } } @@ -158,18 +341,73 @@ type ListMembersOpPermissionOption struct { } type ListMembersOpPermissionItem struct { - MemberUid string UserUid string UserName string OpPermissions []OpPermissionWithOpRange } -func (o *OpPermissionVerifyUsecase) ListMembersOpPermissionInNamespace(ctx context.Context, namespaceUid string, opt *ListMembersOpPermissionOption) ([]ListMembersOpPermissionItem, int64, error) { +func (o *OpPermissionVerifyUsecase) ListUsersOpPermissionInProject(ctx context.Context, projectUid string, opt *ListMembersOpPermissionOption) ([]ListMembersOpPermissionItem, int64, error) { - items, total, err := o.repo.ListMembersOpPermissionInNamespace(ctx, namespaceUid, opt) + items, total, err := o.repo.ListUsersOpPermissionInProject(ctx, projectUid, opt) if err != nil { - return nil, 0, fmt.Errorf("failed to list members op permission in namespace: %v", err) + return nil, 0, fmt.Errorf("failed to list members op permission in project: %v", err) } return items, total, nil } + +func (o *OpPermissionVerifyUsecase) ListUsersInProject(ctx context.Context, projectUid string) ([]ListMembersOpPermissionItem, error) { + return o.repo.ListUsersInProject(ctx, projectUid) +} + +func (o *OpPermissionVerifyUsecase) GetUserProject(ctx context.Context, userUid string) ([]*Project, error) { + + projects, err := o.repo.GetUserProject(ctx, userUid) + if err != nil { + return nil, fmt.Errorf("failed to get user project with op permission : %v", err) + } + + return projects, nil +} + +func (o *OpPermissionVerifyUsecase) UserCanOpDB(userOpPermissions []OpPermissionWithOpRange, needOpPermissionTypes []string, dbServiceUid string) bool { + for _, userOpPermission := range userOpPermissions { + // 项目管理员可以查看所有数据源 + if userOpPermission.OpPermissionUID == pkgConst.UIDOfOpPermissionProjectAdmin { + return true + } + + // 动作权限(创建、审核、上线工单等) + for _, needOpPermission := range needOpPermissionTypes { + if needOpPermission == userOpPermission.OpPermissionUID && userOpPermission.OpRangeType == OpRangeType(dmsV1.OpRangeTypeDBService) { + // 对象权限(指定数据源) + for _, id := range userOpPermission.RangeUIDs { + if id == dbServiceUid { + return true + } + } + } + } + } + + return false +} + +func (o *OpPermissionVerifyUsecase) GetCanOpDBUsers(ctx context.Context, projectUID, dbServiceUid string, needOpPermissionTypes []string) ([]string, error) { + members, _, err := o.ListUsersOpPermissionInProject(ctx, projectUID, &ListMembersOpPermissionOption{ + PageNumber: 1, + LimitPerPage: 999, + }) + if nil != err { + return nil, err + } + + userIds := make([]string, 0) + for _, member := range members { + if o.UserCanOpDB(member.OpPermissions, needOpPermissionTypes, dbServiceUid) { + userIds = append(userIds, member.UserUid) + } + } + + return userIds, nil +} diff --git a/internal/dms/biz/operation_record.go b/internal/dms/biz/operation_record.go new file mode 100644 index 000000000..289f9df2b --- /dev/null +++ b/internal/dms/biz/operation_record.go @@ -0,0 +1,106 @@ +package biz + +import ( + "context" + "strconv" + "time" + + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +type OperationRecordRepo interface { + SaveOperationRecord(ctx context.Context, record *OperationRecord) error + ListOperationRecords(ctx context.Context, opt *ListOperationRecordOption) ([]*OperationRecord, uint64, error) + ExportOperationRecords(ctx context.Context, opt *ListOperationRecordOption) ([]*OperationRecord, error) + CleanOperationRecordOpTimeBefore(ctx context.Context, t time.Time) (rowsAffected int64, err error) +} + +type OperationRecord struct { + ID uint + OperationTime time.Time + OperationUserName string + OperationReqIP string + OperationUserAgent string + OperationTypeName string + OperationAction string + OperationProjectName string + OperationStatus string + OperationI18nContent i18nPkg.I18nStr +} + +type ListOperationRecordOption struct { + PageIndex uint32 + PageSize uint32 + FilterOperateTimeFrom string + FilterOperateTimeTo string + FilterOperateProjectName *string + FuzzySearchOperateUserName string + FilterOperateTypeName string + FilterOperateAction string + // 权限相关字段 + CanViewGlobal bool // 是否有全局查看权限(admin/sys/全局权限) + AccessibleProjectNames []string // 可访问的项目名称列表(项目管理员) +} + +type OperationRecordUsecase struct { + repo OperationRecordRepo + systemVariableUsecase *SystemVariableUsecase + log *utilLog.Helper +} + +func NewOperationRecordUsecase(logger utilLog.Logger, repo OperationRecordRepo, svu *SystemVariableUsecase) *OperationRecordUsecase { + return &OperationRecordUsecase{ + repo: repo, + systemVariableUsecase: svu, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.operationRecord")), + } +} + +func (u *OperationRecordUsecase) DoClean() { + if u.systemVariableUsecase == nil { + u.log.Errorf("failed to clean operation record when get systemVariableUsecase") + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + variables, err := u.systemVariableUsecase.GetSystemVariables(ctx) + if err != nil { + u.log.Errorf("failed to clean operation record when get expired duration: %v", err) + return + } + + operationRecordExpiredHoursVar, ok := variables[SystemVariableOperationRecordExpiredHours] + if !ok { + u.log.Debugf("system variable %s not found, using default value", SystemVariableOperationRecordExpiredHours) + operationRecordExpiredHoursVar = SystemVariable{ + Key: SystemVariableOperationRecordExpiredHours, + Value: strconv.Itoa(DefaultOperationRecordExpiredHours), + } + } + + operationRecordExpiredHours, err := strconv.Atoi(operationRecordExpiredHoursVar.Value) + if err != nil { + u.log.Errorf("failed to parse operation_record_expired_hours value: %v", err) + return + } + + if operationRecordExpiredHours <= 0 { + u.log.Errorf("got OperationRecordExpiredHours: %d", operationRecordExpiredHours) + return + } + + cleanTime := time.Now().Add(time.Duration(-operationRecordExpiredHours) * time.Hour) + rowsAffected, err := u.repo.CleanOperationRecordOpTimeBefore(ctx, cleanTime) + if err != nil { + u.log.Errorf("failed to clean operation record: %v", err) + return + } + u.log.Infof("OperationRecord regular cleaned rows: %d operation time before: %s", rowsAffected, cleanTime.Format("2006-01-02 15:04:05")) +} + +func (u *OperationRecordUsecase) GetLog() *utilLog.Helper { + return u.log +} diff --git a/internal/dms/biz/plugin.go b/internal/dms/biz/plugin.go index e6feb08af..0fa4c8083 100644 --- a/internal/dms/biz/plugin.go +++ b/internal/dms/biz/plugin.go @@ -2,11 +2,21 @@ package biz import ( "context" + "encoding/base64" + "encoding/json" "fmt" - + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + + v1 "github.com/actiontech/dms/api/dms/service/v1" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" - + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" @@ -25,17 +35,18 @@ type PluginUsecase struct { } type Plugin struct { - Name string - AddDBServicePreCheckUrl string - DelDBServicePreCheckUrl string - DelUserPreCheckUrl string - DelUserGroupPreCheckUrl string + Name string + // 该地址目的是统一调用其他服务 数据资源变更前后校验/更新数据的 接口 + // eg: 删除数据源前: + // 需要sqle服务中实现接口逻辑,判断该数据源上已经没有进行中的工单 OperateDataResourceHandleUrl string + GetDatabaseDriverOptionsUrl string + GetDatabaseDriverLogosUrl string } func (p *Plugin) String() string { - return fmt.Sprintf("name=%v,addDBServicePreCheckUrl=%v,delDBServicePreCheckUrl=%v,delUserPreCheckUrl=%v,delUserGroupPreCheckUrl=%v,OperateDataHandleUrl=%v", - p.Name, p.AddDBServicePreCheckUrl, p.DelDBServicePreCheckUrl, p.DelUserPreCheckUrl, p.DelUserGroupPreCheckUrl, p.OperateDataResourceHandleUrl) + return fmt.Sprintf("name=%v,OperateDataHandleUrl=%v", + p.Name, p.OperateDataResourceHandleUrl) } func NewDMSPluginUsecase(logger utilLog.Logger, repo DMSPluginRepo) (*PluginUsecase, error) { @@ -80,187 +91,545 @@ func (p *PluginUsecase) RegisterPlugin(ctx context.Context, plugin *Plugin, curr return nil } -func (p *PluginUsecase) AddDBServicePreCheck(ctx context.Context, ds *DBService) error { - dbTyp, err := dmsV1.ParseIPluginDBType(ds.DBType.String()) - if err != nil { - return fmt.Errorf("parse db type failed: %v", err) +func (p *PluginUsecase) AddProjectAfterHandle(ctx context.Context, ProjectUid string) error { + if err := p.OperateDataResourceHandle(ctx, ProjectUid, nil, dmsV1.DataResourceTypeProject, dmsV1.OperationTypeCreate, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("add project handle failed: %v", err) + } + return nil +} + +func (p *PluginUsecase) UpdateProjectPreCheck(ctx context.Context, project *Project) error { + // 项目归档 + if err := p.OperateDataResourceHandle(ctx, project.UID, dmsV1.IPluginProject{ + Name: project.Name, + Archived: project.Status == ProjectStatusArchived, + Desc: project.Desc, + }, dmsV1.DataResourceTypeProject, dmsV1.OperationTypeUpdate, dmsV1.OperationTimingTypeBefore); err != nil { + return fmt.Errorf("update project handle failed: %v", err) + } + return nil +} + +func (p *PluginUsecase) UpdateProjectAfterHandle(ctx context.Context, projectUid string) error { + return nil +} + +func (p *PluginUsecase) DelProjectPreCheck(ctx context.Context, projectUid string) error { + if err := p.OperateDataResourceHandle(ctx, projectUid, nil, dmsV1.DataResourceTypeProject, dmsV1.OperationTypeDelete, dmsV1.OperationTimingTypeBefore); err != nil { + return fmt.Errorf("del project pre check failed: %v", err) } + return nil +} + +func (p *PluginUsecase) DelProjectAfterHandle(ctx context.Context, projectUid string) error { + if err := p.OperateDataResourceHandle(ctx, projectUid, nil, dmsV1.DataResourceTypeProject, dmsV1.OperationTypeDelete, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("del project handle failed: %v", err) + } + return nil +} + +func (p *PluginUsecase) AddDBServicePreCheck(ctx context.Context, ds *DBService) error { dbService := &dmsV1.IPluginDBService{ - Name: ds.Name, - DBType: dbTyp, - Host: ds.Host, - Port: ds.Port, - User: ds.AdminUser, - Business: ds.Business, + Name: ds.Name, + DBType: ds.DBType, + Host: ds.Host, + Port: ds.Port, + User: ds.User, + // Business: ds.Business, + EnvironmentTag: ds.EnvironmentTag, + AdditionalParams: ds.AdditionalParams, } if ds.SQLEConfig != nil { dbService.SQLERuleTemplateName = ds.SQLEConfig.RuleTemplateName dbService.SQLERuleTemplateId = ds.SQLEConfig.RuleTemplateID } - for _, plugin := range p.registeredPlugins { - if plugin.AddDBServicePreCheckUrl != "" { - if err := p.CallAddDBServicePreCheck(ctx, plugin.AddDBServicePreCheckUrl, dbService); err != nil { - return fmt.Errorf("plugin %s add db service pre check failed: %v", plugin.Name, err) - } - } + + if err := p.OperateDataResourceHandle(ctx, "", dbService, dmsV1.DataResourceTypeDBService, dmsV1.OperationTypeCreate, dmsV1.OperationTimingTypeBefore); err != nil { + return fmt.Errorf("add db service pre check failed: %v", err) + } + + return nil +} + +func (p *PluginUsecase) AddDBServiceAfterHandle(ctx context.Context, dbServiceUid string) error { + if err := p.OperateDataResourceHandle(ctx, dbServiceUid, nil, dmsV1.DataResourceTypeDBService, dmsV1.OperationTypeCreate, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("add db service handle failed: %v", err) + } + + return nil +} + +func (p *PluginUsecase) UpdateDBServicePreCheck(ctx context.Context, ds *DBService) error { + return nil +} + +func (p *PluginUsecase) UpdateDBServiceAfterHandle(ctx context.Context, dbServiceUid string) error { + if err := p.OperateDataResourceHandle(ctx, dbServiceUid, nil, dmsV1.DataResourceTypeDBService, dmsV1.OperationTypeUpdate, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("update db service handle failed: %v", err) } return nil } func (p *PluginUsecase) DelDBServicePreCheck(ctx context.Context, dbServiceUid string) error { - for _, plugin := range p.registeredPlugins { - if plugin.DelDBServicePreCheckUrl != "" { - if err := p.CallDelDBServicePreCheck(ctx, plugin.DelDBServicePreCheckUrl, dbServiceUid); err != nil { - return fmt.Errorf("plugin %s del db service pre check failed: %v", plugin.Name, err) - } - } + if err := p.OperateDataResourceHandle(ctx, dbServiceUid, nil, dmsV1.DataResourceTypeDBService, dmsV1.OperationTypeDelete, dmsV1.OperationTimingTypeBefore); err != nil { + return fmt.Errorf("del db service pre check failed: %v", err) + } + return nil +} + +func (p *PluginUsecase) DelDBServiceAfterHandle(ctx context.Context, dbServiceUid string) error { + if err := p.OperateDataResourceHandle(ctx, dbServiceUid, nil, dmsV1.DataResourceTypeDBService, dmsV1.OperationTypeDelete, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("del db service handle failed: %v", err) } return nil } func (p *PluginUsecase) DelUserPreCheck(ctx context.Context, userUid string) error { - for _, plugin := range p.registeredPlugins { - if plugin.DelUserPreCheckUrl != "" { - if err := p.CallDelUserPreCheck(ctx, plugin.DelUserPreCheckUrl, userUid); err != nil { - return fmt.Errorf("plugin %s del user pre check failed: %v", plugin.Name, err) - } - } + if err := p.OperateDataResourceHandle(ctx, userUid, nil, dmsV1.DataResourceTypeUser, dmsV1.OperationTypeDelete, dmsV1.OperationTimingTypeBefore); err != nil { + return fmt.Errorf("del user pre check failed: %v", err) + } + return nil +} + +func (p *PluginUsecase) DelUserAfterHandle(ctx context.Context, userUid string) error { + if err := p.OperateDataResourceHandle(ctx, userUid, nil, dmsV1.DataResourceTypeUser, dmsV1.OperationTypeDelete, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("del user after handle failed: %v", err) } return nil } func (p *PluginUsecase) DelUserGroupPreCheck(ctx context.Context, groupUid string) error { - for _, plugin := range p.registeredPlugins { - if plugin.DelUserGroupPreCheckUrl != "" { - if err := p.CallDelUserGroupPreCheck(ctx, plugin.DelUserGroupPreCheckUrl, groupUid); err != nil { - return fmt.Errorf("plugin %s del user group pre check failed: %v", plugin.Name, err) - } + return nil +} + +func (p *PluginUsecase) DelMemberGroupAfterHandle(ctx context.Context, memberGroupUid string) error { + if err := p.OperateDataResourceHandle(ctx, memberGroupUid, nil, dmsV1.DataResourceTypeMemberGroup, dmsV1.OperationTypeDelete, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("del member group after handle failed: %v", err) + } + return nil +} +func (p *PluginUsecase) UpdateMemberGroupAfterHandle(ctx context.Context, memberGroupUid string, userUids []string) error { + userUidsInts := make([]int64, len(userUids)) + for i, userUid := range userUids { + userUidsInt, err := strconv.ParseInt(userUid, 10, 64) + if err != nil { + return fmt.Errorf("convert user uid to int failed: %v", err) } + userUidsInts[i] = userUidsInt + } + + if err := p.OperateDataResourceHandle(ctx, memberGroupUid, userUidsInts, dmsV1.DataResourceTypeMemberGroup, dmsV1.OperationTypeUpdate, dmsV1.OperationTimingTypeAfter); err != nil { + return fmt.Errorf("update member group after handle failed: %v", err) } return nil } -func (p *PluginUsecase) OperateDataResourceHandle(ctx context.Context, uid string, dateResourceType dmsV1.DataResourceType, +func (p *PluginUsecase) OperateDataResourceHandle(ctx context.Context, uid string, resource interface{}, dateResourceType dmsV1.DataResourceType, operationType dmsV1.OperationType, operationTiming dmsV1.OperationTimingType) error { + var ( + mu sync.Mutex + errs []error + wg sync.WaitGroup + ) + for _, plugin := range p.registeredPlugins { if plugin.OperateDataResourceHandleUrl != "" { - if err := p.CallOperateDataResourceHandle(ctx, plugin.OperateDataResourceHandleUrl, uid, dateResourceType, operationType, operationTiming); err != nil { - return fmt.Errorf("call plugin %s operate data resource handle failed: %v", plugin.Name, err) - } + wg.Add(1) + go func(plugin *Plugin) { + defer wg.Done() + if err := p.CallOperateDataResourceHandle(ctx, plugin.OperateDataResourceHandleUrl, uid, resource, dateResourceType, operationType, operationTiming); err != nil { + mu.Lock() + errs = append(errs, fmt.Errorf("call plugin %s operate data resource handle failed: %v", plugin.Name, err)) + mu.Unlock() + } + }(plugin) } } + + wg.Wait() + + if len(errs) > 0 { + return fmt.Errorf("encountered errors: %v", errs) + } + return nil } -func (p *PluginUsecase) CallAddDBServicePreCheck(ctx context.Context, url string, ds *dmsV1.IPluginDBService) error { +func (p *PluginUsecase) CallOperateDataResourceHandle(ctx context.Context, url string, dataResourceUid string, resource interface{}, dataResourceType dmsV1.DataResourceType, operationType dmsV1.OperationType, operationTiming dmsV1.OperationTimingType) error { header := map[string]string{ "Authorization": pkgHttp.DefaultDMSToken, } - - reqBody := struct { - DBService *dmsV1.IPluginDBService `json:"db_service"` - }{ - DBService: ds, + extraParams, err := json.Marshal(resource) + if err != nil { + return fmt.Errorf("marshal resource failed: %v", err) } + operateDataResourceHandleReq := dmsV1.OperateDataResourceHandleReq{ + DataResourceUid: dataResourceUid, + DataResourceType: dataResourceType, + OperationType: operationType, + OperationTiming: operationTiming, + ExtraParams: string(extraParams), + } + reply := &dmsV1.OperateDataResourceHandleReply{} - reply := &dmsV1.AddDBServicePreCheckReply{} - - if err := pkgHttp.Get(ctx, url, header, reqBody, reply); err != nil { + if err := pkgHttp.POST(ctx, url, header, operateDataResourceHandleReq, reply); err != nil { return err } if reply.Code != 0 { - return fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Msg) + return fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Message) } return nil } -func (p *PluginUsecase) CallDelDBServicePreCheck(ctx context.Context, url string, dbServiceUid string) error { - header := map[string]string{ - "Authorization": pkgHttp.DefaultDMSToken, +const ( + LogoPath = "/logo" + LogoDir = "./static/logo" +) + +var databaseDriverOptions []*v1.DatabaseDriverOption + +func (p *PluginUsecase) GetDatabaseDriverOptionsCache(ctx context.Context) ([]*v1.DatabaseDriverOption, error) { + if len(databaseDriverOptions) != 0 { + return databaseDriverOptions, nil } + // refresh the cache + options, err := p.GetDatabaseDriverOptionsHandle(ctx) + if err != nil { + return nil, err + } + databaseDriverOptions = append(databaseDriverOptions, options...) + return databaseDriverOptions, nil +} - reqBody := struct { - DBServiceUid string `json:"db_service_uid"` - }{ - DBServiceUid: dbServiceUid, +func (p *PluginUsecase) ClearDatabaseDriverOptionsCache() { + databaseDriverOptions = []*v1.DatabaseDriverOption{} +} + +// 获取数据库插件扩展选项和加载数据库插件logo +// 1. 首先从缓存中获取options,如果缓存为空则调用dms的plugin接口获取并保存到缓存中 +// 2. 在从plugin获取options后,会启用协程按数据库类型到dms plugin中下载缺失的logo +// 3. 缓存清空:清空缓存后会重新调用接口获取options +// a) 当有新的plugin注册到dms时(provision和sqle启动) +// b) 当从plugin中加载logo的方法执行完成时 +func (p *PluginUsecase) GetDatabaseDriverOptionsHandle(ctx context.Context) ([]*v1.DatabaseDriverOption, error) { + log := utilLog.NewHelper(p.logger, utilLog.WithMessageKey("biz.dmsplugin.DatabaseDriverOptionsHandle")) + var ( + mu sync.Mutex + errs []error + wg sync.WaitGroup + dbOptions []struct { + options []*v1.DatabaseDriverOption + source string + } + ) + + for _, plugin := range p.registeredPlugins { + if plugin.GetDatabaseDriverOptionsUrl == "" { + continue + } + wg.Add(1) + go func(plugin *Plugin) { + defer wg.Done() + op, err := p.CallDatabaseDriverOptionsHandle(ctx, plugin.GetDatabaseDriverOptionsUrl) + if err != nil { + mu.Lock() + errs = append(errs, fmt.Errorf("call plugin %s get database driver options handle failed: %v", plugin.Name, err)) + mu.Unlock() + return + } + mu.Lock() + dbOptions = append(dbOptions, struct { + options []*v1.DatabaseDriverOption + source string + }{ + options: op, + source: plugin.Name, + }) + mu.Unlock() + }(plugin) + } + + wg.Wait() + + if len(errs) > 0 { + return nil, fmt.Errorf("encountered errors: %v", errs) + } + options := p.aggregateOptions(log, dbOptions) + dbTypes := make([]string, 0, len(options)) + for _, dbType := range options { + dbTypes = append(dbTypes, dbType.DBType) + } + // 处理数据库插件logo + go p.DatabaseLogoHandle(context.TODO(), dbTypes) + return options, nil +} + +// 根据数据库类型合并各插件的options +func (p *PluginUsecase) aggregateOptions(log *utilLog.Helper, optionRes []struct { + options []*v1.DatabaseDriverOption + source string +}) []*v1.DatabaseDriverOption { + dbTypeMap := make(map[string]*v1.DatabaseDriverOption) + for _, res := range optionRes { + for _, opt := range res.options { + if aggOpt, exists := dbTypeMap[opt.DBType]; exists { + // 聚合Params, 合并时如有重复以sqle为主 + aggOpt.Params = mergeParamsByName(aggOpt.Params, opt.Params, res.source == _const.SqleComponentName) + } else { + logofile, err := p.GetLogoFilesMap(opt.DBType) + if err != nil { + log.Errorf("get %s logo file name error: %v", opt.DBType, err) + } + dbTypeMap[opt.DBType] = &v1.DatabaseDriverOption{ + DBType: opt.DBType, + LogoPath: filepath.Join(LogoPath, logofile[opt.DBType]), + Params: opt.Params, + } + } + } } - reply := &dmsV1.DelDBServicePreCheckReply{} + // 转换为切片返回 + result := make([]*v1.DatabaseDriverOption, 0, len(dbTypeMap)) + for _, opt := range dbTypeMap { + result = append(result, opt) + } + return result +} - if err := pkgHttp.Get(ctx, url, header, reqBody, reply); err != nil { - return err +// 根据参数名合并additional和params, overwriteExisting代表是不是要以新参数覆盖旧参数 +func mergeParamsByName(existing, newParams []*v1.DatabaseDriverAdditionalParam, overwriteExisting bool) []*v1.DatabaseDriverAdditionalParam { + paramMap := make(map[string]*v1.DatabaseDriverAdditionalParam) + + // 添加已有参数 + for _, param := range existing { + paramMap[param.Name] = param } - if reply.Code != 0 { - return fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Msg) + + // 合并新参数 + for _, param := range newParams { + if _, exists := paramMap[param.Name]; exists && overwriteExisting { + newAggParam := *param + paramMap[param.Name] = &newAggParam // 覆盖已有参数 + } else if !exists { + paramMap[param.Name] = param + } } - return nil + // 转换为切片返回 + result := make([]*v1.DatabaseDriverAdditionalParam, 0, len(paramMap)) + for _, param := range paramMap { + result = append(result, param) + } + return result } -func (p *PluginUsecase) CallDelUserPreCheck(ctx context.Context, url string, userUid string) error { +func (p *PluginUsecase) CallDatabaseDriverOptionsHandle(ctx context.Context, url string) ([]*v1.DatabaseDriverOption, error) { header := map[string]string{ "Authorization": pkgHttp.DefaultDMSToken, } + reply := &v1.ListDBServiceDriverOptionReply{} - reqBody := struct { - UserUid string `json:"user_uid"` - }{ - UserUid: userUid, - } - - reply := &dmsV1.DelUserPreCheckReply{} - - if err := pkgHttp.Get(ctx, url, header, reqBody, reply); err != nil { - return err + if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { + return nil, err } if reply.Code != 0 { - return fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Msg) + return nil, fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Message) } - return nil + return reply.Data, nil } -func (p *PluginUsecase) CallDelUserGroupPreCheck(ctx context.Context, url string, userGroupUid string) error { - header := map[string]string{ - "Authorization": pkgHttp.DefaultDMSToken, +func (p *PluginUsecase) DatabaseLogoHandle(ctx context.Context, dbTypes []string) { + log := utilLog.NewHelper(p.logger, utilLog.WithMessageKey("biz.dmsplugin.logohandle")) + // 定义 logo 文件夹路径 + if err := os.MkdirAll(LogoDir, os.ModePerm); err != nil { + log.Errorf("create logo dir error: %v", err) + return } + // 获取需要保存logo的数据库插件类型 + logoDBTypes, err := p.GetDBTypesForLogoSave(dbTypes) + if err != nil { + log.Errorf("get db types for logo save error: %v", err) + return + } + if len(logoDBTypes) == 0 { + return + } + var ( + mu sync.Mutex + errs []error + wg sync.WaitGroup + allLogos []struct { + logo string + dbType string + source string + } + ) + for _, plugin := range p.registeredPlugins { + if plugin.GetDatabaseDriverLogosUrl == "" { + continue + } - reqBody := struct { - UserGroupUid string `json:"user_group_uid"` - }{ - UserGroupUid: userGroupUid, + wg.Add(1) + go func(plugin *Plugin) { + defer wg.Done() + logos, err := p.CallDatabaseDriverLogosHandle(ctx, plugin.GetDatabaseDriverLogosUrl, logoDBTypes) + if err != nil { + mu.Lock() + errs = append(errs, fmt.Errorf("call plugin %s get database driver logos handle failed: %v", plugin.Name, err)) + mu.Unlock() + return + } + mu.Lock() + for k, v := range logos { + allLogos = append(allLogos, struct { + logo string + dbType string + source string + }{ + logo: v, + dbType: k, + source: plugin.Name, + }) + } + mu.Unlock() + }(plugin) } - reply := &dmsV1.DelUserGroupPreCheckReply{} + wg.Wait() - if err := pkgHttp.Get(ctx, url, header, reqBody, reply); err != nil { - return err + if len(errs) > 0 { + log.Errorf("encountered errors: %v", errs) } - if reply.Code != 0 { - return fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Msg) + logoMap := make(map[string]string) + for _, entry := range allLogos { + // 目前只使用sqle提供的logo,因为其他插件暂未提供logo + if _, found := logoMap[entry.dbType]; !found && entry.source == _const.SqleComponentName { + logoMap[entry.dbType] = entry.logo + } + } + addedNewLogo, err := p.SaveLogoFiles(log, logoMap) + if err != nil { + log.Errorf("save logo error: %v", err) } + // 当有新的logo文件被加载时, 清空缓存, 用以重新加载logo path + if addedNewLogo { + p.ClearDatabaseDriverOptionsCache() + } +} - return nil +func (p *PluginUsecase) GetDBTypesForLogoSave(allDBTypes []string) ([]string, error) { + needToSave := []string{} + existingFiles, err := p.GetLogoFilesMap(allDBTypes...) + if err != nil { + return nil, fmt.Errorf("failed to read logo directory '%s': %w", LogoDir, err) + } + // 检查每种数据库类型对应的文件是否已存在 + for _, dbType := range allDBTypes { + // 如果未找到对应文件,加入需要保存的列表 + if _, ok := existingFiles[dbType]; !ok { + needToSave = append(needToSave, dbType) + } + } + + return needToSave, nil } -func (p *PluginUsecase) CallOperateDataResourceHandle(ctx context.Context, url string, dataResourceUid string, dataResourceType dmsV1.DataResourceType, operationType dmsV1.OperationType, operationTiming dmsV1.OperationTimingType) error { +// 返回指定数据库类型的logo文件名称 +func (p *PluginUsecase) GetLogoFilesMap(dbTypes ...string) (map[string]string /*key: db type, value: logo file name*/, error) { + entries, err := os.ReadDir(LogoDir) + if err != nil { + return nil, err + } + logoFiles := make(map[string]string) + for _, dbType := range dbTypes { + // 构建文件名前缀 + filePrefix := strings.ToLower(strings.ReplaceAll(dbType, " ", "_")) + "." + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), filePrefix) { + logoFiles[dbType] = entry.Name() + } + } + } + return logoFiles, nil +} + +func (p *PluginUsecase) CallDatabaseDriverLogosHandle(ctx context.Context, url string, dbTypes []string) (map[string]string /*key: db type; value: logo string*/, error) { header := map[string]string{ "Authorization": pkgHttp.DefaultDMSToken, } - operateDataResourceHandleReq := dmsV1.OperateDataResourceHandleReq{ - DataResourceUid: dataResourceUid, - DataResourceType: dataResourceType, - OperationType: operationType, - OperationTiming: operationTiming, + var reply struct { + Logos []struct { + DBType string `json:"db_type"` + Logo string `json:"logo"` + } `json:"data"` + base.GenericResp } - reply := &dmsV1.OperateDataResourceHandleReply{} - - if err := pkgHttp.POST(ctx, url, header, operateDataResourceHandleReq, reply); err != nil { - return err + reqBody := struct { + DBTypes []string `json:"db_types"` + }{ + DBTypes: dbTypes, + } + // 因为logo数据较大,调整超时时间为1分钟 + ctx = pkgHttp.SetTimeoutValueContext(ctx, 60) + if err := pkgHttp.Get(ctx, url, header, reqBody, &reply); err != nil { + return nil, fmt.Errorf("failed to get logos for %s: %v", url, err) } if reply.Code != 0 { - return fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Msg) + return nil, fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Message) + } + logosMap := make(map[string]string, len(reply.Logos)) + for _, logo := range reply.Logos { + logosMap[logo.DBType] = logo.Logo } + return logosMap, nil +} - return nil +func (p *PluginUsecase) SaveLogoFiles(log *utilLog.Helper, logoMap map[string]string /*key: db type; value: logo string*/) (bool /*added new logo file*/, error) { + var addedNewLogo bool + for k, v := range logoMap { + if v == "" { + log.Errorf("%s logo base64 string is empty", k) + continue + } + data, err := base64.StdEncoding.DecodeString(v) + + if err != nil { + log.Errorf("decode %s logo base64 string error: %v", k, err) + continue + } + mimeType := http.DetectContentType(data) + isSupport, logoType := p.GetLogoFileTypeByHttpContentType(mimeType) + if !isSupport { + log.Errorf("unsupported image type: %s", mimeType) + continue + } + fileName := p.GetLogoFileName(k, logoType) + if err := os.WriteFile(filepath.Join(LogoDir, fileName), data, os.ModePerm); err != nil { + log.Errorf("write %s logo file error: %v", k, err) + continue + } + addedNewLogo = true + } + return addedNewLogo, nil +} + +func (p *PluginUsecase) GetLogoFileName(dbType, logoType string) string { + return strings.ToLower(strings.ReplaceAll(dbType, " ", "_")) + logoType +} + +func (p *PluginUsecase) GetLogoFileTypeByHttpContentType(mimeType string) (bool, string) { + switch mimeType { + case "image/jpeg": + return true, ".jpeg" + case "image/png": + return true, ".png" + case "image/svg+xml": + return true, ".svg" + case "image/webp": + return true, ".webp" + default: + return false, "" + } } diff --git a/internal/dms/biz/prepare.go b/internal/dms/biz/prepare.go index 2a486b4ac..28811166a 100644 --- a/internal/dms/biz/prepare.go +++ b/internal/dms/biz/prepare.go @@ -13,7 +13,7 @@ func EnvPrepare(ctx context.Context, logger utilLog.Logger, opPermissionUsecase *OpPermissionUsecase, userUsecase *UserUsecase, roleUsecase *RoleUsecase, - namespaceUsecase *NamespaceUsecase) (err error) { + projectUsecase *ProjectUsecase) (err error) { log := utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.prepare")) // 开启事务 tx := transaction.BeginTX(ctx) @@ -32,7 +32,7 @@ func EnvPrepare(ctx context.Context, logger utilLog.Logger, // 如果找到了,则判断是否需要初始化数据对象操作 if dmsConfig.NeedInitOpPermissions { - if err := opPermissionUsecase.InitOpPermissions(tx); nil != err { + if err := opPermissionUsecase.InitOpPermissions(tx, initOpPermission()); nil != err { return err } dmsConfig.NeedInitOpPermissions = false @@ -58,11 +58,11 @@ func EnvPrepare(ctx context.Context, logger utilLog.Logger, return fmt.Errorf("failed to update dms config: %v", err) } } - if dmsConfig.NeedInitNamespaces { - if err := namespaceUsecase.InitNamespaces(tx); nil != err { + if dmsConfig.NeedInitProjects { + if err := projectUsecase.InitProjects(tx); nil != err { return err } - dmsConfig.NeedInitNamespaces = false + dmsConfig.NeedInitProjects = false if err := config.UpdateDMSConfig(tx, dmsConfig); nil != err { return fmt.Errorf("failed to update dms config: %v", err) } diff --git a/internal/dms/biz/project.go b/internal/dms/biz/project.go new file mode 100644 index 000000000..1e6fe58c2 --- /dev/null +++ b/internal/dms/biz/project.go @@ -0,0 +1,238 @@ +package biz + +import ( + "context" + "errors" + "fmt" + "time" + + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" +) + +type ProjectStatus string + +const ( + ProjectStatusArchived ProjectStatus = "archived" + ProjectStatusActive ProjectStatus = "active" + ProjectStatusUnknown ProjectStatus = "unknown" +) + +type Project struct { + Base + + UID string + Name string + Desc string + Priority dmsCommonV1.ProjectPriority + BusinessTag BusinessTag + CreateUserUID string + CreateTime time.Time + Status ProjectStatus +} + +type Business struct { + Uid string + Name string +} + +type PreviewProject struct { + Name string + Desc string + BusinessTagName string +} + +func NewProject(createUserUID, name, desc string, priority dmsCommonV1.ProjectPriority, businessTagUID string) (*Project, error) { + uid, err := pkgRand.GenStrUid() + if err != nil { + return nil, err + } + return &Project{ + UID: uid, + Name: name, + Desc: desc, + Status: ProjectStatusActive, + CreateUserUID: createUserUID, + BusinessTag: BusinessTag{UID: businessTagUID}, + Priority: priority, + }, nil +} + +func initProjects() []*Project { + return []*Project{ + { + UID: pkgConst.UIDOfProjectDefault, + Name: "default", + Desc: "default project", + Status: ProjectStatusActive, + CreateUserUID: pkgConst.UIDOfUserAdmin, + Priority: dmsCommonV1.ProjectPriorityMedium, + }, + } +} + +type ProjectRepo interface { + SaveProject(ctx context.Context, project *Project) error + BatchSaveProjects(ctx context.Context, projects []*Project) error + ListProjects(ctx context.Context, opt *ListProjectsOption, currentUserUID string) (projects []*Project, total int64, err error) + GetProject(ctx context.Context, projectUid string) (*Project, error) + GetProjectByName(ctx context.Context, projectName string) (*Project, error) + GetProjectByNames(ctx context.Context, projectNames []string) ([]*Project, error) + UpdateProject(ctx context.Context, u *Project) error + DelProject(ctx context.Context, projectUid string) error + UpdateDBServiceBusiness(ctx context.Context, projectUid string, originBusiness string, descBusiness string) error +} + +type ProjectUsecase struct { + tx TransactionGenerator + repo ProjectRepo + memberUsecase *MemberUsecase + businessTagUsecase *BusinessTagUsecase + environmentTagUsecase *EnvironmentTagUsecase + opPermissionVerifyUsecase *OpPermissionVerifyUsecase + pluginUsecase *PluginUsecase + log *utilLog.Helper +} + +func NewProjectUsecase(log utilLog.Logger, tx TransactionGenerator, repo ProjectRepo, + memberUsecase *MemberUsecase, + opPermissionVerifyUsecase *OpPermissionVerifyUsecase, + pluginUsecase *PluginUsecase, + businessTagUsecase *BusinessTagUsecase, + environmentTagUsecase *EnvironmentTagUsecase) *ProjectUsecase { + return &ProjectUsecase{ + tx: tx, + repo: repo, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.project")), + memberUsecase: memberUsecase, + pluginUsecase: pluginUsecase, + businessTagUsecase: businessTagUsecase, + environmentTagUsecase: environmentTagUsecase, + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + } +} + +type ListProjectsOption struct { + PageNumber uint32 + LimitPerPage uint32 + OrderBy ProjectField + FilterByOptions pkgConst.FilterOptions +} + +func (d *ProjectUsecase) ListProject(ctx context.Context, option *ListProjectsOption, currentUserUid string) (projects []*Project, total int64, err error) { + canViewGlobal, err := d.opPermissionVerifyUsecase.CanViewGlobal(ctx, currentUserUid) + if err != nil { + return nil, 0, err + } + + // filter visible namespace space in advance + // user can only view his belonging project,sys user can view all project + if currentUserUid != pkgConst.UIDOfUserSys && !canViewGlobal { + projects, err := d.opPermissionVerifyUsecase.GetUserProject(ctx, currentUserUid) + if err != nil { + return nil, 0, err + } + canViewableId := make([]string, 0) + for _, project := range projects { + canViewableId = append(canViewableId, project.UID) + } + option.FilterByOptions.Groups = append(option.FilterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(ProjectFieldUID), + Operator: pkgConst.FilterOperatorIn, + Value: canViewableId, + }, + )) + + } + + projects, total, err = d.repo.ListProjects(ctx, option, currentUserUid) + if err != nil { + return nil, 0, fmt.Errorf("list projects failed: %v", err) + } + + return projects, total, nil +} + +func (d *ProjectUsecase) ListProjectTips(ctx context.Context, currentUserUid string) ([]*Project, error) { + return d.opPermissionVerifyUsecase.GetUserProject(ctx, currentUserUid) +} + +func (d *ProjectUsecase) InitProjects(ctx context.Context) (err error) { + for _, n := range initProjects() { + _, err := d.GetProject(ctx, n.UID) + // already exist + if err == nil { + continue + } + + // error, return directly + if !errors.Is(err, pkgErr.ErrStorageNoData) { + return fmt.Errorf("failed to get project: %v", err) + } + + business, err := d.businessTagUsecase.newBusinessTag(n.Name) + if err != nil { + d.log.Error("create business tag for default project failed") + return fmt.Errorf("create business tag for default project failed: %v", err) + } + err = d.businessTagUsecase.businessTagRepo.CreateBusinessTag(ctx, business) + if err != nil { + d.log.Error("get business tag for default project failed") + return fmt.Errorf("get business tag for default project failed: %v", err) + } + n.BusinessTag = *business + + // not exist, then create it. + err = d.repo.SaveProject(ctx, n) + if err != nil { + return fmt.Errorf("save projects failed: %v", err) + } + + _, err = d.memberUsecase.AddUserToProjectAdminMember(ctx, pkgConst.UIDOfUserAdmin, n.UID) + if err != nil { + return fmt.Errorf("add admin to projects failed: %v", err) + } + // 初始化环境标签 + err = d.environmentTagUsecase.InitDefaultEnvironmentTags(ctx, n.UID, n.CreateUserUID) + if err != nil { + d.log.Error("init default environment tags failed", + "error", err, + "project_uid", n.UID, + "create_user_uid", n.CreateUserUID, + ) + return fmt.Errorf("init default environment tags failed: %v", err) + } + } + d.log.Debug("init project success") + return nil +} + +func (d *ProjectUsecase) GetProject(ctx context.Context, projectUid string) (*Project, error) { + return d.repo.GetProject(ctx, projectUid) +} + +func (d *ProjectUsecase) UpdateDBServiceBusiness(ctx context.Context, currentUserUid, projectUid string, originBusiness, descBusiness string) error { + // 检查项目是否归档/删除 + if err := d.isProjectActive(ctx, projectUid); err != nil { + return fmt.Errorf("update db service error: %v", err) + } + + // 检查当前用户有项目管理员权限 + if canOpProject, err := d.opPermissionVerifyUsecase.CanOpProject(ctx, currentUserUid, projectUid); err != nil { + return fmt.Errorf("check user is project admin or global op permission failed: %v", err) + } else if !canOpProject { + return fmt.Errorf("user is not project admin or global op permission user") + } + + err := d.repo.UpdateDBServiceBusiness(ctx, projectUid, originBusiness, descBusiness) + if err != nil { + return fmt.Errorf("update db service business failed: %v", err) + } + + return nil +} diff --git a/internal/dms/biz/project_ce.go b/internal/dms/biz/project_ce.go new file mode 100644 index 000000000..684427fde --- /dev/null +++ b/internal/dms/biz/project_ce.go @@ -0,0 +1,57 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +var errNotSupportProject = errors.New("project related functions are enterprise version functions") + +func (d *ProjectUsecase) CreateProject(ctx context.Context, project *Project, createUserUID string) (err error) { + return errNotSupportProject +} + +func (d *ProjectUsecase) GetProjectByName(ctx context.Context, projectName string) (*Project, error) { + return nil, errNotSupportProject +} + +func (d *ProjectUsecase) UpdateProjectDesc(ctx context.Context, currentUserUid, projectUid string, desc *string) (err error) { + + return errNotSupportProject +} + +func (d *ProjectUsecase) ArchivedProject(ctx context.Context, currentUserUid, projectUid string, archived bool) (err error) { + + return errNotSupportProject +} + +func (d *ProjectUsecase) DeleteProject(ctx context.Context, currentUserUid, projectUid string) (err error) { + return errNotSupportProject +} + +func (d *ProjectUsecase) isProjectActive(ctx context.Context, projectUid string) error { + return nil +} + +func (d *ProjectUsecase) ImportProjects(ctx context.Context, uid string, projects []*Project) error { + return errNotSupportProject +} + +func (d *ProjectUsecase) GetImportProjectsTemplate(ctx context.Context, projectUid string) ([]byte, error) { + return nil, errNotSupportProject +} + +func (d *ProjectUsecase) PreviewImportProjects(ctx context.Context, uid, file string) ([]*PreviewProject, error) { + return nil, errNotSupportProject +} + +func (d *ProjectUsecase) UpdateProject(ctx context.Context, currentUserUid, projectUid string, desc *string, priority *dmsCommonV1.ProjectPriority, businessTagUID string) (err error) { + return errNotSupportProject +} + +func (d *ProjectUsecase) ExportProjects(ctx context.Context, uid string, option *ListProjectsOption) ([]byte, error) { + return nil, errNotSupportProject +} diff --git a/internal/dms/biz/proxy.go b/internal/dms/biz/proxy.go index 65d6167e4..9f081e9b9 100644 --- a/internal/dms/biz/proxy.go +++ b/internal/dms/biz/proxy.go @@ -8,6 +8,8 @@ import ( "sync" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/pkg/dms-common/conf" + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" "github.com/labstack/echo/v4" @@ -18,10 +20,31 @@ type ProxyTargetRepo interface { SaveProxyTarget(ctx context.Context, u *ProxyTarget) error UpdateProxyTarget(ctx context.Context, u *ProxyTarget) error ListProxyTargets(ctx context.Context) ([]*ProxyTarget, error) + ListProxyTargetsByScenarios(ctx context.Context, scenarios []ProxyScenario) ([]*ProxyTarget, error) GetProxyTargetByName(ctx context.Context, name string) (*ProxyTarget, error) } -type ProxyTarget middleware.ProxyTarget +func (p *ProxyTarget) GetURL() string { + if p.URL == nil { + return "" + } + return p.URL.String() +} + +type ProxyTarget struct { + middleware.ProxyTarget + Version string + Scenario ProxyScenario +} +type ProxyScenario string + +const ( + ProxyScenarioInternalService ProxyScenario = "internal_service" + ProxyScenarioThirdPartyIntegrate ProxyScenario = "thrid_party_integrate" + ProxyScenarioUnknown ProxyScenario = "unknown" +) + +var ErrUnknownProxyScenario error = fmt.Errorf("unknown proxy scenairo") const ProxyTargetMetaKey = "prefixs" @@ -41,35 +64,54 @@ type DmsProxyUsecase struct { rewrite map[string]string mutex sync.RWMutex logger utilLog.Logger + opPermissionUc *OpPermissionUsecase + roleUc *RoleUsecase } -func NewDmsProxyUsecase(logger utilLog.Logger, repo ProxyTargetRepo, dmsPort int) (*DmsProxyUsecase, error) { +func NewDmsProxyUsecase(logger utilLog.Logger, repo ProxyTargetRepo, apiCnf *conf.APIServerOpts, opPermissionUC *OpPermissionUsecase, roleUc *RoleUsecase) (*DmsProxyUsecase, error) { targets, err := repo.ListProxyTargets(context.TODO()) if err != nil { return nil, fmt.Errorf("list proxy targets from repo error: %v", err) } - dmsUrl, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%v", dmsPort)) + dmsUrl, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%v", apiCnf.Port)) + if err != nil { + return nil, fmt.Errorf("parse dms url error: %v", err) + } + if apiCnf.EnableHttps { + dmsUrl.Scheme = "https" + } return &DmsProxyUsecase{ repo: repo, // 将自身定义为默认代理,当无法匹配转发规则时,转发到自身 defaultTargetSelf: &ProxyTarget{ - Name: "dms", - URL: dmsUrl, + ProxyTarget: middleware.ProxyTarget{ + Name: _const.DmsComponentName, + URL: dmsUrl, + }, }, // TODO 支持可配置 rewrite: map[string]string{ - "/sqle/*": "/$1", + "/sqle/*": "/$1", + "/webhook/*": "/$1", }, - targets: targets, - logger: logger, + targets: targets, + logger: logger, + opPermissionUc: opPermissionUC, + roleUc: roleUc, }, nil } type RegisterDMSProxyTargetArgs struct { Name string Addr string + Version string ProxyUrlPrefixs []string + Scenario ProxyScenario +} + +func (d *DmsProxyUsecase) GetTargetByName(ctx context.Context, name string) (*ProxyTarget, error) { + return d.repo.GetProxyTargetByName(ctx, name) } func (d *DmsProxyUsecase) RegisterDMSProxyTarget(ctx context.Context, currentUserUid string, args RegisterDMSProxyTargetArgs) error { @@ -93,9 +135,13 @@ func (d *DmsProxyUsecase) RegisterDMSProxyTarget(ctx context.Context, currentUse } target := &ProxyTarget{ - Name: args.Name, - URL: url, - Meta: echo.Map{ProxyTargetMetaKey: args.ProxyUrlPrefixs}, + ProxyTarget: middleware.ProxyTarget{ + Name: args.Name, + URL: url, + Meta: echo.Map{ProxyTargetMetaKey: args.ProxyUrlPrefixs}, + }, + Version: args.Version, + Scenario: args.Scenario, } for i, t := range d.targets { @@ -116,6 +162,20 @@ func (d *DmsProxyUsecase) RegisterDMSProxyTarget(ctx context.Context, currentUse return fmt.Errorf("add proxy target error: %v", err) } log.Infof("add target: %s; url: %s; prefix: %v", target.Name, target.URL, args.ProxyUrlPrefixs) + + // 注册独立权限 + proxyOpPermission := GetProxyOpPermission()[target.Name] + if len(proxyOpPermission) > 0 { + if err := d.opPermissionUc.InitOpPermissions(ctx, proxyOpPermission); nil != err { + return err + } + // 更新角色 + rolePermission := OpsEngineerPermissionsStrategy{}.GetPermissions() + err = d.roleUc.InsureOpPermissionsToRole(ctx, rolePermission, pkgConst.UIDOfRoleOpsEngineer) + if err != nil { + return fmt.Errorf("insure op permissions to role failed: %v", err) + } + } return nil } @@ -131,6 +191,14 @@ func (d *DmsProxyUsecase) checkProxyUrlPrefix(proxyUrlPrefixs []string) error { return nil } +func (d *DmsProxyUsecase) ListProxyTargets(ctx context.Context) ([]*ProxyTarget, error) { + return d.repo.ListProxyTargets(ctx) +} + +func (d *DmsProxyUsecase) ListProxyTargetsByScenarios(ctx context.Context, scenarios []ProxyScenario) ([]*ProxyTarget, error) { + return d.repo.ListProxyTargetsByScenarios(ctx, scenarios) +} + // AddTarget实现echo的ProxyBalancer接口, 没有实际意义 func (d *DmsProxyUsecase) AddTarget(target *middleware.ProxyTarget) bool { return true @@ -152,7 +220,11 @@ func (d *DmsProxyUsecase) Next(c echo.Context) *middleware.ProxyTarget { for _, prefix := range t.GetProxyUrlPrefixs() { if prefix != "" && strings.HasPrefix(c.Request().URL.Path, prefix) { log.Debugf("url: %s; proxy to target: %s; proxy prefix: %v", c.Request().URL.Path, t.Name, t.Meta[ProxyTargetMetaKey]) - return (*middleware.ProxyTarget)(t) + return &middleware.ProxyTarget{ + Name: t.Name, + URL: t.URL, + Meta: t.Meta, + } } } } @@ -160,7 +232,12 @@ func (d *DmsProxyUsecase) Next(c echo.Context) *middleware.ProxyTarget { // 由于Skipper方法的存在,当无法匹配转发规则时,会跳过转发,所以大部分情况下不会执行到这里。 // 极端情况比如Skipper后,target列表发生了变动,则可能执行到这里,使用默认代理转发到自身作为兜底。 log.Debugf("proxy to default target") - return (*middleware.ProxyTarget)(d.defaultTargetSelf) + + return &middleware.ProxyTarget{ + Name: d.defaultTargetSelf.Name, + URL: d.defaultTargetSelf.URL, + Meta: d.defaultTargetSelf.Meta, + } } // DmsProxyUsecase 实现了 middleware.ProxyBalancer 接口 diff --git a/internal/dms/biz/repo_fields.go b/internal/dms/biz/repo_fields.go index 7e5dd9b5b..861d048e8 100644 --- a/internal/dms/biz/repo_fields.go +++ b/internal/dms/biz/repo_fields.go @@ -1,57 +1,200 @@ // Code generated by gencli for actiontech dms. DO NOT EDIT package biz +type BasicConfigField string + +type CloudbeaverConnectionCacheField string + +type CloudbeaverUserCacheField string + +type ClusterLeaderField string + +type ClusterNodeInfoField string + +type CompanyNoticeField string + type DBServiceField string type DMSConfigField string +type DataExportTaskField string + +type DataExportTaskRecordField string + +type DatabaseSourceServiceField string + +type IMConfigurationField string + type LDAPConfigurationField string type MemberField string +type MemberGroupField string + +type MemberGroupRoleOpRangeField string + type MemberRoleOpRangeField string type ModelField string -type NamespaceField string - type Oauth2ConfigurationField string type OpPermissionField string type PluginField string +type ProjectField string + type ProxyTargetField string type RoleField string +type SMTPConfigurationField string + type UserField string type UserGroupField string +type WeChatConfigurationField string + +type WebHookConfigurationField string + +type WorkflowField string + +type WorkflowRecordField string + +type WorkflowStepField string + +type CbOperationLogField string + +const ( + BasicConfigFieldUID BasicConfigField = "uid" + BasicConfigFieldLogo BasicConfigField = "logo" + BasicConfigFieldTitle BasicConfigField = "title" +) + +const ( + CbOperationLogFieldUID CbOperationLogField = "uid" + CbOperationLogFieldOpPersonUID CbOperationLogField = "op_person_uid" + CbOperationLogFieldOpTime CbOperationLogField = "op_time" + CbOperationLogFieldDBServiceUID CbOperationLogField = "db_service_uid" + CbOperationLogFieldOpDetail CbOperationLogField = "op_detail" + CbOperationLogFieldOpSessionID CbOperationLogField = "op_session_id" + CbOperationLogFieldProjectID CbOperationLogField = "project_id" + CbOperationLogFieldOpHost CbOperationLogField = "op_host" + CbOperationLogFieldAuditResult CbOperationLogField = "audit_result" + CbOperationLogFieldIsAuditPassed CbOperationLogField = "is_audit_passed" + CbOperationLogFieldExecResult CbOperationLogField = "exec_result" + CbOperationLogFieldExecTotalSec CbOperationLogField = "exec_total_sec" + CbOperationLogFieldResultSetRowCount CbOperationLogField = "result_set_row_count" + CbOperationLogFieldWorkflowID CbOperationLogField = "workflow_id" +) + +const ( + CloudbeaverConnectionCacheFieldDMSDBServiceID CloudbeaverConnectionCacheField = "dms_db_service_id" + CloudbeaverConnectionCacheFieldDMSUserID CloudbeaverConnectionCacheField = "dms_user_id" + CloudbeaverConnectionCacheFieldDMSDBServiceFingerprint CloudbeaverConnectionCacheField = "dms_db_service_fingerprint" + CloudbeaverConnectionCacheFieldCloudbeaverConnectionID CloudbeaverConnectionCacheField = "cloudbeaver_connection_id" + CloudbeaverConnectionCacheFieldPurpose CloudbeaverConnectionCacheField = "purpose" +) + +const ( + CloudbeaverUserCacheFieldDMSUserID CloudbeaverUserCacheField = "dms_user_id" + CloudbeaverUserCacheFieldDMSFingerprint CloudbeaverUserCacheField = "dms_fingerprint" + CloudbeaverUserCacheFieldCloudbeaverUserID CloudbeaverUserCacheField = "cloudbeaver_user_id" +) + +const ( + ClusterLeaderFieldAnchor ClusterLeaderField = "anchor" + ClusterLeaderFieldServerId ClusterLeaderField = "serverid" + ClusterLeaderFieldLastSeenTime ClusterLeaderField = "lastseentime" +) + +const ( + ClusterNodeInfoFieldServerId ClusterNodeInfoField = "serverid" + ClusterNodeInfoFieldHardwareSign ClusterNodeInfoField = "hardwaresign" + ClusterNodeInfoFieldCreatedAt ClusterNodeInfoField = "createdat" +) + +const ( + CompanyNoticeFieldUID CompanyNoticeField = "uid" + CompanyNoticeFieldNoticeStr CompanyNoticeField = "noticestr" + CompanyNoticeFieldReadUserIds CompanyNoticeField = "readuserids" +) + const ( - DBServiceFieldUID DBServiceField = "uid" - DBServiceFieldName DBServiceField = "name" - DBServiceFieldDBType DBServiceField = "db_type" - DBServiceFieldHost DBServiceField = "db_host" - DBServiceFieldPort DBServiceField = "db_port" - DBServiceFieldUser DBServiceField = "db_user" - DBServiceFieldPassword DBServiceField = "db_password" - DBServiceFieldDesc DBServiceField = "desc" - DBServiceFieldBusiness DBServiceField = "business" - DBServiceFieldAdditionalParams DBServiceField = "additionalparams" - DBServiceFieldSource DBServiceField = "source" - DBServiceFieldNamespaceUID DBServiceField = "namespace_uid" - DBServiceFieldMaintenancePeriod DBServiceField = "maintenanceperiod" - DBServiceFieldExtraParameters DBServiceField = "extraparameters" + DBServiceFieldUID DBServiceField = "uid" + DBServiceFieldName DBServiceField = "name" + DBServiceFieldDBType DBServiceField = "db_type" + DBServiceFieldHost DBServiceField = "db_host" + DBServiceFieldPort DBServiceField = "db_port" + DBServiceFieldUser DBServiceField = "db_user" + DBServiceFieldPassword DBServiceField = "db_password" + DBServiceFieldDesc DBServiceField = "desc" + DBServiceFieldBusiness DBServiceField = "business" + DBServiceFieldAdditionalParams DBServiceField = "additionalparams" + DBServiceFieldSource DBServiceField = "source" + DBServiceFieldProjectUID DBServiceField = "project_uid" + DBServiceFieldMaintenancePeriod DBServiceField = "maintenanceperiod" + DBServiceFieldExtraParameters DBServiceField = "extraparameters" + DBServiceFieldLastConnectionStatus DBServiceField = "last_connection_status" + DBServiceFieldEnvironmentTagUID DBServiceField = "environment_tag_uid" ) const ( - DMSConfigFieldUID DMSConfigField = "uid" - DMSConfigFieldNeedInitOpPermissions DMSConfigField = "need_init_op_permissions" - DMSConfigFieldNeedInitUsers DMSConfigField = "need_init_users" - DMSConfigFieldNeedInitRoles DMSConfigField = "need_init_roles" - DMSConfigFieldNeedInitNamespaces DMSConfigField = "need_init_namespaces" + DMSConfigFieldUID DMSConfigField = "uid" + DMSConfigFieldNeedInitOpPermissions DMSConfigField = "need_init_op_permissions" + DMSConfigFieldNeedInitUsers DMSConfigField = "need_init_users" + DMSConfigFieldNeedInitRoles DMSConfigField = "need_init_roles" + DMSConfigFieldNeedInitProjects DMSConfigField = "need_init_projects" + DMSConfigFieldEnableSQLResultSetsDataMasking DMSConfigField = "enable_sql_result_sets_data_masking" +) + +const ( + DataExportTaskFieldUID DataExportTaskField = "uid" + DataExportTaskFieldDBServiceUid DataExportTaskField = "dbserviceuid" + DataExportTaskFieldDatabaseName DataExportTaskField = "databasename" + DataExportTaskFieldWorkFlowRecordUid DataExportTaskField = "workflowrecorduid" + DataExportTaskFieldExportType DataExportTaskField = "exporttype" + DataExportTaskFieldExportFileType DataExportTaskField = "exportfiletype" + DataExportTaskFieldExportFileName DataExportTaskField = "export_file_name" + DataExportTaskFieldExportStatus DataExportTaskField = "export_status" + DataExportTaskFieldExportStartTime DataExportTaskField = "export_start_time" + DataExportTaskFieldExportEndTime DataExportTaskField = "export_end_time" + DataExportTaskFieldCreateUserUID DataExportTaskField = "create_user_uid" + DataExportTaskFieldAuditLevel DataExportTaskField = "auditlevel" + DataExportTaskFieldDataExportTaskRecords DataExportTaskField = "dataexporttaskrecords" +) + +const ( + DataExportTaskRecordFieldNumber DataExportTaskRecordField = "number" + DataExportTaskRecordFieldDataExportTaskId DataExportTaskRecordField = "data_export_task_id" + DataExportTaskRecordFieldExportSQLType DataExportTaskRecordField = "export_sql_type" + DataExportTaskRecordFieldExportStatus DataExportTaskRecordField = "exportstatus" + DataExportTaskRecordFieldAuditResults DataExportTaskRecordField = "auditresults" +) + +const ( + DatabaseSourceServiceFieldUID DatabaseSourceServiceField = "uid" + DatabaseSourceServiceFieldName DatabaseSourceServiceField = "name" + DatabaseSourceServiceFieldSource DatabaseSourceServiceField = "source" + DatabaseSourceServiceFieldVersion DatabaseSourceServiceField = "version" + DatabaseSourceServiceFieldURL DatabaseSourceServiceField = "url" + DatabaseSourceServiceFieldDbType DatabaseSourceServiceField = "dbtype" + DatabaseSourceServiceFieldProjectUID DatabaseSourceServiceField = "project_uid" + DatabaseSourceServiceFieldCronExpress DatabaseSourceServiceField = "cron_express" + DatabaseSourceServiceFieldLastSyncErr DatabaseSourceServiceField = "last_sync_err" + DatabaseSourceServiceFieldLastSyncSuccessTime DatabaseSourceServiceField = "last_sync_success_time" + DatabaseSourceServiceFieldExtraParameters DatabaseSourceServiceField = "extraparameters" +) + +const ( + IMConfigurationFieldUID IMConfigurationField = "uid" + IMConfigurationFieldAppKey IMConfigurationField = "app_key" + IMConfigurationFieldAppSecret IMConfigurationField = "app_secret" + IMConfigurationFieldIsEnable IMConfigurationField = "is_enable" + IMConfigurationFieldProcessCode IMConfigurationField = "process_code" + IMConfigurationFieldType IMConfigurationField = "type" ) const ( @@ -70,10 +213,25 @@ const ( const ( MemberFieldUID MemberField = "uid" MemberFieldUserUID MemberField = "user_uid" - MemberFieldNamespaceUID MemberField = "namespace_uid" + MemberFieldProjectUID MemberField = "project_uid" MemberFieldRoleWithOpRanges MemberField = "rolewithopranges" ) +const ( + MemberGroupFieldUID MemberGroupField = "uid" + MemberGroupFieldName MemberGroupField = "name" + MemberGroupFieldProjectUID MemberGroupField = "project_uid" + MemberGroupFieldUsers MemberGroupField = "users" + MemberGroupFieldRoleWithOpRanges MemberGroupField = "rolewithopranges" +) + +const ( + MemberGroupRoleOpRangeFieldMemberGroupUID MemberGroupRoleOpRangeField = "member_group_uid" + MemberGroupRoleOpRangeFieldRoleUID MemberGroupRoleOpRangeField = "role_uid" + MemberGroupRoleOpRangeFieldOpRangeType MemberGroupRoleOpRangeField = "op_range_type" + MemberGroupRoleOpRangeFieldRangeUIDs MemberGroupRoleOpRangeField = "range_uids" +) + const ( MemberRoleOpRangeFieldMemberUID MemberRoleOpRangeField = "member_uid" MemberRoleOpRangeFieldRoleUID MemberRoleOpRangeField = "role_uid" @@ -82,20 +240,15 @@ const ( ) const ( - ModelFieldUID ModelField = "uid" -) - -const ( - NamespaceFieldUID NamespaceField = "uid" - NamespaceFieldName NamespaceField = "name" - NamespaceFieldDesc NamespaceField = "desc" - NamespaceFieldCreateUserUID NamespaceField = "create_user_uid" - NamespaceFieldStatus NamespaceField = "status" + ModelFieldUID ModelField = "uid" + ModelFieldCreatedAt ModelField = "created_at" ) const ( Oauth2ConfigurationFieldUID Oauth2ConfigurationField = "uid" Oauth2ConfigurationFieldEnableOauth2 Oauth2ConfigurationField = "enable_oauth2" + Oauth2ConfigurationFieldSkipCheckState Oauth2ConfigurationField = "skip_check_state" + Oauth2ConfigurationFieldAutoCreateUser Oauth2ConfigurationField = "autocreateuser" Oauth2ConfigurationFieldClientID Oauth2ConfigurationField = "client_id" Oauth2ConfigurationFieldClientKey Oauth2ConfigurationField = "clientkey" Oauth2ConfigurationFieldClientSecret Oauth2ConfigurationField = "clientsecret" @@ -106,6 +259,8 @@ const ( Oauth2ConfigurationFieldScopes Oauth2ConfigurationField = "scopes" Oauth2ConfigurationFieldAccessTokenTag Oauth2ConfigurationField = "access_token_tag" Oauth2ConfigurationFieldUserIdTag Oauth2ConfigurationField = "user_id_tag" + Oauth2ConfigurationFieldUserWeChatTag Oauth2ConfigurationField = "user_wechat_tag" + Oauth2ConfigurationFieldUserEmailTag Oauth2ConfigurationField = "user_email_tag" Oauth2ConfigurationFieldLoginTip Oauth2ConfigurationField = "login_tip" ) @@ -114,6 +269,7 @@ const ( OpPermissionFieldName OpPermissionField = "name" OpPermissionFieldDesc OpPermissionField = "description" OpPermissionFieldRangeType OpPermissionField = "range_type" + OpPermissionFieldService OpPermissionField = "service" ) const ( @@ -125,24 +281,49 @@ const ( PluginFieldOperateDataResourceHandleUrl PluginField = "operate_data_resource_handle_url" ) +const ( + ProjectFieldUID ProjectField = "uid" + ProjectFieldName ProjectField = "name" + ProjectFieldDesc ProjectField = "`desc`" // desc是MySQL的保留字,在作为被引用的field时,需要用``括起 + ProjectFieldCreateUserUID ProjectField = "create_user_uid" + ProjectFieldStatus ProjectField = "status" + ProjectFieldPriority ProjectField = "priority" + ProjectFieldBusinessTagUID ProjectField = "business_tag_uid" +) + const ( ProxyTargetFieldName ProxyTargetField = "name" ProxyTargetFieldUrl ProxyTargetField = "url" + ProxyTargetFieldVersion ProxyTargetField = "version" ProxyTargetFieldProxyUrlPrefixs ProxyTargetField = "proxy_url_prefixs" + ProxyTargetFieldScenario ProxyTargetField = "scenario" ) const ( - RoleFieldUID RoleField = "uid" + RoleFieldUID RoleField = "roles.uid" RoleFieldName RoleField = "name" + RoleFieldCreatedAt RoleField = "created_at" RoleFieldDesc RoleField = "description" RoleFieldStat RoleField = "stat" + RoleFieldOpPermission RoleField = "op_permission" RoleFieldOpPermissions RoleField = "oppermissions" ) +const ( + SMTPConfigurationFieldUID SMTPConfigurationField = "uid" + SMTPConfigurationFieldEnableSMTPNotify SMTPConfigurationField = "enablesmtpnotify" + SMTPConfigurationFieldHost SMTPConfigurationField = "smtp_host" + SMTPConfigurationFieldPort SMTPConfigurationField = "smtp_port" + SMTPConfigurationFieldUsername SMTPConfigurationField = "smtp_username" + SMTPConfigurationFieldSecretPassword SMTPConfigurationField = "secret_smtp_password" + SMTPConfigurationFieldIsSkipVerify SMTPConfigurationField = "isskipverify" +) + const ( UserFieldUID UserField = "uid" UserFieldName UserField = "name" UserFieldThirdPartyUserID UserField = "third_party_user_id" + UserFieldThirdPartyUserInfo UserField = "third_party_user_info" UserFieldEmail UserField = "email" UserFieldPhone UserField = "phone" UserFieldWeChatID UserField = "wechat_id" @@ -162,3 +343,51 @@ const ( UserGroupFieldStat UserGroupField = "stat" UserGroupFieldUsers UserGroupField = "users" ) + +const ( + WeChatConfigurationFieldUID WeChatConfigurationField = "uid" + WeChatConfigurationFieldEnableWeChatNotify WeChatConfigurationField = "enablewechatnotify" + WeChatConfigurationFieldCorpID WeChatConfigurationField = "corpid" + WeChatConfigurationFieldEncryptedCorpSecret WeChatConfigurationField = "encryptedcorpsecret" + WeChatConfigurationFieldAgentID WeChatConfigurationField = "agentid" + WeChatConfigurationFieldSafeEnabled WeChatConfigurationField = "safeenabled" + WeChatConfigurationFieldProxyIP WeChatConfigurationField = "proxyip" +) + +const ( + WebHookConfigurationFieldUID WebHookConfigurationField = "uid" + WebHookConfigurationFieldEnable WebHookConfigurationField = "enable" + WebHookConfigurationFieldMaxRetryTimes WebHookConfigurationField = "maxretrytimes" + WebHookConfigurationFieldRetryIntervalSeconds WebHookConfigurationField = "retryintervalseconds" + WebHookConfigurationFieldEncryptedToken WebHookConfigurationField = "encryptedtoken" + WebHookConfigurationFieldURL WebHookConfigurationField = "url" +) + +const ( + WorkflowFieldUID WorkflowField = "uid" + WorkflowFieldName WorkflowField = "name" + WorkflowFieldProjectUID WorkflowField = "project_uid" + WorkflowFieldWorkflowType WorkflowField = "workflow_type" + WorkflowFieldDesc WorkflowField = "desc" + WorkflowFieldCreateTime WorkflowField = "create_time" + WorkflowFieldCreateUserUID WorkflowField = "create_user_uid" + WorkflowFieldWorkflowRecordUid WorkflowField = "workflow_record_uid" + WorkflowFieldWorkflowRecord WorkflowField = "workflowrecord" +) + +const ( + WorkflowRecordFieldUID WorkflowRecordField = "uid" + WorkflowRecordFieldWorkflowUid WorkflowRecordField = "workflowuid" + WorkflowRecordFieldStatus WorkflowRecordField = "status" + WorkflowRecordFieldTaskIds WorkflowRecordField = "taskids" + WorkflowRecordFieldSteps WorkflowRecordField = "steps" +) + +const ( + WorkflowStepFieldStepId WorkflowStepField = "stepid" + WorkflowStepFieldWorkflowRecordUid WorkflowStepField = "workflowrecorduid" + WorkflowStepFieldOperationUserUid WorkflowStepField = "operationuseruid" + WorkflowStepFieldState WorkflowStepField = "state" + WorkflowStepFieldReason WorkflowStepField = "reason" + WorkflowStepFieldAssignees WorkflowStepField = "assignees" +) diff --git a/internal/dms/biz/resource_overview.go b/internal/dms/biz/resource_overview.go new file mode 100644 index 000000000..3bb813d2a --- /dev/null +++ b/internal/dms/biz/resource_overview.go @@ -0,0 +1,96 @@ +package biz + +import ( + "context" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +type ResourceOverviewVisibility string + +type ResourceOverviewRepo interface { + GetResourceList(ctx context.Context, listOptions ListResourceOverviewOption) ([]*ResourceRow, int64, error) +} + +type ResourceTopology struct { + Resources []*Resource `json:"resources"` +} + +type Resource struct { + Business Business `json:"business"` + Projects []*ResourceProject `json:"project"` +} + +type ResourceProject struct { + Project Project `json:"project"` + DBServices []*DBService `json:"db_services"` +} + +type ListResourceOverviewOption struct { + ListOptions *ResourceOverviewListOptions + Filters *ResourceOverviewFilter +} + +type ResourceOverviewListOptions struct { + PageIndex uint32 `json:"page_index"` + PageSize uint32 `json:"page_size"` +} + +type ResourceOverviewFilter struct { + FilterByDBType string `json:"filter_by_db_type"` + FilterByBusinessTagUID string `json:"filter_by_business_tag_uid"` + FilterByEnvironmentTagUID string `json:"filter_by_environment_tag_uid"` + FilterByProjectUID string `json:"filter_by_project_uid"` + FilterByProjectUIDs []string `json:"filter_by_project_uids"` + FuzzySearchResourceName string `json:"fuzzy_search_resource_name"` + FilterDBServiceNotNull bool `json:"filter_db_service_not_null"` +} + +type ResourceDetail struct { + ResourceRow + // 审核评分 + AuditScore float32 `json:"audit_score"` + // 待处理工单数 + PendingWorkflowCount int32 `json:"pending_workflow_count"` + // 高优先级SQL数 + HighPrioritySQLCount int32 `json:"high_priority_sql_count"` +} + +type ResourceRow struct { + ProjectName string `json:"project_name"` + ProjectUID string `json:"project_uid"` + EnvironmentTagUID string `json:"environment_tag_uid"` + EnvironmentTagName string `json:"environment_tag_name"` + BusinessTagName string `json:"business_tag_name"` + BusinessTagUID string `json:"business_tag_uid"` + DBServiceName string `json:"db_service_name"` + DBServiceUID string `json:"db_service_uid"` + DBType string `json:"db_type"` +} + +type ResourceOverviewUsecase struct { + log *utilLog.Helper + projectRepo ProjectRepo + dbServiceRepo DBServiceRepo + resourceOverviewRepo ResourceOverviewRepo + opPermissionVerifyUsecase OpPermissionVerifyUsecase + dmsProxyTargetRepo ProxyTargetRepo +} + +func NewResourceOverviewUsecase( + log utilLog.Logger, + projectRepo ProjectRepo, + dbServiceRepo DBServiceRepo, + opPermissionVerifyUsecase OpPermissionVerifyUsecase, + resourceOverviewRepo ResourceOverviewRepo, + dmsProxyTargetRepo ProxyTargetRepo, +) *ResourceOverviewUsecase { + return &ResourceOverviewUsecase{ + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.ResourceOverview")), + projectRepo: projectRepo, + dbServiceRepo: dbServiceRepo, + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + resourceOverviewRepo: resourceOverviewRepo, + dmsProxyTargetRepo: dmsProxyTargetRepo, + } +} diff --git a/internal/dms/biz/role.go b/internal/dms/biz/role.go index 6d5533f84..1654db67d 100644 --- a/internal/dms/biz/role.go +++ b/internal/dms/biz/role.go @@ -35,10 +35,11 @@ func ParseRoleStat(stat uint) (RoleStat, error) { type Role struct { Base - UID string - Name string - Desc string - Stat RoleStat + UID string + Name string + Desc string + Stat RoleStat + OpPermissions []*OpPermission } func newRole(name, desc string) (*Role, error) { @@ -64,36 +65,40 @@ func (u *Role) GetUID() string { func initRole() []*Role { return []*Role{ { - UID: pkgConst.UIDOfRoleNamespaceAdmin, - Name: "空间管理员", - Desc: "namespace admin", + UID: pkgConst.UIDOfRoleProjectAdmin, + Name: "项目管理员", // todo i18n 返回时会根据uid国际化,name、desc已弃用;数据库name字段是唯一键,故暂时保留 + Desc: "project admin", }, { - UID: pkgConst.UIDOfRoleSQLEAdmin, - Name: "SQLE管理员", - Desc: "拥有该权限的用户可以创建/编辑工单,审核/驳回工单,上线工单,创建/编辑扫描任务", + UID: pkgConst.UIDOfRoleDevEngineer, + Name: "开发工程师", }, { - UID: pkgConst.UIDOfRoleProvisionAdmin, - Name: "provision管理员", - Desc: "拥有该权限的用户可以授权数据源数据权限", + UID: pkgConst.UIDOfRoleDevManager, + Name: "开发主管", + }, + { + UID: pkgConst.UIDOfRoleOpsEngineer, + Name: "运维工程师", }, } } type ListRolesOption struct { - PageNumber uint32 - LimitPerPage uint32 - OrderBy RoleField - FilterBy []pkgConst.FilterCondition + PageNumber uint32 + LimitPerPage uint32 + OrderBy RoleField + FilterByOptions pkgConst.FilterOptions } type RoleRepo interface { SaveRole(ctx context.Context, role *Role) error UpdateRole(ctx context.Context, u *Role) error CheckRoleExist(ctx context.Context, roleUids []string) (exists bool, err error) + CheckRoleExistByRoleName(ctx context.Context, roleName string) (exists bool, err error) ListRoles(ctx context.Context, opt *ListRolesOption) (roles []*Role, total int64, err error) DelRole(ctx context.Context, roleUid string) error + DelRoleFromAllMemberGroups(ctx context.Context, roleUid string) error GetRole(ctx context.Context, roleUid string) (*Role, error) AddOpPermissionToRole(ctx context.Context, OpPermissionUid string, roleUid string) error ReplaceOpPermissionsInRole(ctx context.Context, roleUid string, OpPermissionUids []string) error @@ -124,6 +129,63 @@ func NewRoleUsecase(log utilLog.Logger, tx TransactionGenerator, repo RoleRepo, } } +// 定义角色权限策略接口 +type RolePermissionsStrategy interface { + GetPermissions() []string +} + +// 定义具体的角色权限策略 +type ProjectAdminPermissionsStrategy struct{} + +func (s ProjectAdminPermissionsStrategy) GetPermissions() []string { + return []string{pkgConst.UIDOfOpPermissionProjectAdmin} +} + +type DevEngineerPermissionsStrategy struct { + RoleId string +} + +func (s DevEngineerPermissionsStrategy) GetPermissions() []string { + return []string{ + pkgConst.UIDOfOpPermissionCreateWorkflow, + pkgConst.UIDOfOpPermissionSQLQuery, + pkgConst.UIDOfOpPermissionCreatePipeline, + pkgConst.UIDOfOpPermissionCreateOptimization, + } +} + +type DevManagerPermissionsStrategy struct{} + +func (s DevManagerPermissionsStrategy) GetPermissions() []string { + return []string{ + pkgConst.UIDOfOpPermissionViewOthersWorkflow, + pkgConst.UIDOfOpPermissionAuditWorkflow, + pkgConst.UIDOfOpPermissionCreatePipeline, + pkgConst.UIDOfOpPermissionViewOthersOptimization, + } +} + +type OpsEngineerPermissionsStrategy struct{} + +func (s OpsEngineerPermissionsStrategy) GetPermissions() []string { + return []string{ + pkgConst.UIDOfOpPermissionViewOthersWorkflow, + pkgConst.UIDOfOpPermissionExecuteWorkflow, + pkgConst.UIDOfOpPermissionSaveAuditPlan, + pkgConst.UIDOfOpPermissionViewOthersAuditPlan, + pkgConst.UIDOfOpPermissionExportCreate, + pkgConst.UIDOfOpPermissionViewSQLInsight, + } +} + +// 权限映射关系 +var rolePermissionsMap = map[string]RolePermissionsStrategy{ + pkgConst.UIDOfRoleProjectAdmin: ProjectAdminPermissionsStrategy{}, + pkgConst.UIDOfRoleDevEngineer: DevEngineerPermissionsStrategy{}, + pkgConst.UIDOfRoleDevManager: DevManagerPermissionsStrategy{}, + pkgConst.UIDOfRoleOpsEngineer: OpsEngineerPermissionsStrategy{}, +} + func (d *RoleUsecase) InitRoles(ctx context.Context) (err error) { for _, r := range initRole() { @@ -142,26 +204,13 @@ func (d *RoleUsecase) InitRoles(ctx context.Context) (err error) { if err := d.repo.SaveRole(ctx, r); err != nil { return fmt.Errorf("failed to init role: %v", err) } - roleId := r.GetUID() - switch roleId { - case pkgConst.UIDOfRoleNamespaceAdmin: - if err = d.InsureOpPermissionsToRole(ctx, []string{pkgConst.UIDOfOpPermissionNamespaceAdmin}, roleId); err != nil { - return fmt.Errorf("insure op permissions in role failed: %v", err) - } - case pkgConst.UIDOfRoleSQLEAdmin: - if err = d.InsureOpPermissionsToRole(ctx, []string{pkgConst.UIDOfOpPermissionCreateWorkflow, - pkgConst.UIDOfOpPermissionAuditWorkflow, pkgConst.UIDOfOpPermissionExecuteWorkflow, - pkgConst.UIDOfOpPermissionViewOthersWorkflow, pkgConst.UIDOfOpPermissionSaveAuditPlan, - pkgConst.UIDOfOpPermissionViewOthersAuditPlan, pkgConst.UIDOfOpPermissionSQLQuery}, roleId); err != nil { - return fmt.Errorf("insure op permissions in role failed: %v", err) - } - case pkgConst.UIDOfRoleProvisionAdmin: - if err = d.InsureOpPermissionsToRole(ctx, []string{pkgConst.UIDOfOpPermissionAuthDBServiceData}, roleId); err != nil { + if rolePermissionsStrategy, ok := rolePermissionsMap[roleId]; !ok { + return fmt.Errorf("invalid role uid: %s", r.GetUID()) + } else { + if err = d.InsureOpPermissionsToRole(ctx, rolePermissionsStrategy.GetPermissions(), roleId); err != nil { return fmt.Errorf("insure op permissions in role failed: %v", err) } - default: - return fmt.Errorf("invalid role uid: %s", r.GetUID()) } } @@ -172,12 +221,19 @@ func (d *RoleUsecase) InitRoles(ctx context.Context) (err error) { func (d *RoleUsecase) CreateRole(ctx context.Context, currentUserUid, name, desc string, opPermissionUids []string) (uid string, err error) { // check { - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return "", fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return "", fmt.Errorf("user is not admin") + if canGlobalOp, err := d.opPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return "", fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return "", fmt.Errorf("user is not admin or global management permission") } } + existed, err := d.repo.CheckRoleExistByRoleName(ctx, name) + if err != nil { + return "", fmt.Errorf("check role exist failed: %v", err) + } + if existed { + return "", fmt.Errorf("role name already existed") + } u, err := newRole(name, desc) if err != nil { @@ -223,12 +279,15 @@ func (d *RoleUsecase) InsureOpPermissionsToRole(ctx context.Context, opPermissio } func (d *RoleUsecase) ListRole(ctx context.Context, option *ListRolesOption) (roles []*Role, total int64, err error) { - // DMS-125:空间管理员为内置角色,不对外展示 - option.FilterBy = append(option.FilterBy, pkgConst.FilterCondition{ - Field: string(RoleFieldUID), - Operator: pkgConst.FilterOperatorNotEqual, - Value: pkgConst.UIDOfRoleNamespaceAdmin, - }) + // DMS-125:项目管理员为内置角色,不对外展示 + option.FilterByOptions.Groups = append(option.FilterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(RoleFieldUID), + Operator: pkgConst.FilterOperatorNotEqual, + Value: pkgConst.UIDOfRoleProjectAdmin, + }, + )) roles, total, err = d.repo.ListRoles(ctx, option) if err != nil { return nil, 0, fmt.Errorf("list roles failed: %v", err) @@ -239,10 +298,10 @@ func (d *RoleUsecase) ListRole(ctx context.Context, option *ListRolesOption) (ro func (d *RoleUsecase) DelRole(ctx context.Context, currentUserUid, roleUid string) (err error) { // check { - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not admin") + if canGlobalOp, err := d.opPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not admin or global management permission") } } @@ -257,6 +316,10 @@ func (d *RoleUsecase) DelRole(ctx context.Context, currentUserUid, roleUid strin return fmt.Errorf("delete role from all members error: %v", err) } + if err := d.repo.DelRoleFromAllMemberGroups(tx, roleUid); nil != err { + return fmt.Errorf("delete role from all member groups error: %v", err) + } + if err := d.repo.DelAllOpPermissionsFromRole(tx, roleUid); nil != err { return fmt.Errorf("delete all op permissions from role error: %v", err) } @@ -291,10 +354,10 @@ func (d *RoleUsecase) CheckRoleExist(ctx context.Context, roleUids []string) (bo func (d *RoleUsecase) UpdateRole(ctx context.Context, currentUserUid, updateRoleUid string, isDisabled bool, desc *string, opPermissionUids []string) error { // check { - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not admin") + if canGlobalOp, err := d.opPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not admin or global management permission") } } diff --git a/internal/dms/biz/sms_configuration.go b/internal/dms/biz/sms_configuration.go new file mode 100644 index 000000000..1d65e37ed --- /dev/null +++ b/internal/dms/biz/sms_configuration.go @@ -0,0 +1,42 @@ +package biz + +import ( + "context" + + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" +) + +func initSmsConfiguration() (*model.SmsConfiguration, error) { + uid, err := pkgRand.GenStrUid() + if err != nil { + return nil, err + } + return &model.SmsConfiguration{ + Model: model.Model{ + UID: uid, + }, + }, nil +} + +type SmsConfigurationRepo interface { + UpdateSmsConfiguration(ctx context.Context, configuration *model.SmsConfiguration) error + GetLastSmsConfiguration(ctx context.Context) (*model.SmsConfiguration, error) +} + +type SmsConfigurationUseCase struct { + tx TransactionGenerator + repo SmsConfigurationRepo + userUsecase *UserUsecase + log *utilLog.Helper +} + +func NewSmsConfigurationUsecase(log utilLog.Logger, tx TransactionGenerator, repo SmsConfigurationRepo, userUsecase *UserUsecase) *SmsConfigurationUseCase { + return &SmsConfigurationUseCase{ + tx: tx, + repo: repo, + userUsecase: userUsecase, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.webhook_configuration")), + } +} diff --git a/internal/dms/biz/sms_configuration_ce.go b/internal/dms/biz/sms_configuration_ce.go new file mode 100644 index 000000000..d2e67eeea --- /dev/null +++ b/internal/dms/biz/sms_configuration_ce.go @@ -0,0 +1,34 @@ +//go:build !enterprise + +package biz + +import ( + "context" + "errors" + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/storage/model" +) + +var errNotSupportSms = errors.New("sms related functions are enterprise version functions") + +func (d *SmsConfigurationUseCase) UpdateSmsConfiguration(ctx context.Context, enable *bool, url *string, smsType *string, configuration *map[string]string) error { + + return errNotSupportSms +} + +func (d *SmsConfigurationUseCase) TestSmsConfiguration(ctx context.Context, recipientPhone string) error { + return errNotSupportSms +} + +func (d *SmsConfigurationUseCase) GetSmsConfiguration(ctx context.Context) (smsConfiguration *model.SmsConfiguration, exist bool, err error) { + return nil, false, errNotSupportSms +} + +func (d *SmsConfigurationUseCase) SendSmsCode(ctx context.Context, username string) (reply *dmsV1.SendSmsCodeReply, err error) { + return nil, errNotSupportSms +} + +func (d *SmsConfigurationUseCase) VerifySmsCode(code string, username string) (reply *dmsV1.VerifySmsCodeReply) { + return nil +} + diff --git a/internal/dms/biz/swagger.go b/internal/dms/biz/swagger.go new file mode 100644 index 000000000..62882cddf --- /dev/null +++ b/internal/dms/biz/swagger.go @@ -0,0 +1,44 @@ +package biz + +import ( + "github.com/actiontech/dms/api" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "github.com/labstack/echo/v4" +) + +type SwaggerUseCase struct { + log *utilLog.Helper + dmsProxyUsecase *DmsProxyUsecase +} + +func NewSwaggerUseCase(logger utilLog.Logger, dmsProxyUseCase *DmsProxyUsecase) *SwaggerUseCase { + return &SwaggerUseCase{ + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("biz.swagger")), + dmsProxyUsecase: dmsProxyUseCase, + } +} + +func (s *SwaggerUseCase) GetSwaggerContentByType(c echo.Context, targetName api.SwaggerType) ([]byte, error) { + target, err := s.dmsProxyUsecase.GetTargetByName(c.Request().Context(), string(targetName)) + if err != nil { + return nil, err + } + + url := target.URL.String() + "/swagger_file" + + header := map[string]string{ + echo.HeaderAuthorization: pkgHttp.DefaultDMSToken, + } + + resp := struct { + Content []byte `json:"content"` + }{} + + err = pkgHttp.Get(c.Request().Context(), url, header, nil, &resp) + if err != nil { + return nil, err + } + + return resp.Content, nil +} diff --git a/internal/dms/biz/system_variable.go b/internal/dms/biz/system_variable.go new file mode 100644 index 000000000..bcc315c27 --- /dev/null +++ b/internal/dms/biz/system_variable.go @@ -0,0 +1,78 @@ +package biz + +import ( + "context" + "fmt" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +const ( + SystemVariableSqlManageRawExpiredHours = "system_variable_sql_manage_raw_expired_hours" + SystemVariableWorkflowExpiredHours = "system_variable_workflow_expired_hours" + SystemVariableSqleUrl = "system_variable_sqle_url" + SystemVariableOperationRecordExpiredHours = "system_variable_operation_record_expired_hours" + SystemVariableCbOperationLogsExpiredHours = "system_variable_cb_operation_logs_expired_hours" + SystemVariableSSHPrimaryKey = "system_variable_ssh_primary_key" +) + +const ( + DefaultOperationRecordExpiredHours = 90 * 24 + DefaultCbOperationLogsExpiredHours = 90 * 24 + DefaultSystemVariableWorkflowExpiredHours = 30 * 24 + DefaultSystemVariableSqlManageRawExpiredHours= 30 * 24 +) + +// SystemVariable 系统变量业务模型 +type SystemVariable struct { + Key string `json:"key"` + Value string `json:"value"` +} + +// SystemVariableRepo 系统变量存储接口 +type SystemVariableRepo interface { + GetSystemVariables(ctx context.Context) (map[string]SystemVariable, error) + UpdateSystemVariables(ctx context.Context, variables []*SystemVariable) error +} + +// SystemVariableUsecase 系统变量业务逻辑 +type SystemVariableUsecase struct { + repo SystemVariableRepo + log *utilLog.Helper +} + +// NewSystemVariableUsecase 创建系统变量业务逻辑实例 +func NewSystemVariableUsecase(log utilLog.Logger, repo SystemVariableRepo) *SystemVariableUsecase { + return &SystemVariableUsecase{ + repo: repo, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.system_variable")), + } +} + +// GetSystemVariables 获取所有系统变量 +func (s *SystemVariableUsecase) GetSystemVariables(ctx context.Context) (map[string]SystemVariable, error) { + s.log.Infof("GetSystemVariables") + defer func() { + s.log.Infof("GetSystemVariables completed") + }() + + variables, err := s.repo.GetSystemVariables(ctx) + if err != nil { + return nil, fmt.Errorf("failed to get system variables: %v", err) + } + + return variables, nil +} + +// UpdateSystemVariables 更新系统变量 +func (s *SystemVariableUsecase) UpdateSystemVariables(ctx context.Context, variables []*SystemVariable) error { + s.log.Infof("UpdateSystemVariables") + defer func() { + s.log.Infof("UpdateSystemVariables completed") + }() + + if err := s.repo.UpdateSystemVariables(ctx, variables); err != nil { + return fmt.Errorf("failed to update system variables: %v", err) + } + + return nil +} diff --git a/internal/dms/biz/user.go b/internal/dms/biz/user.go index c963bffe0..ef3398eec 100644 --- a/internal/dms/biz/user.go +++ b/internal/dms/biz/user.go @@ -5,11 +5,16 @@ import ( "crypto/tls" "errors" "fmt" + "strconv" "time" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" pkgRand "github.com/actiontech/dms/pkg/rand" + "github.com/labstack/echo/v4" "github.com/actiontech/dms/pkg/dms-common/pkg/aes" @@ -21,9 +26,16 @@ import ( type UserAuthenticationType string const ( - UserAuthenticationTypeLDAP UserAuthenticationType = "ldap" // user verify through ldap - UserAuthenticationTypeDMS UserAuthenticationType = "dms" // user verify through dms - UserAuthenticationTypeOAUTH2 UserAuthenticationType = "oauth2" // user verify through oauth2 + UserAuthenticationTypeLDAP UserAuthenticationType = "ldap" // user verify through ldap + UserAuthenticationTypeDMS UserAuthenticationType = _const.DmsComponentName // user verify through dms + UserAuthenticationTypeOAUTH2 UserAuthenticationType = "oauth2" // user verify through oauth2 +) + +type UserSystem string + +const ( + UserSystemWorkbench UserSystem = "WORKBENCH" + UserSystemManagement UserSystem = "MANAGEMENT" ) func (u *UserAuthenticationType) String() string { @@ -70,18 +82,31 @@ type User struct { Name string Password string ThirdPartyUserID string + ThirdPartyUserInfo string Email string Phone string WxID string + Language string Desc string + Projects []string + TwoFactorEnabled bool UserAuthenticationType UserAuthenticationType Stat UserStat + // 用户系统类型 + System UserSystem // 用户上次登录时间的时间 LastLoginAt time.Time // 用户是否被删除 Deleted bool } +type AccessTokenInfo struct { + UID string + UserID uint + Token string + ExpiredTime time.Time +} + func initUsers() []*User { return []*User{ { @@ -103,7 +128,7 @@ func initUsers() []*User { } } -func newUser(args *CreateUserArgs) (*User, error) { +func newUser(args *CreateUserArgs) (user *User, err error) { if args.Name == "" { return nil, fmt.Errorf("name is empty") } @@ -112,15 +137,17 @@ func newUser(args *CreateUserArgs) (*User, error) { return nil, fmt.Errorf("password is empty") } } - uid, err := pkgRand.GenStrUid() - if err != nil { - return nil, err + if args.UID == "" { + args.UID, err = pkgRand.GenStrUid() + if err != nil { + return nil, err + } } if args.UserAuthenticationType == "" { args.UserAuthenticationType = UserAuthenticationTypeDMS } return &User{ - UID: uid, + UID: args.UID, Name: args.Name, Password: args.Password, Email: args.Email, @@ -129,6 +156,8 @@ func newUser(args *CreateUserArgs) (*User, error) { Desc: args.Desc, UserAuthenticationType: args.UserAuthenticationType, ThirdPartyUserID: args.ThirdPartyUserID, + ThirdPartyUserInfo: args.ThirdPartyUserInfo, + System: args.System, Stat: UserStatOK, }, nil } @@ -138,10 +167,10 @@ func (u *User) GetUID() string { } type ListUsersOption struct { - PageNumber uint32 - LimitPerPage uint32 - OrderBy UserField - FilterBy []pkgConst.FilterCondition + PageNumber uint32 + LimitPerPage uint32 + OrderBy UserField + FilterByOptions pkgConst.FilterOptions } type UserRepo interface { @@ -149,8 +178,10 @@ type UserRepo interface { UpdateUser(ctx context.Context, u *User) error CheckUserExist(ctx context.Context, userUids []string) (exists bool, err error) ListUsers(ctx context.Context, opt *ListUsersOption) (users []*User, total int64, err error) + CountUsers(ctx context.Context, opts []pkgConst.FilterCondition) (total int64, err error) DelUser(ctx context.Context, UserUid string) error GetUser(ctx context.Context, UserUid string) (*User, error) + GetUserIncludeDeleted(ctx context.Context, UserUid string) (*User, error) GetUserByName(ctx context.Context, userName string) (*User, error) AddUserToUserGroup(ctx context.Context, userGroupUid string, userUid string) error DelUserFromAllUserGroups(ctx context.Context, userUid string) error @@ -159,6 +190,38 @@ type UserRepo interface { GetUserGroupsByUser(ctx context.Context, userUid string) ([]*UserGroup, error) GetOpPermissionsByUser(ctx context.Context, userUid string) ([]*OpPermission, error) GetUserByThirdPartyUserID(ctx context.Context, thirdPartyUserUID string) (*User, error) + SaveAccessToken(ctx context.Context, accessTokenInfo *AccessTokenInfo) error + GetAccessTokenByUser(ctx context.Context, UserUid string) (*AccessTokenInfo, error) +} + +// SqlWorkbenchUser SqlWorkbench用户缓存 +type SqlWorkbenchUser struct { + DMSUserID string `json:"dms_user_id"` + SqlWorkbenchUserId int64 `json:"sql_workbench_user_id"` + SqlWorkbenchUsername string `json:"sql_workbench_username"` +} + +// SqlWorkbenchUserRepo SqlWorkbench用户缓存存储接口 +type SqlWorkbenchUserRepo interface { + GetSqlWorkbenchUserByDMSUserID(ctx context.Context, dmsUserID string) (*SqlWorkbenchUser, bool, error) + SaveSqlWorkbenchUserCache(ctx context.Context, user *SqlWorkbenchUser) error +} + +// SqlWorkbenchDatasource SqlWorkbench数据源缓存 +type SqlWorkbenchDatasource struct { + DMSDBServiceID string `json:"dms_db_service_id"` + DMSUserID string `json:"dms_user_id"` + DMSDBServiceFingerprint string `json:"dms_db_service_fingerprint"` + SqlWorkbenchDatasourceID int64 `json:"sql_workbench_datasource_id"` + Purpose string `json:"purpose"` +} + +// SqlWorkbenchDatasourceRepo SqlWorkbench数据源缓存存储接口 +type SqlWorkbenchDatasourceRepo interface { + GetSqlWorkbenchDatasourceByDMSDBServiceID(ctx context.Context, dmsDBServiceID, dmsUserID, purpose string) (*SqlWorkbenchDatasource, bool, error) + SaveSqlWorkbenchDatasourceCache(ctx context.Context, datasource *SqlWorkbenchDatasource) error + DeleteSqlWorkbenchDatasourceCache(ctx context.Context, dmsDBServiceID, dmsUserID, purpose string) error + GetSqlWorkbenchDatasourcesByUserID(ctx context.Context, dmsUserID string) ([]*SqlWorkbenchDatasource, error) } type UserUsecase struct { @@ -168,12 +231,16 @@ type UserUsecase struct { pluginUsecase *PluginUsecase opPermissionUsecase *OpPermissionUsecase OpPermissionVerifyUsecase *OpPermissionVerifyUsecase + loginConfigurationUsecase *LoginConfigurationUsecase ldapConfigurationUsecase *LDAPConfigurationUsecase + cloudBeaverRepo CloudbeaverRepo + gatewayUsecase *GatewayUsecase log *utilLog.Helper } func NewUserUsecase(log utilLog.Logger, tx TransactionGenerator, repo UserRepo, userGroupRepo UserGroupRepo, pluginUsecase *PluginUsecase, opPermissionUsecase *OpPermissionUsecase, - OpPermissionVerifyUsecase *OpPermissionVerifyUsecase, ldapConfigurationUsecase *LDAPConfigurationUsecase) *UserUsecase { + OpPermissionVerifyUsecase *OpPermissionVerifyUsecase, loginConfigurationUsecase *LoginConfigurationUsecase, ldapConfigurationUsecase *LDAPConfigurationUsecase, cloudBeaverRepo CloudbeaverRepo, gatewayUsecase *GatewayUsecase, +) *UserUsecase { return &UserUsecase{ tx: tx, repo: repo, @@ -181,44 +248,62 @@ func NewUserUsecase(log utilLog.Logger, tx TransactionGenerator, repo UserRepo, pluginUsecase: pluginUsecase, opPermissionUsecase: opPermissionUsecase, OpPermissionVerifyUsecase: OpPermissionVerifyUsecase, + loginConfigurationUsecase: loginConfigurationUsecase, ldapConfigurationUsecase: ldapConfigurationUsecase, + cloudBeaverRepo: cloudBeaverRepo, + gatewayUsecase: gatewayUsecase, log: utilLog.NewHelper(log, utilLog.WithMessageKey("biz.user")), } } -func (d *UserUsecase) UserLogin(ctx context.Context, name string, password string) (uid string, err error) { - loginVerifier, err := d.GetUserLoginVerifier(ctx, name) +func (d *UserUsecase) UserLogin(ctx context.Context, name string, password string) (uid string, twoFactorEnabled bool, phone string, err error) { + loginVerifier, twoFactorEnabled, phone, err := d.GetUserLoginVerifier(ctx, name) if err != nil { - return "", fmt.Errorf("get user login verifier failed: %v", err) + return "", twoFactorEnabled, phone, fmt.Errorf("get user login verifier failed: %v", err) } userUid, err := loginVerifier.Verify(ctx, name, password) if err != nil { - return "", fmt.Errorf("verify user login failed: %v", err) + return "", twoFactorEnabled, phone, fmt.Errorf("verify user login failed: %v", err) + } + + loginC, err := d.loginConfigurationUsecase.GetLoginConfiguration(ctx) + if err != nil { + return "", twoFactorEnabled, phone, err + } + if loginC.DisableUserPwdLogin { + isDmsAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, userUid) + if err != nil { + return "", twoFactorEnabled, phone, err + } + if !isDmsAdmin { + return "", twoFactorEnabled, phone, fmt.Errorf("normal user account password login has been disabled") + } } - return userUid, nil + return userUid, twoFactorEnabled, phone, nil } // GetUserLoginVerifier get login Verifier by user name and init login verifier -func (d *UserUsecase) GetUserLoginVerifier(ctx context.Context, name string) (UserLoginVerifier, error) { +func (d *UserUsecase) GetUserLoginVerifier(ctx context.Context, name string) (UserLoginVerifier, bool, string, error) { user, err := d.repo.GetUserByName(ctx, name) if nil != err && !errors.Is(err, pkgErr.ErrStorageNoData) { - return nil, fmt.Errorf("get user by name error: %v", err) + return nil, false, "", fmt.Errorf("get user by name error: %v", err) + } + towFactorEnabled, phone := false, "" + if user != nil { + towFactorEnabled = user.TwoFactorEnabled + phone = user.Phone } ldapC, _, err := d.ldapConfigurationUsecase.GetLDAPConfiguration(ctx) if err != nil { - return nil, fmt.Errorf("get ldap configuration failed: %v", err) + return nil, towFactorEnabled, phone, fmt.Errorf("get ldap configuration failed: %v", err) } loginVerifierType, exist := d.getLoginVerifierType(user, ldapC) - if err != nil { - return nil, fmt.Errorf("get login verifier type failed: %v", err) - } var userLoginVerifier UserLoginVerifier { - switch loginVerifierType { case loginVerifierTypeLDAP: userLoginVerifier = &LoginLdap{ @@ -235,13 +320,12 @@ func (d *UserUsecase) GetUserLoginVerifier(ctx context.Context, name string) (Us userUsecase: d, } case loginVerifierTypeUnknown: - return nil, fmt.Errorf("the user login type is unsupported") + return nil, towFactorEnabled, phone, fmt.Errorf("the user login type is unsupported") default: - return nil, fmt.Errorf("the user does not exist or the password is wrong") + return nil, towFactorEnabled, phone, fmt.Errorf("the user does not exist or the password is wrong") } - } - return userLoginVerifier, nil + return userLoginVerifier, towFactorEnabled, phone, nil } type verifierType int @@ -254,7 +338,6 @@ const ( // determine whether the login conditions are met according to the order of login priority func (d *UserUsecase) getLoginVerifierType(user *User, ldapC *LDAPConfiguration) (verifyType verifierType, userExist bool) { - // ldap login condition if ldapC != nil && ldapC.Enable { if user != nil && user.UserAuthenticationType == UserAuthenticationTypeLDAP { @@ -307,7 +390,6 @@ var errLdapLoginFailed = errors.New("ldap login failed, username and password do const ldapServerErrorFormat = "search user on ldap server failed: %v" func (l *LoginLdap) Verify(ctx context.Context, userName, password string) (userUID string, err error) { - ldapC := l.config var conn *ldap.Conn if l.config.EnableSSL { @@ -400,9 +482,11 @@ func (d *UserUsecase) AfterUserLogin(ctx context.Context, uid string) (err error } type CreateUserArgs struct { + UID string Name string Password string ThirdPartyUserID string + ThirdPartyUserInfo string Email string Phone string WxID string @@ -411,23 +495,40 @@ type CreateUserArgs struct { IsDisabled bool OpPermissionUIDs []string UserAuthenticationType UserAuthenticationType + System UserSystem } -func (d *UserUsecase) CreateUser(ctx context.Context, currentUserUid string, args *CreateUserArgs) (uid string, err error) { +func (d *UserUsecase) AddUser(ctx context.Context, currentUserUid string, args *CreateUserArgs) (uid string, err error) { // check { - if isAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return "", fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return "", fmt.Errorf("user is not admin") + isUserDMSAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid) + if err != nil { + return "", err + } + + var hasGlobalViewOrManagementPermission bool + for _, permissionUID := range args.OpPermissionUIDs { + if permissionUID == pkgConst.UIDOfOpPermissionGlobalView || permissionUID == pkgConst.UIDOfOpPermissionGlobalManagement { + hasGlobalViewOrManagementPermission = true + } + } + + if !isUserDMSAdmin && hasGlobalViewOrManagementPermission { + return "", fmt.Errorf("only admin can create user with global view or management permission") + } + + if canGlobalOp, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return "", fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return "", fmt.Errorf("user is not admin or global management permission") } user, err := d.repo.GetUserByName(ctx, args.Name) if err == nil { return "", fmt.Errorf("user %v is exist", user.Name) } - if nil != err && !errors.Is(err, pkgErr.ErrStorageNoData) { - return "", fmt.Errorf("get user by name error: %v", user) + if !errors.Is(err, pkgErr.ErrStorageNoData) { + return "", fmt.Errorf("get user by name error: %v", err) } } @@ -458,10 +559,20 @@ func (d *UserUsecase) CreateUser(ctx context.Context, currentUserUid string, arg if err := tx.Commit(d.log); err != nil { return "", fmt.Errorf("commit tx failed: %v", err) } - return u.UID, nil } +func (d *UserUsecase) CreateUser(ctx context.Context, currentUserUid string, args *CreateUserArgs) (uid string, err error) { + uid, err = d.AddUser(ctx, currentUserUid, args) + if err != nil { + return "", err + } + if err := d.gatewayUsecase.BroadcastAddUser(ctx, args); err != nil { + return "", err + } + return uid, nil +} + func (d *UserUsecase) InitUsers(ctx context.Context) (err error) { for _, u := range initUsers() { @@ -518,7 +629,6 @@ func (d *UserUsecase) InsureOpPermissionsInUser(ctx context.Context, opPermissio } else if !isGlobal { return fmt.Errorf("op permissions must be global") } - } if err := d.repo.ReplaceOpPermissionsInUser(ctx, userUid, opPermissionUids); err != nil { @@ -542,10 +652,32 @@ func (d *UserUsecase) DelUser(ctx context.Context, currentUserUid, UserUid strin if UserUid == pkgConst.UIDOfUserAdmin || UserUid == pkgConst.UIDOfUserSys { return fmt.Errorf("can not delete user admin or sys") } - if isAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not admin") + + isUserDMSAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid) + if err != nil { + return err + } + + permissionList, err := d.OpPermissionVerifyUsecase.GetUserOpPermission(ctx, UserUid) + if err != nil { + return err + } + + var hasGlobalViewOrManagementPermission bool + for _, permission := range permissionList { + if permission.OpPermissionUID == pkgConst.UIDOfOpPermissionGlobalView || permission.OpPermissionUID == pkgConst.UIDOfOpPermissionGlobalManagement { + hasGlobalViewOrManagementPermission = true + } + } + + if hasGlobalViewOrManagementPermission && !isUserDMSAdmin { + return fmt.Errorf("only admin can delete user with global view or management permission") + } + + if canGlobalOp, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not admin or global management permission") } } @@ -570,10 +702,19 @@ func (d *UserUsecase) DelUser(ctx context.Context, currentUserUid, UserUid strin return fmt.Errorf("del user from all user groups failed: %v", err) } + if err := d.cloudBeaverRepo.DeleteAllCloudbeaverCachesByUserId(tx, UserUid); nil != err { + return fmt.Errorf("delete cloudbeaver cache failed: %v", err) + } + if err := d.repo.DelUser(tx, UserUid); nil != err { return fmt.Errorf("delete user error: %v", err) } + // 调用其他服务对成员进行删除后处理 + if err := d.pluginUsecase.DelUserAfterHandle(ctx, UserUid); err != nil { + return err + } + if err := tx.Commit(d.log); err != nil { return fmt.Errorf("commit tx failed: %v", err) } @@ -601,53 +742,117 @@ func (d *UserUsecase) GetUser(ctx context.Context, userUid string) (*User, error return d.repo.GetUser(ctx, userUid) } -func (d *UserUsecase) UpdateUser(ctx context.Context, currentUserUid, updateUserUid string, isDisabled bool, - password, email, phone, wxId *string, userGroupUids []string, opPermissionUids []string) error { +type UpdateUserArgs struct { + UserUID string + IsDisabled bool + Password *string + Email *string + Phone *string + WxID *string + Language *string + UserGroupUIDs []string + OpPermissionUIDs []string + UserAuthenticationType *UserAuthenticationType + ThirdPartyUserInfo *string + ThirdPartyUserID *string + System *UserSystem +} + +func (d *UserUsecase) UpdateUser(ctx context.Context, currentUserUid string, args *UpdateUserArgs) (err error) { // checks { - if isDisabled { - if currentUserUid == updateUserUid { + isAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid) + if err != nil { + return err + } + + updateUserIsAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, args.UserUID) + if err != nil { + return err + } + + if !isAdmin && updateUserIsAdmin { + return fmt.Errorf("only admin can update admin user") + } + + if args.IsDisabled { + if currentUserUid == args.UserUID { return fmt.Errorf("can not disable current user") } - if pkgConst.UIDOfUserAdmin == updateUserUid { + if pkgConst.UIDOfUserAdmin == args.UserUID { return fmt.Errorf("can not disable admin user") } - if pkgConst.UIDOfUserSys == updateUserUid { + if pkgConst.UIDOfUserSys == args.UserUID { return fmt.Errorf("can not disable sys user") } } - if isAdmin, err := d.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not admin") + hasGlobalManagementOrViewPermission, err := d.OpPermissionVerifyUsecase.HasGlobalManagementOrViewPermission(ctx, args.UserUID) + if err != nil { + return err + } + + var updateGlobalViewOrManagementPermission bool + for _, permission := range args.OpPermissionUIDs { + if permission == pkgConst.UIDOfOpPermissionGlobalView || permission == pkgConst.UIDOfOpPermissionGlobalManagement { + updateGlobalViewOrManagementPermission = true + } + } + + // 1. 只有管理员才能更新拥有全局管理权限的用户,拥有全局管理权限的用户相互之间不能更新 + // 2. 拥有全局管理权限的用户不能更新普通用户为全局管理,全局统计权限 + if (hasGlobalManagementOrViewPermission || updateGlobalViewOrManagementPermission) && !isAdmin { + return fmt.Errorf("only admin can manage user with global manage or view permission") + } + + if canGlobalOp, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not admin or global management permission") } } - user, err := d.GetUser(ctx, updateUserUid) + user, err := d.GetUser(ctx, args.UserUID) if err != nil { return fmt.Errorf("get user failed: %v", err) } - if isDisabled { + if args.IsDisabled { user.Stat = UserStatDisable } else { user.Stat = UserStatOK } - if password != nil { - user.Password = *password + if args.Password != nil { + user.Password = *args.Password } - if email != nil { - user.Email = *email + if args.Email != nil { + user.Email = *args.Email } - if phone != nil { - user.Phone = *phone + if args.Phone != nil { + user.Phone = *args.Phone } - if wxId != nil { - user.WxID = *wxId + if args.WxID != nil { + user.WxID = *args.WxID + } + if args.Language != nil { + user.Language = *args.Language + } + if args.System != nil { + user.System = *args.System } + if user.GetUID() == pkgConst.UIDOfUserSys { + if args.ThirdPartyUserID != nil { + user.ThirdPartyUserID = *args.ThirdPartyUserID + } + if args.ThirdPartyUserInfo != nil { + user.ThirdPartyUserInfo = *args.ThirdPartyUserInfo + } + if args.UserAuthenticationType != nil { + user.UserAuthenticationType = *args.UserAuthenticationType + } + } if user.Stat == UserStatOK && user.Password == "" { return fmt.Errorf("password is needed when user is enabled") } @@ -659,11 +864,11 @@ func (d *UserUsecase) UpdateUser(ctx context.Context, currentUserUid, updateUser } }() - if err := d.InsureUserToUserGroups(tx, userGroupUids, user.GetUID()); err != nil { + if err := d.InsureUserToUserGroups(tx, args.UserGroupUIDs, user.GetUID()); err != nil { return fmt.Errorf("insure user to user groups failed: %v", err) } - if err := d.InsureOpPermissionsInUser(tx, opPermissionUids, user.GetUID()); err != nil { + if err := d.InsureOpPermissionsInUser(tx, args.OpPermissionUIDs, user.GetUID()); err != nil { return fmt.Errorf("insure op permissions in user failed: %v", err) } @@ -677,6 +882,49 @@ func (d *UserUsecase) UpdateUser(ctx context.Context, currentUserUid, updateUser return nil } +func (d *UserUsecase) UpdateCurrentUser(ctx context.Context, currentUserUid string, oldPassword, password, email, phone, wxId, language *string, twoFactorEnabled *bool, system *UserSystem) error { + user, err := d.GetUser(ctx, currentUserUid) + if err != nil { + return fmt.Errorf("get user failed: %v", err) + } + + // update password + if oldPassword != nil && password != nil { + if user.UserAuthenticationType == UserAuthenticationTypeLDAP { + return fmt.Errorf("the password of the ldap user cannot be changed or reset, because this password is meaningless") + } + if user.Password != *oldPassword { + return fmt.Errorf("old password is wrong") + } + user.Password = *password + } + + if email != nil { + user.Email = *email + } + if phone != nil { + user.Phone = *phone + } + if wxId != nil { + user.WxID = *wxId + } + if language != nil { + user.Language = *language + } + if twoFactorEnabled != nil { + user.TwoFactorEnabled = *twoFactorEnabled + } + if system != nil { + user.System = *system + } + + if err := d.repo.UpdateUser(ctx, user); nil != err { + return fmt.Errorf("update current user error: %v", err) + } + + return nil +} + func (d *UserUsecase) GetUserByThirdPartyUserID(ctx context.Context, userUid string) (*User, bool, error) { user, err := d.repo.GetUserByThirdPartyUserID(ctx, userUid) if err != nil { @@ -700,5 +948,101 @@ func (d *UserUsecase) GetUserByName(ctx context.Context, userName string) (*User } func (d *UserUsecase) SaveUser(ctx context.Context, user *User) error { - return d.repo.UpdateUser(ctx, user) + if err := d.repo.UpdateUser(ctx, user); err != nil { + return err + } + if err := d.gatewayUsecase.BroadcastUpdateUser(ctx, user); err != nil { + d.log.Errorf("broadcast update user failed: %v", err) + } + return nil +} + +func (d *UserUsecase) GetBizUserWithNameByUids(ctx context.Context, uids []string) []UIdWithName { + if len(uids) == 0 { + return []UIdWithName{} + } + uidWithNameCacheCache.ulock.Lock() + defer uidWithNameCacheCache.ulock.Unlock() + if uidWithNameCacheCache.UserCache == nil { + uidWithNameCacheCache.UserCache = make(map[string]UIdWithName) + } + ret := make([]UIdWithName, 0) + for _, uid := range uids { + userCache, ok := uidWithNameCacheCache.UserCache[uid] + if !ok { + userCache = UIdWithName{ + Uid: uid, + } + user, err := d.repo.GetUser(ctx, uid) + if err == nil { + userCache.Name = user.Name + uidWithNameCacheCache.UserCache[user.UID] = userCache + } else { + d.log.Errorf("get user for cache err: %v", err) + } + } + ret = append(ret, userCache) + } + return ret +} + +func (d *UserUsecase) GetBizUserIncludeDeletedWithNameByUids(ctx context.Context, uids []string) []UIdWithName { + if len(uids) == 0 { + return []UIdWithName{} + } + ret := make([]UIdWithName, 0) + for _, uid := range uids { + user, ok := uidWithNameCacheCache.UserCache[uid] + if !ok { + user = UIdWithName{ + Uid: uid, + } + userInfo, err := d.repo.GetUserIncludeDeleted(ctx, uid) + if err == nil { + user.Name = userInfo.Name + } else { + d.log.Errorf("get user for cache err: %v", err) + } + } + ret = append(ret, user) + } + return ret +} + +func (d *UserUsecase) SaveAccessToken(ctx context.Context, userId string, token string, expiredTime time.Time) error { + userIdInt, err := strconv.Atoi(userId) + if err != nil { + return err + } + uid, err := pkgRand.GenStrUid() + if err != nil { + return err + } + + tokenInfo := &AccessTokenInfo{UID: uid, UserID: uint(userIdInt), Token: token, ExpiredTime: expiredTime} + return d.repo.SaveAccessToken(ctx, tokenInfo) +} + +func (d *UserUsecase) GetAccessTokenByUser(ctx context.Context, UserUid string) (*AccessTokenInfo, error) { + accessTokenInfo, err := d.repo.GetAccessTokenByUser(ctx, UserUid) + if err != nil { + return nil, err + } + return accessTokenInfo, nil +} + +func (d *UserUsecase) GetUserLanguageByEchoCtx(c echo.Context) string { + uid, err := jwt.GetUserUidStrFromContext(c) + if err != nil { + return "" + } + if uid == pkgConst.UIDOfUserSys { + // 系统用户直接通过请求头AcceptLanguage确定语言 + return i18nPkg.GetLangByAcceptLanguage(c) + } + user, err := d.GetUser(c.Request().Context(), uid) + if err != nil { + return "" + } + return user.Language } diff --git a/internal/dms/biz/user_group.go b/internal/dms/biz/user_group.go index 41e86efa3..690ff68fe 100644 --- a/internal/dms/biz/user_group.go +++ b/internal/dms/biz/user_group.go @@ -61,10 +61,10 @@ func (u *UserGroup) GetUID() string { } type ListUserGroupsOption struct { - PageNumber uint32 - LimitPerPage uint32 - OrderBy UserGroupField - FilterBy []pkgConst.FilterCondition + PageNumber uint32 + LimitPerPage uint32 + OrderBy UserGroupField + FilterByOptions pkgConst.FilterOptions } type UserGroupRepo interface { @@ -109,10 +109,10 @@ type CreateUserGroupArgs struct { func (d *UserGroupUsecase) CreateUserGroup(ctx context.Context, currentUserUid string, args *CreateUserGroupArgs) (uid string, err error) { // check { - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return "", fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return "", fmt.Errorf("user is not admin") + if canGlobalOp, err := d.opPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return "", fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return "", fmt.Errorf("user is not admin or global management permission") } } @@ -165,10 +165,10 @@ func (d *UserGroupUsecase) DelUserGroup(ctx context.Context, currentUserUid, Use // check { - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not admin") + if canGlobalOp, err := d.opPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not admin or global management permission") } } @@ -203,10 +203,10 @@ func (d *UserGroupUsecase) GetUserGroup(ctx context.Context, userGroupUid string func (d *UserGroupUsecase) UpdateUserGroup(ctx context.Context, currentUserUid, updateUserGroupUid string, isDisabled bool, desc *string, userUids []string) error { // check { - if isAdmin, err := d.opPermissionVerifyUsecase.IsUserDMSAdmin(ctx, currentUserUid); err != nil { - return fmt.Errorf("check user is admin failed: %v", err) - } else if !isAdmin { - return fmt.Errorf("user is not admin") + if canGlobalOp, err := d.opPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user is admin or global management permission : %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not admin or global management permission") } } diff --git a/internal/dms/conf/config.go b/internal/dms/conf/config.go new file mode 100644 index 000000000..457e06972 --- /dev/null +++ b/internal/dms/conf/config.go @@ -0,0 +1,3 @@ +package conf + +var Version string diff --git a/internal/dms/conf/options.go b/internal/dms/conf/options.go index 2138a43cd..d982d42fe 100644 --- a/internal/dms/conf/options.go +++ b/internal/dms/conf/options.go @@ -1,27 +1,20 @@ package conf -import ( - utilConf "github.com/actiontech/dms/pkg/dms-common/pkg/config" - utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" -) - type Options struct { - Data struct { - Database struct { - UserName string `yaml:"username" ` - Password string `yaml:"password" ` - Host string `yaml:"host" validate:"required"` - Port string `yaml:"port" validate:"required"` - Database string `yaml:"database" validate:"required"` - Debug bool `yaml:"debug"` - } `yaml:"database"` - } `yaml:"data"` + Database struct { + UserName string `yaml:"username" ` + Password string `yaml:"password" ` + Host string `yaml:"host" validate:"required"` + Port string `yaml:"port" validate:"required"` + Database string `yaml:"database" validate:"required"` + Debug bool `yaml:"debug"` + } `yaml:"database"` } -func ReadOptions(log utilLog.Logger, path string) (*Options, error) { - var opts Options - if err := utilConf.ParseYamlFile(log, path, &opts); err != nil { - return nil, err - } - return &opts, nil -} +// func ReadOptions(log utilLog.Logger, path string) (*Options, error) { +// var opts Options +// if err := utilConf.ParseYamlFile(log, path, &opts); err != nil { +// return nil, err +// } +// return &opts, nil +// } diff --git a/internal/dms/pkg/constant/const.go b/internal/dms/pkg/constant/const.go index 7211ed878..73ed4d0a1 100644 --- a/internal/dms/pkg/constant/const.go +++ b/internal/dms/pkg/constant/const.go @@ -1,32 +1,221 @@ package constant -import "fmt" +import ( + "fmt" + + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) // internel build-in uid const ( - UIDOfOpPermissionCreateNamespace = "700001" - UIDOfOpPermissionNamespaceAdmin = "700002" - UIDOfOpPermissionCreateWorkflow = "700003" - UIDOfOpPermissionAuditWorkflow = "700004" - UIDOfOpPermissionAuthDBServiceData = "700005" - UIDOfOpPermissionExecuteWorkflow = "700006" - UIDOfOpPermissionViewOthersWorkflow = "700007" - UIDOfOpPermissionViewOthersAuditPlan = "700008" - UIDOfOpPermissionSaveAuditPlan = "700009" - UIDOfOpPermissionSQLQuery = "700010" + UIDOfOpPermissionCreateProject = "700001" + UIDOfOpPermissionProjectAdmin = "700002" + UIDOfOpPermissionCreateWorkflow = "700003" + UIDOfOpPermissionAuditWorkflow = "700004" + UIDOfOpPermissionAuthDBServiceData = "700005" + UIDOfOpPermissionExecuteWorkflow = "700006" + UIDOfOpPermissionViewOthersWorkflow = "700007" + UIDOfOpPermissionViewOthersAuditPlan = "700008" + UIDOfOpPermissionSaveAuditPlan = "700009" + UIDOfOpPermissionSQLQuery = "700010" + UIDOfOpPermissionExportApprovalReject = "700011" + UIDOfOpPermissionExportCreate = "700012" + UIDOfOpPermissionCreateOptimization = "700013" + UIDOfOpPermissionViewOthersOptimization = "700014" + UIDOfOpPermissionCreatePipeline = "700015" + // UIDOfOpPermissionGlobalView 可以查看全局资源,但是不能修改资源 + UIDOfOpPermissionGlobalView = "700016" + // UIDOfOpPermissionGlobalManagement 可以操作和查看全局资源,但是权限级别低于admin,admin可以修改全局资源权限,全局资源权限不能修改admin + // 拥有全局资源权限用户不能同级权限用户 + UIDOfOpPermissionGlobalManagement = "700017" + UIDOfOrdinaryUser = "700018" + UIDOfOpPermissionViewOperationRecord = "700019" + UIDOfOpPermissionViewExportTask = "700020" + UIDOfPermissionViewQuickAuditRecord = "700021" + UIDOfOpPermissionViewIDEAuditRecord = "700022" + UIDOfOpPermissionViewOptimizationRecord = "700023" + UIDOfOpPermissionViewVersionManage = "700024" + UIDOfOpPermissionVersionManage = "700025" + UIdOfOpPermissionViewPipeline = "700026" + UIdOfOpPermissionManageProjectDataSource = "700028" + UIdOfOpPermissionManageAuditRuleTemplate = "700029" + UIdOfOpPermissionManageApprovalTemplate = "700030" + UIdOfOpPermissionManageMember = "700031" + UIdOfOpPermissionPushRule = "700032" + UIdOfOpPermissionMangeAuditSQLWhiteList = "700033" + UIdOfOpPermissionManageSQLMangeWhiteList = "700034" + UIdOfOpPermissionManageRoleMange = "700035" + UIdOfOpPermissionDesensitization = "700036" + UIDOfOpPermissionViewSQLInsight = "700037" + UIdOfOpPermissionMaskingAudit = "700038" UIDOfDMSConfig = "700100" UIDOfUserAdmin = "700200" UIDOfUserSys = "700201" - UIDOfNamespaceDefault = "700300" + UIDOfProjectDefault = "700300" - UIDOfRoleNamespaceAdmin = "700400" - UIDOfRoleSQLEAdmin = "700401" - UIDOfRoleProvisionAdmin = "700402" + UIDOfRoleProjectAdmin = "700400" + UIDOfRoleDevEngineer = "700403" + UIDOfRoleDevManager = "700404" + UIDOfRoleOpsEngineer = "700405" ) +func ConvertPermissionIdToType(opPermissionUid string) (apiOpPermissionTyp dmsCommonV1.OpPermissionType, err error) { + switch opPermissionUid { + case UIDOfOpPermissionCreateWorkflow: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeCreateWorkflow + case UIDOfOpPermissionAuditWorkflow: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeAuditWorkflow + case UIDOfOpPermissionAuthDBServiceData: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeAuthDBServiceData + case UIDOfOpPermissionProjectAdmin: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeProjectAdmin + case UIDOfOpPermissionCreateProject: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeCreateProject + case UIDOfOpPermissionExecuteWorkflow: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeExecuteWorkflow + case UIDOfOpPermissionViewOthersWorkflow: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeViewOthersWorkflow + case UIDOfOpPermissionSaveAuditPlan: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeSaveAuditPlan + case UIDOfOpPermissionViewOthersAuditPlan: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeViewOtherAuditPlan + case UIDOfOpPermissionViewSQLInsight: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeViewSQLInsight + case UIDOfOpPermissionSQLQuery: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeSQLQuery + case UIDOfOpPermissionExportApprovalReject: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeAuditExportWorkflow + case UIDOfOpPermissionExportCreate: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeExportCreate + case UIDOfOpPermissionCreatePipeline: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeCreatePipeline + case UIDOfOpPermissionViewOperationRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewOperationRecord + case UIDOfOpPermissionViewExportTask: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewExportTask + case UIDOfPermissionViewQuickAuditRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewQuickAuditRecord + case UIDOfOpPermissionViewIDEAuditRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewIDEAuditRecord + case UIDOfOpPermissionViewOptimizationRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewOptimizationRecord + case UIDOfOpPermissionViewVersionManage: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewVersionManage + case UIDOfOpPermissionVersionManage: + apiOpPermissionTyp = dmsCommonV1.OpPermissionVersionManage + case UIdOfOpPermissionViewPipeline: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewPipeline + case UIdOfOpPermissionManageProjectDataSource: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageProjectDataSource + case UIdOfOpPermissionManageAuditRuleTemplate: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageAuditRuleTemplate + case UIdOfOpPermissionManageApprovalTemplate: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageApprovalTemplate + case UIdOfOpPermissionManageMember: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageMember + case UIdOfOpPermissionPushRule: + apiOpPermissionTyp = dmsCommonV1.OpPermissionPushRule + case UIdOfOpPermissionMangeAuditSQLWhiteList: + apiOpPermissionTyp = dmsCommonV1.OpPermissionMangeAuditSQLWhiteList + case UIdOfOpPermissionManageSQLMangeWhiteList: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageSQLMangeWhiteList + case UIdOfOpPermissionManageRoleMange: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageRoleMange + case UIdOfOpPermissionDesensitization: + apiOpPermissionTyp = dmsCommonV1.OpPermissionDesensitization + case UIdOfOpPermissionMaskingAudit: + apiOpPermissionTyp = dmsCommonV1.OpPermissionMaskingAudit + case UIDOfOrdinaryUser: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeNone + default: + return dmsCommonV1.OpPermissionTypeUnknown, fmt.Errorf("get user op permission type error: invalid op permission uid: %v", opPermissionUid) + + } + return apiOpPermissionTyp, nil +} + +func ConvertPermissionTypeToId(opPermissionType dmsCommonV1.OpPermissionType) (permissionId string, err error) { + switch opPermissionType { + case dmsCommonV1.OpPermissionTypeCreateWorkflow: + permissionId = UIDOfOpPermissionCreateWorkflow + case dmsCommonV1.OpPermissionTypeAuditWorkflow: + permissionId = UIDOfOpPermissionAuditWorkflow + case dmsCommonV1.OpPermissionTypeAuthDBServiceData: + permissionId = UIDOfOpPermissionAuthDBServiceData + case dmsCommonV1.OpPermissionTypeProjectAdmin: + permissionId = UIDOfOpPermissionProjectAdmin + case dmsCommonV1.OpPermissionTypeCreateProject: + permissionId = UIDOfOpPermissionCreateProject + case dmsCommonV1.OpPermissionTypeGlobalManagement: + permissionId = UIDOfOpPermissionGlobalManagement + case dmsCommonV1.OpPermissionTypeGlobalView: + permissionId = UIDOfOpPermissionGlobalView + case dmsCommonV1.OpPermissionTypeExecuteWorkflow: + permissionId = UIDOfOpPermissionExecuteWorkflow + case dmsCommonV1.OpPermissionTypeViewOthersWorkflow: + permissionId = UIDOfOpPermissionViewOthersWorkflow + case dmsCommonV1.OpPermissionTypeSaveAuditPlan: + permissionId = UIDOfOpPermissionSaveAuditPlan + case dmsCommonV1.OpPermissionTypeViewOtherAuditPlan: + permissionId = UIDOfOpPermissionViewOthersAuditPlan + case dmsCommonV1.OpPermissionTypeViewSQLInsight: + permissionId = UIDOfOpPermissionViewSQLInsight + case dmsCommonV1.OpPermissionTypeSQLQuery: + permissionId = UIDOfOpPermissionSQLQuery + case dmsCommonV1.OpPermissionTypeAuditExportWorkflow: + permissionId = UIDOfOpPermissionExportApprovalReject + case dmsCommonV1.OpPermissionTypeExportCreate: + permissionId = UIDOfOpPermissionExportCreate + case dmsCommonV1.OpPermissionTypeCreatePipeline: + permissionId = UIDOfOpPermissionCreatePipeline + case dmsCommonV1.OpPermissionViewOperationRecord: + permissionId = UIDOfOpPermissionViewOperationRecord + case dmsCommonV1.OpPermissionViewExportTask: + permissionId = UIDOfOpPermissionViewExportTask + case dmsCommonV1.OpPermissionViewQuickAuditRecord: + permissionId = UIDOfPermissionViewQuickAuditRecord + case dmsCommonV1.OpPermissionViewIDEAuditRecord: + permissionId = UIDOfOpPermissionViewIDEAuditRecord + case dmsCommonV1.OpPermissionViewOptimizationRecord: + permissionId = UIDOfOpPermissionViewOptimizationRecord + case dmsCommonV1.OpPermissionViewVersionManage: + permissionId = UIDOfOpPermissionViewVersionManage + case dmsCommonV1.OpPermissionVersionManage: + permissionId = UIDOfOpPermissionVersionManage + case dmsCommonV1.OpPermissionViewPipeline: + permissionId = UIdOfOpPermissionViewPipeline + case dmsCommonV1.OpPermissionManageProjectDataSource: + permissionId = UIdOfOpPermissionManageProjectDataSource + case dmsCommonV1.OpPermissionManageAuditRuleTemplate: + permissionId = UIdOfOpPermissionManageAuditRuleTemplate + case dmsCommonV1.OpPermissionManageApprovalTemplate: + permissionId = UIdOfOpPermissionManageApprovalTemplate + case dmsCommonV1.OpPermissionManageMember: + permissionId = UIdOfOpPermissionManageMember + case dmsCommonV1.OpPermissionPushRule: + permissionId = UIdOfOpPermissionPushRule + case dmsCommonV1.OpPermissionMangeAuditSQLWhiteList: + permissionId = UIdOfOpPermissionMangeAuditSQLWhiteList + case dmsCommonV1.OpPermissionManageSQLMangeWhiteList: + permissionId = UIdOfOpPermissionManageSQLMangeWhiteList + case dmsCommonV1.OpPermissionManageRoleMange: + permissionId = UIdOfOpPermissionManageRoleMange + case dmsCommonV1.OpPermissionDesensitization: + permissionId = UIdOfOpPermissionDesensitization + case dmsCommonV1.OpPermissionMaskingAudit: + permissionId = UIdOfOpPermissionMaskingAudit + case dmsCommonV1.OpPermissionTypeNone: + permissionId = UIDOfOrdinaryUser + default: + return "", fmt.Errorf("get user op permission id error: invalid op permission type: %v", opPermissionType) + } + + return permissionId, nil +} + type DBType string func (d DBType) String() string { @@ -37,14 +226,31 @@ func ParseDBType(s string) (DBType, error) { switch s { case "MySQL": return DBTypeMySQL, nil + case "TDSQL For InnoDB": + return DBTypeTDSQLForInnoDB, nil + case "TiDB": + return DBTypeTiDB, nil case "PostgreSQL": return DBTypePostgreSQL, nil case "Oracle": return DBTypeOracle, nil - case "SQLServer": + case "DB2": + return DBTypeDB2, nil + case "SQL Server": return DBTypeSQLServer, nil - case "OceanBaseMySQL": + case "OceanBase For MySQL": return DBTypeOceanBaseMySQL, nil + case "GoldenDB": + return DBTypeGoldenDB, nil + case "TBase": + return DBTypeTBase, nil + case "Hive": + return DBTypeHive, nil + case "DM": + return DBTypeDM, nil + case "GaussDB for MySQL": + return DBTypeGaussDB, nil + default: return "", fmt.Errorf("invalid db type: %s", s) } @@ -53,15 +259,45 @@ func ParseDBType(s string) (DBType, error) { const ( DBTypeMySQL DBType = "MySQL" DBTypePostgreSQL DBType = "PostgreSQL" + DBTypeTiDB DBType = "TiDB" + DBTypeSQLServer DBType = "SQL Server" DBTypeOracle DBType = "Oracle" - DBTypeSQLServer DBType = "SQLServer" - DBTypeOceanBaseMySQL DBType = "OceanBaseMySQL" + DBTypeDB2 DBType = "DB2" + DBTypeOceanBaseMySQL DBType = "OceanBase For MySQL" + DBTypeTDSQLForInnoDB DBType = "TDSQL For InnoDB" + DBTypeGoldenDB DBType = "GoldenDB" + DBTypeTBase DBType = "TBase" + DBTypeHive DBType = "Hive" + DBTypeDM DBType = "达梦(DM)" + DBTypeGaussDB DBType = "GaussDB / openGauss" ) +var supportedDataExportDBTypes = map[DBType]struct{}{ + DBTypeMySQL: {}, + DBTypePostgreSQL: {}, + DBTypeOracle: {}, + DBTypeSQLServer: {}, + DBTypeOceanBaseMySQL: {}, + DBTypeHive: {}, + DBTypeDM: {}, +} + +func CheckDBTypeIfDataExportSupported(dbtype string) bool { + dbType, err := ParseDBType(dbtype) + if err != nil { + return false + } + _, ok := supportedDataExportDBTypes[dbType] + return ok +} + type FilterCondition struct { - Field string - Operator FilterOperator - Value interface{} + // Filter For Preload Table + Table string + KeywordSearch bool + Field string + Operator FilterOperator + Value interface{} } type FilterOperator string @@ -71,16 +307,62 @@ const ( FilterOperatorIsNull FilterOperator = "isNull" FilterOperatorNotEqual FilterOperator = "<>" FilterOperatorContains FilterOperator = "like" + FilterOperatorNotContains FilterOperator = "not like" FilterOperatorGreaterThanOrEqual FilterOperator = ">=" FilterOperatorLessThanOrEqual FilterOperator = "<=" FilterOperatorIn FilterOperator = "in" ) +type FilterLogic string + +const ( + FilterLogicAnd FilterLogic = "AND" + FilterLogicOr FilterLogic = "OR" +) + +type FilterConditionGroup struct { + Logic FilterLogic + Conditions []FilterCondition + Groups []FilterConditionGroup +} + +type FilterOptions struct { + Logic FilterLogic + Groups []FilterConditionGroup +} + +func NewFilterOptions(logic FilterLogic, groups ...FilterConditionGroup) FilterOptions { + return FilterOptions{ + Logic: logic, + Groups: groups, + } +} + +func NewConditionGroup(logic FilterLogic, conditions ...FilterCondition) FilterConditionGroup { + return FilterConditionGroup{ + Logic: logic, + Conditions: conditions, + } +} + +func ConditionsToFilterOptions(conditions []FilterCondition) FilterOptions { + if len(conditions) == 0 { + return FilterOptions{} + } + + return FilterOptions{ + Logic: FilterLogicAnd, + Groups: []FilterConditionGroup{NewConditionGroup(FilterLogicAnd, conditions...)}, + } +} + type DBServiceSourceName string const ( - DBServiceSourceNameDMP DBServiceSourceName = "Actiontech DMP" - DBServiceSourceNameDMS DBServiceSourceName = "Actiontech DMS" + DBServiceSourceNameDMP DBServiceSourceName = "Actiontech DMP" + DBServiceSourceNameDMS DBServiceSourceName = "Actiontech DMS" + DBServiceSourceNameSQLE DBServiceSourceName = "SQLE" + DBServiceSourceNameExpandService DBServiceSourceName = "Expand Service" ) func ParseDBServiceSource(s string) (DBServiceSourceName, error) { @@ -89,11 +371,16 @@ func ParseDBServiceSource(s string) (DBServiceSourceName, error) { return DBServiceSourceNameDMP, nil case string(DBServiceSourceNameDMS): return DBServiceSourceNameDMS, nil + case string(DBServiceSourceNameSQLE): + return DBServiceSourceNameSQLE, nil + case string(DBServiceSourceNameExpandService): + return DBServiceSourceNameExpandService, nil default: return "", fmt.Errorf("invalid data object source name: %s", s) } } const ( - DMSToken = "dms-token" + DMSToken = "dms-token" + DMSRefreshToken = "dms-refresh-token" ) diff --git a/internal/dms/pkg/errors/error.go b/internal/dms/pkg/errors/error.go index e343cda06..9bea0943a 100644 --- a/internal/dms/pkg/errors/error.go +++ b/internal/dms/pkg/errors/error.go @@ -30,6 +30,6 @@ func WrapStorageErr(log *utilLog.Helper, originalErr error) error { func WrapErrStorageNoData(log *utilLog.Helper, originalErr error) error { err := fmt.Errorf("%w:%v", ErrStorageNoData, originalErr) - log.Errorf(err.Error()) + // log.Errorf(err.Error()) return err } diff --git a/internal/dms/service/basic.go b/internal/dms/service/basic.go new file mode 100644 index 000000000..c2897d6e9 --- /dev/null +++ b/internal/dms/service/basic.go @@ -0,0 +1,63 @@ +package service + +import ( + "context" + "errors" + + v1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" +) + +func (d *DMSService) GetBasicInfo(ctx context.Context) (reply *v1.GetBasicInfoReply, err error) { + basic, err := d.BasicUsecase.GetBasicInfo(ctx) + if nil != err { + return nil, err + } + + ret := &v1.BasicInfo{ + LogoUrl: basic.LogoUrl, + Title: basic.Title, + } + + for _, item := range basic.Components { + ret.Components = append(ret.Components, v1.ComponentNameWithVersion{ + Name: item.Name, + Version: item.Version, + }) + } + + return &v1.GetBasicInfoReply{ + Data: ret, + }, nil +} + +func (d *DMSService) GetStaticLogo(ctx context.Context) (*v1.GetStaticLogoReply, string, error) { + basicConfig, contentType, err := d.BasicUsecase.GetStaticLogo(ctx) + if nil != err { + return nil, contentType, err + } + + return &v1.GetStaticLogoReply{ + File: basicConfig.Logo, + }, contentType, nil +} + +func (d *DMSService) Personalization(ctx context.Context, req *v1.PersonalizationReq) error { + if req.Title == "" && req.File == nil { + return errors.New("one of the parameters title, logo is required") + } + + params := &biz.BasicConfigParams{ + Title: req.Title, + File: req.File, + } + + return d.BasicUsecase.Personalization(ctx, params) +} + +func (d *DMSService) GetLimitAndOffset(pageIndex, pageSize uint32) (limit, offset int) { + if pageIndex >= 1 { + offset = int((pageIndex - 1) * pageSize) + } + return int(pageSize), offset +} diff --git a/internal/dms/service/business_tag.go b/internal/dms/service/business_tag.go new file mode 100644 index 000000000..d88a64304 --- /dev/null +++ b/internal/dms/service/business_tag.go @@ -0,0 +1,113 @@ +package service + +import ( + "context" + "fmt" + + v1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" +) + +func (d *DMSService) CreateBusinessTag(ctx context.Context, currentUserUid string, businessTag *v1.BusinessTag) (err error) { + d.log.Infof("CreateBusinessTag.req=%v", businessTag) + defer func() { + d.log.Infof("CreateBusinessTag.req=%v;error=%v", businessTag, err) + }() + + // 权限校验 + if canGlobalOp, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user op permission failed: %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not project admin or global op permission user") + } + + if err := d.BusinessTagUsecase.CreateBusinessTag(ctx, businessTag.Name); err != nil { + return fmt.Errorf("create business tag failed: %w", err) + } + + return nil +} + +func (d *DMSService) UpdateBusinessTag(ctx context.Context, currentUserUid string, businessTagUID string, businessTagForUpdate *v1.BusinessTag) (err error) { + d.log.Infof("UpdateBusinessTag.req=%v", businessTagForUpdate) + defer func() { + d.log.Infof("UpdateBusinessTag.req=%v;error=%v", businessTagForUpdate, err) + }() + + // 权限校验 + if canGlobalOp, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user op permission failed: %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not project admin or global op permission user") + } + + if err := d.BusinessTagUsecase.UpdateBusinessTag(ctx, businessTagUID, businessTagForUpdate.Name); err != nil { + return fmt.Errorf("update business tag failed: %w", err) + } + return nil +} + +func (d *DMSService) DeleteBusinessTag(ctx context.Context, currentUserUid string, businessTagUID string) (err error) { + d.log.Infof("DeleteBusinessTag.req=%v", businessTagUID) + defer func() { + d.log.Infof("DeleteBusinessTag.req=%v;error=%v", businessTagUID, err) + }() + + // 权限校验 + if canGlobalOp, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid); err != nil { + return fmt.Errorf("check user op permission failed: %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not project admin or global op permission user") + } + + // 业务标签被项目关联时,不允许删除 + filterBy := []pkgConst.FilterCondition{ + { + Field: string(biz.ProjectFieldBusinessTagUID), + Operator: pkgConst.FilterOperatorEqual, + Value: businessTagUID, + }, + } + + _, total, err := d.ProjectUsecase.ListProject(ctx, &biz.ListProjectsOption{FilterByOptions: pkgConst.ConditionsToFilterOptions(filterBy)}, currentUserUid) + if err != nil { + return fmt.Errorf("list project failed: %w", err) + } + if total > 0 { + return fmt.Errorf("business tag is used by project, please detach business tag with project first") + } + + if err := d.BusinessTagUsecase.DeleteBusinessTag(ctx, businessTagUID); err != nil { + return fmt.Errorf("delete business tag failed: %w", err) + } + + return nil +} + +func (d *DMSService) ListBusinessTags(ctx context.Context, req *v1.ListBusinessTagReq) (reply *v1.ListBusinessTagsReply, err error) { + d.log.Infof("ListBusinessTags.req=%v", *req) + defer func() { + d.log.Infof("ListBusinessTags.req=%v;error=%v", *req, err) + }() + limit, offset := d.GetLimitAndOffset(req.PageIndex, req.PageSize) + bizBusinessTags, count, err := d.BusinessTagUsecase.ListBusinessTags(ctx, &biz.ListBusinessTagsOption{ + Limit: limit, + Offset: offset, + FuzzyKeyword: req.FuzzyKeyword, + }) + if err != nil { + return nil, fmt.Errorf("list business tags failed: %w", err) + } + businessTags := make([]*v1.BusinessTag, 0, len(bizBusinessTags)) + for _, bizBusinessTag := range bizBusinessTags { + businessTags = append(businessTags, &v1.BusinessTag{ + UID: bizBusinessTag.UID, + Name: bizBusinessTag.Name, + }) + } + return &v1.ListBusinessTagsReply{ + Data: businessTags, + Total: count, + }, nil +} diff --git a/internal/dms/service/cb_operation_log.go b/internal/dms/service/cb_operation_log.go new file mode 100644 index 000000000..47b10d741 --- /dev/null +++ b/internal/dms/service/cb_operation_log.go @@ -0,0 +1,19 @@ +package service + +import ( + "context" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" +) + +func (d *DMSService) ListCBOperationLogs(ctx context.Context, req *dmsV1.ListCBOperationLogsReq, uid string) (reply *dmsV1.ListCBOperationLogsReply, err error) { + return d.listCBOperationLogs(ctx, req, uid) +} + +func (d *DMSService) GetCBOperationLogTips(ctx context.Context, req *dmsV1.GetCBOperationLogTipsReq, uid string) (reply *dmsV1.GetCBOperationLogTipsReply, err error) { + return d.getCBOperationLogTips(ctx, req, uid) +} + +func (d *DMSService) ExportCBOperationLogs(ctx context.Context, req *dmsV1.ExportCBOperationLogsReq, uid string) ([]byte, error) { + return d.exportCbOperationLogs(ctx, req, uid) +} diff --git a/internal/dms/service/cb_operation_log_ce.go b/internal/dms/service/cb_operation_log_ce.go new file mode 100644 index 000000000..1ed5f8311 --- /dev/null +++ b/internal/dms/service/cb_operation_log_ce.go @@ -0,0 +1,24 @@ +//go:build !enterprise + +package service + +import ( + "context" + "errors" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" +) + +var errNotSupportCBOperationLog = errors.New("cloudbeaver operation log related functions are enterprise version functions") + +func (d *DMSService) listCBOperationLogs(ctx context.Context, req *dmsV1.ListCBOperationLogsReq, uid string) (reply *dmsV1.ListCBOperationLogsReply, err error) { + return nil, errNotSupportCBOperationLog +} + +func (d *DMSService) getCBOperationLogTips(ctx context.Context, req *dmsV1.GetCBOperationLogTipsReq, currentUid string) (*dmsV1.GetCBOperationLogTipsReply, error) { + return nil, errNotSupportCBOperationLog +} + +func (d *DMSService) exportCbOperationLogs(ctx context.Context, req *dmsV1.ExportCBOperationLogsReq, uid string) ([]byte, error) { + return nil, errNotSupportCBOperationLog +} diff --git a/internal/dms/service/cloudbeaver.go b/internal/dms/service/cloudbeaver.go index 8bca433e7..ecd135ba3 100644 --- a/internal/dms/service/cloudbeaver.go +++ b/internal/dms/service/cloudbeaver.go @@ -1,10 +1,8 @@ package service import ( - "context" "fmt" - dmsV1 "github.com/actiontech/dms/api/dms/service/v1" "github.com/actiontech/dms/internal/apiserver/conf" "github.com/actiontech/dms/internal/dms/biz" "github.com/actiontech/dms/internal/dms/storage" @@ -18,23 +16,16 @@ type CloudbeaverService struct { log *utilLog.Helper } -func NewAndInitCloudbeaverService(logger utilLog.Logger, opts *conf.Options) (*CloudbeaverService, error) { - cfg := biz.CloudbeaverCfg{ - EnableHttps: opts.CloudbeaverOpts.EnableHttps, - Host: opts.CloudbeaverOpts.Host, - Port: opts.CloudbeaverOpts.Port, - AdminUser: opts.CloudbeaverOpts.AdminUser, - AdminPassword: opts.CloudbeaverOpts.AdminPassword, - } - +func NewAndInitCloudbeaverService(logger utilLog.Logger, opts *conf.DMSOptions) (*CloudbeaverService, error) { // todo: because cloudbeaver required userUsecase, optimisation may be needed here st, err := storage.NewStorage(logger, &storage.StorageConfig{ - User: opts.DMSServiceOpts.Data.Database.UserName, - Password: opts.DMSServiceOpts.Data.Database.Password, - Host: opts.DMSServiceOpts.Data.Database.Host, - Port: opts.DMSServiceOpts.Data.Database.Port, - Schema: opts.DMSServiceOpts.Data.Database.Database, - Debug: opts.DMSServiceOpts.Data.Database.Debug, + User: opts.ServiceOpts.Database.UserName, + Password: opts.ServiceOpts.Database.Password, + Host: opts.ServiceOpts.Database.Host, + Port: opts.ServiceOpts.Database.Port, + Schema: opts.ServiceOpts.Database.Database, + Debug: opts.ServiceOpts.Database.Debug, + AutoMigrate: opts.ServiceOpts.Database.AutoMigrate, }) if nil != err { return nil, fmt.Errorf("failed to new data: %v", err) @@ -50,11 +41,15 @@ func NewAndInitCloudbeaverService(logger utilLog.Logger, opts *conf.Options) (*C } // 预定义解决usecase循环依赖问题 memberUsecase := &biz.MemberUsecase{} - - namespaceRepo := storage.NewNamespaceRepo(logger, st) - namespaceUsecase := biz.NewNamespaceUsecase(logger, tx, namespaceRepo, memberUsecase, opPermissionVerifyUsecase, pluginUseCase) + environmentTagUsecase := biz.EnvironmentTagUsecase{} + businessTagUsecase := biz.NewBusinessTagUsecase(storage.NewBusinessTagRepo(logger, st), logger) + dmsProxyTargetRepo := storage.NewProxyTargetRepo(logger, st) + projectRepo := storage.NewProjectRepo(logger, st) + projectUsecase := biz.NewProjectUsecase(logger, tx, projectRepo, memberUsecase, opPermissionVerifyUsecase, pluginUseCase, businessTagUsecase, &environmentTagUsecase) dbServiceRepo := storage.NewDBServiceRepo(logger, st) - dbServiceUseCase := biz.NewDBServiceUsecase(dbServiceRepo, pluginUseCase, opPermissionVerifyUsecase, namespaceUsecase) + environmentTagUsecase = *biz.NewEnvironmentTagUsecase(storage.NewEnvironmentTagRepo(logger, st), logger, projectUsecase, opPermissionVerifyUsecase) + discoveryTaskRepo := storage.NewSensitiveDataDiscoveryTaskRepo(logger, st) + dbServiceUseCase := biz.NewDBServiceUsecase(logger, dbServiceRepo, discoveryTaskRepo, pluginUseCase, opPermissionVerifyUsecase, projectUsecase, dmsProxyTargetRepo, &environmentTagUsecase) ldapConfigurationRepo := storage.NewLDAPConfigurationRepo(logger, st) ldapConfigurationUsecase := biz.NewLDAPConfigurationUsecase(logger, tx, ldapConfigurationRepo) @@ -62,10 +57,32 @@ func NewAndInitCloudbeaverService(logger utilLog.Logger, opts *conf.Options) (*C userGroupRepo := storage.NewUserGroupRepo(logger, st) opPermissionRepo := storage.NewOpPermissionRepo(logger, st) opPermissionUsecase := biz.NewOpPermissionUsecase(logger, tx, opPermissionRepo, pluginUseCase) - userUsecase := biz.NewUserUsecase(logger, tx, userRepo, userGroupRepo, pluginUseCase, opPermissionUsecase, opPermissionVerifyUsecase, ldapConfigurationUsecase) - dmsProxyTargetRepo := storage.NewProxyTargetRepo(logger, st) cloudbeaverRepo := storage.NewCloudbeaverRepo(logger, st) - cloudbeaverUsecase := biz.NewCloudbeaverUsecase(logger, cfg, userUsecase, dbServiceUseCase, opPermissionVerifyUsecase, cloudbeaverRepo, dmsProxyTargetRepo) + loginConfigurationRepo := storage.NewLoginConfigurationRepo(logger, st) + loginConfigurationUsecase := biz.NewLoginConfigurationUsecase(logger, tx, loginConfigurationRepo) + userUsecase := biz.NewUserUsecase(logger, tx, userRepo, userGroupRepo, pluginUseCase, opPermissionUsecase, opPermissionVerifyUsecase, loginConfigurationUsecase, ldapConfigurationUsecase, cloudbeaverRepo, nil) + sqlResultMasker, err := newCloudbeaverSQLResultMasker(logger, st, dmsProxyTargetRepo) + if err != nil { + return nil, err + } + dmsConfigRepo := storage.NewDMSConfigRepo(logger, st) + dmsConfigUseCase := biz.NewDMSConfigUseCase(logger, dmsConfigRepo) + cbOperationLogUsecase := biz.NewCbOperationLogUsecase(logger, storage.NewCbOperationLogRepo(logger, st), opPermissionVerifyUsecase, dmsProxyTargetRepo, biz.NewSystemVariableUsecase(logger, storage.NewSystemVariableRepo(logger, st))) + + maintenanceTimeUsecase := biz.NewMaintenanceTimeUsecase(logger, opPermissionVerifyUsecase) + + var cfg *biz.CloudbeaverCfg + if opts.CloudbeaverOpts != nil { + cfg = &biz.CloudbeaverCfg{ + EnableHttps: opts.CloudbeaverOpts.EnableHttps, + Host: opts.CloudbeaverOpts.Host, + Port: opts.CloudbeaverOpts.Port, + AdminUser: opts.CloudbeaverOpts.AdminUser, + AdminPassword: opts.CloudbeaverOpts.AdminPassword, + } + } + + cloudbeaverUsecase := biz.NewCloudbeaverUsecase(logger, cfg, userUsecase, dbServiceUseCase, opPermissionVerifyUsecase, dmsConfigUseCase, sqlResultMasker, cloudbeaverRepo, dmsProxyTargetRepo, cbOperationLogUsecase, projectUsecase, discoveryTaskRepo, maintenanceTimeUsecase) proxyUsecase := biz.NewCloudbeaverProxyUsecase(logger, cloudbeaverUsecase) return &CloudbeaverService{ @@ -75,19 +92,6 @@ func NewAndInitCloudbeaverService(logger utilLog.Logger, opts *conf.Options) (*C }, nil } -func (cs *CloudbeaverService) GetCloudbeaverConfiguration(ctx context.Context) (reply *dmsV1.GetSQLQueryConfigurationReply, err error) { - cs.log.Infof("GetCloudbeaverConfiguration") - defer func() { - cs.log.Infof("GetCloudbeaverConfiguration; reply=%v, error=%v", reply, err) - }() - - return &dmsV1.GetSQLQueryConfigurationReply{ - Payload: struct { - EnableSQLQuery bool `json:"enable_sql_query"` - SQLQueryRootURI string `json:"sql_query_root_uri"` - }{ - EnableSQLQuery: cs.CloudbeaverUsecase.IsCloudbeaverConfigured(), - SQLQueryRootURI: cs.CloudbeaverUsecase.GetRootUri(), - }, - }, nil +func (cs *CloudbeaverService) Logout(session string) { + cs.CloudbeaverUsecase.UnbindCBSession(session) } diff --git a/internal/dms/service/company_notice.go b/internal/dms/service/company_notice.go new file mode 100644 index 000000000..a6ea52e21 --- /dev/null +++ b/internal/dms/service/company_notice.go @@ -0,0 +1,35 @@ +package service + +import ( + "context" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" +) + +func (d *DMSService) GetCompanyNotice(ctx context.Context, currentUserUid string, includeLatestOutsidePeriod bool) (reply *dmsV1.GetCompanyNoticeReply, err error) { + companyNotice, err := d.CompanyNoticeUsecase.GetCompanyNotice(ctx, currentUserUid, includeLatestOutsidePeriod) + if err != nil { + return nil, err + } + data := dmsV1.CompanyNotice{ + ReadByCurrentUser: false, + } + if companyNotice != nil { + data.NoticeStr = companyNotice.NoticeStr + if companyNotice.CreateUserUID != "" { + users := d.UserUsecase.GetBizUserWithNameByUids(ctx, []string{companyNotice.CreateUserUID}) + if len(users) > 0 { + data.CreateUserName = users[0].Name + } + } + data.StartTime = companyNotice.StartTime + data.ExpireTime = companyNotice.EndTime + } + return &dmsV1.GetCompanyNoticeReply{ + Data: data, + }, nil +} + +func (d *DMSService) UpdateCompanyNotice(ctx context.Context, currentUserUID string, req *dmsV1.UpdateCompanyNoticeReq) (err error) { + return d.CompanyNoticeUsecase.UpdateCompanyNotice(ctx, currentUserUID, req.UpdateCompanyNotice.NoticeStr, req.UpdateCompanyNotice.StartTime, req.UpdateCompanyNotice.EndTime) +} diff --git a/internal/dms/service/configuration.go b/internal/dms/service/configuration.go index 3cdaa66a8..6a00b516e 100644 --- a/internal/dms/service/configuration.go +++ b/internal/dms/service/configuration.go @@ -2,51 +2,83 @@ package service import ( "context" + "encoding/json" "fmt" + "strconv" dmsV1 "github.com/actiontech/dms/api/dms/service/v1" "github.com/actiontech/dms/internal/dms/biz" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/pkg/locale" + "golang.org/x/text/language" dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" ) -func (d *DMSService) GetOauth2Configuration(ctx context.Context) (reply *dmsV1.GetOauth2ConfigurationReply, err error) { - d.log.Infof("GetOauth2Configuration") +func (d *DMSService) GetLoginTips(ctx context.Context) (reply *dmsV1.GetLoginTipsReply, err error) { + loginConfiguration, err := d.LoginConfigurationUsecase.GetLoginConfiguration(ctx) + if err != nil { + return nil, err + } + + return &dmsV1.GetLoginTipsReply{ + Data: dmsV1.LoginTipsResData{ + LoginButtonText: loginConfiguration.LoginButtonText, + DisableUserPwdLogin: loginConfiguration.DisableUserPwdLogin, + }, + }, nil +} + +func (d *DMSService) UpdateLoginConfiguration(ctx context.Context, userId string, req *dmsV1.UpdateLoginConfigurationReq) (err error) { + d.log.Infof("UpdateLoginConfiguration") defer func() { - d.log.Infof("GetOauth2Configuration.reply=%v;error=%v", reply, err) + d.log.Infof("UpdateLoginConfiguration;error=%v", err) }() + // 权限校验 + if canGlobalOp, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, userId); err != nil { + return fmt.Errorf("check user op permission failed: %v", err) + } else if !canGlobalOp { + return fmt.Errorf("user is not project admin or golobal op permission user") + } + + loginConfiguration := req.LoginConfiguration + err = d.LoginConfigurationUsecase.UpdateLoginConfiguration(ctx, loginConfiguration.LoginButtonText, loginConfiguration.DisableUserPwdLogin) + return +} + +func (d *DMSService) GetOauth2Configuration(ctx context.Context) (reply *dmsV1.GetOauth2ConfigurationReply, err error) { oauth2C, exist, err := d.Oauth2ConfigurationUsecase.GetOauth2Configuration(ctx) if err != nil { return nil, err } if !exist { return &dmsV1.GetOauth2ConfigurationReply{ - Payload: struct { - Data dmsV1.GetOauth2ConfigurationResData `json:"data"` - }{ - Data: dmsV1.GetOauth2ConfigurationResData{}, - }, + Data: dmsV1.GetOauth2ConfigurationResData{}, }, nil } return &dmsV1.GetOauth2ConfigurationReply{ - Payload: struct { - Data dmsV1.GetOauth2ConfigurationResData `json:"data"` - }{ - Data: dmsV1.GetOauth2ConfigurationResData{ - EnableOauth2: oauth2C.EnableOauth2, - ClientID: oauth2C.ClientID, - ClientHost: oauth2C.ClientHost, - ServerAuthUrl: oauth2C.ServerAuthUrl, - ServerTokenUrl: oauth2C.ServerTokenUrl, - ServerUserIdUrl: oauth2C.ServerUserIdUrl, - Scopes: oauth2C.Scopes, - AccessTokenTag: oauth2C.AccessTokenTag, - UserIdTag: oauth2C.UserIdTag, - LoginTip: oauth2C.LoginTip, - }, + Data: dmsV1.GetOauth2ConfigurationResData{ + EnableOauth2: oauth2C.EnableOauth2, + SkipCheckState: oauth2C.SkipCheckState, + EnableManuallyBind: oauth2C.EnableManuallyBind, + AutoBindSameNameUser: oauth2C.AutoBindSameNameUser, + AutoCreateUser: oauth2C.AutoCreateUser, + ClientID: oauth2C.ClientID, + ClientHost: oauth2C.ClientHost, + ServerAuthUrl: oauth2C.ServerAuthUrl, + ServerTokenUrl: oauth2C.ServerTokenUrl, + ServerUserIdUrl: oauth2C.ServerUserIdUrl, + ServerLogoutUrl: oauth2C.ServerLogoutUrl, + Scopes: oauth2C.Scopes, + AccessTokenTag: oauth2C.AccessTokenTag, + UserIdTag: oauth2C.UserIdTag, + LoginTip: oauth2C.LoginTip, + UserEmailTag: oauth2C.UserEmailTag, + UserWeChatTag: oauth2C.UserWeChatTag, + LoginPermExpr: oauth2C.LoginPermExpr, + BackChannelLogoutUri: dmsCommonV1.GroupV1 + "/dms/oauth2" + biz.BackChannelLogoutUri, }, }, nil } @@ -63,25 +95,18 @@ func (d *DMSService) GetOauth2ConfigurationTip(ctx context.Context) (reply *dmsV } if !exist { return &dmsV1.GetOauth2TipsReply{ - Payload: struct { - Data dmsV1.GetOauth2TipsResData `json:"data"` - }{ - Data: dmsV1.GetOauth2TipsResData{}, - }, + Data: dmsV1.GetOauth2TipsResData{}, }, nil } return &dmsV1.GetOauth2TipsReply{ - Payload: struct { - Data dmsV1.GetOauth2TipsResData `json:"data"` - }{ - Data: dmsV1.GetOauth2TipsResData{ - EnableOauth2: oauth2C.EnableOauth2, - LoginTip: oauth2C.LoginTip, - }, + Data: dmsV1.GetOauth2TipsResData{ + EnableOauth2: oauth2C.EnableOauth2, + LoginTip: oauth2C.LoginTip, }, }, nil } + func (d *DMSService) UpdateOauth2Configuration(ctx context.Context, req *dmsV1.Oauth2ConfigurationReq) (err error) { d.log.Infof("UpdateOauth2Configuration") defer func() { @@ -89,55 +114,60 @@ func (d *DMSService) UpdateOauth2Configuration(ctx context.Context, req *dmsV1.O }() oauth2Configuration := req.Oauth2Configuration - return d.Oauth2ConfigurationUsecase.UpdateOauth2Configuration(ctx, oauth2Configuration.EnableOauth2, - oauth2Configuration.ClientID, oauth2Configuration.ClientKey, oauth2Configuration.ClientHost, - oauth2Configuration.ServerAuthUrl, oauth2Configuration.ServerTokenUrl, oauth2Configuration.ServerUserIdUrl, - oauth2Configuration.AccessTokenTag, oauth2Configuration.UserIdTag, oauth2Configuration.LoginTip, oauth2Configuration.Scopes) + return d.Oauth2ConfigurationUsecase.UpdateOauth2Configuration(ctx, oauth2Configuration) } -func (d *DMSService) Oauth2Link(ctx context.Context) (uri string, err error) { - d.log.Infof("Oauth2Link") +func (d *DMSService) Oauth2Link(ctx context.Context, target string) (uri string, err error) { + d.log.Infof("Oauth2Link path: %v", target) defer func() { d.log.Infof("Oauth2Link;error=%v", err) }() - uri, err = d.Oauth2ConfigurationUsecase.GenOauth2LinkURI(ctx) + uri, err = d.Oauth2ConfigurationUsecase.GenOauth2LinkURI(ctx, target) if err != nil { return "", err } return uri, nil } -func (d *DMSService) Oauth2Callback(ctx context.Context, req *dmsV1.Oauth2CallbackReq) (uri string, err error) { +// if redirect directly to SQLE, will return token, otherwise this parameter will be an empty string +func (d *DMSService) Oauth2Callback(ctx context.Context, req *dmsV1.Oauth2CallbackReq) (data *biz.CallbackRedirectData, claims *biz.ClaimsInfo, err error) { d.log.Infof("Oauth2Callback") defer func() { d.log.Infof("Oauth2Callback;error=%v", err) }() - uri, err = d.Oauth2ConfigurationUsecase.GenerateCallbackUri(ctx, req.State, req.Code) - if err != nil { - return "", err - } - return uri, nil + return d.Oauth2ConfigurationUsecase.GenerateCallbackUri(ctx, req.State, req.Code) } -func (d *DMSService) BindOauth2User(ctx context.Context, bindOauth2User *dmsV1.BindOauth2UserReq) (reply *dmsV1.BindOauth2UserReply, err error) { +func (d *DMSService) BindOauth2User(ctx context.Context, bindOauth2User *dmsV1.BindOauth2UserReq) (claims *biz.ClaimsInfo, err error) { d.log.Infof("BindOauth2User") defer func() { d.log.Infof("BindOauth2User;error=%v", err) }() - token, err := d.Oauth2ConfigurationUsecase.BindOauth2User(ctx, bindOauth2User.Oauth2Token, bindOauth2User.UserName, bindOauth2User.Pwd) + return d.Oauth2ConfigurationUsecase.BindOauth2User(ctx, bindOauth2User.Oauth2Token, bindOauth2User.RefreshToken, bindOauth2User.UserName, bindOauth2User.Pwd) +} + +func (d *DMSService) RefreshOauth2Token(ctx context.Context, userUid, sub, sid string) (claims *biz.ClaimsInfo, err error) { + d.log.Infof("RefreshOauth2Token") + defer func() { + d.log.Infof("RefreshOauth2Token;error=%v", err) + }() + + return d.Oauth2ConfigurationUsecase.RefreshOauth2Token(ctx, userUid, sub, sid) +} + +func (d *DMSService) BackChannelLogout(ctx context.Context, logoutToken string) error { + d.log.Infof("BackChannelLogout") + + err := d.Oauth2ConfigurationUsecase.BackChannelLogout(ctx, logoutToken) if err != nil { - return nil, err + d.log.Errorf("BackChannelLogout logout token:%s err:%v", logoutToken, err) + return err } - return &dmsV1.BindOauth2UserReply{ - Payload: struct { - Data dmsV1.BindOauth2UserResData `json:"data"` - }{ - Data: dmsV1.BindOauth2UserResData{Token: token}, - }, - }, nil + + return nil } func (d *DMSService) GetLDAPConfiguration(ctx context.Context) (reply *dmsV1.GetLDAPConfigurationReply, err error) { @@ -152,28 +182,20 @@ func (d *DMSService) GetLDAPConfiguration(ctx context.Context) (reply *dmsV1.Get } if !exist { return &dmsV1.GetLDAPConfigurationReply{ - Payload: struct { - Data dmsV1.LDAPConfigurationResData `json:"data"` - }{ - Data: dmsV1.LDAPConfigurationResData{}, - }, + Data: dmsV1.LDAPConfigurationResData{}, }, nil } return &dmsV1.GetLDAPConfigurationReply{ - Payload: struct { - Data dmsV1.LDAPConfigurationResData `json:"data"` - }{ - Data: dmsV1.LDAPConfigurationResData{ - EnableLdap: ldapConfiguration.Enable, - EnableSSL: ldapConfiguration.EnableSSL, - LdapServerHost: ldapConfiguration.Host, - LdapServerPort: ldapConfiguration.Port, - LdapConnectDn: ldapConfiguration.ConnectDn, - LdapSearchBaseDn: ldapConfiguration.BaseDn, - LdapUserNameRdnKey: ldapConfiguration.UserNameRdnKey, - LdapUserEmailRdnKey: ldapConfiguration.UserEmailRdnKey, - }, + Data: dmsV1.LDAPConfigurationResData{ + EnableLdap: ldapConfiguration.Enable, + EnableSSL: ldapConfiguration.EnableSSL, + LdapServerHost: ldapConfiguration.Host, + LdapServerPort: ldapConfiguration.Port, + LdapConnectDn: ldapConfiguration.ConnectDn, + LdapSearchBaseDn: ldapConfiguration.BaseDn, + LdapUserNameRdnKey: ldapConfiguration.UserNameRdnKey, + LdapUserEmailRdnKey: ldapConfiguration.UserEmailRdnKey, }, }, nil } @@ -203,25 +225,17 @@ func (d *DMSService) GetSMTPConfiguration(ctx context.Context) (reply *dmsV1.Get } if !exist { return &dmsV1.GetSMTPConfigurationReply{ - Payload: struct { - Data dmsV1.SMTPConfigurationResData `json:"data"` - }{ - Data: dmsV1.SMTPConfigurationResData{}, - }, + Data: dmsV1.SMTPConfigurationResData{}, }, nil } return &dmsV1.GetSMTPConfigurationReply{ - Payload: struct { - Data dmsV1.SMTPConfigurationResData `json:"data"` - }{ - Data: dmsV1.SMTPConfigurationResData{ - EnableSMTPNotify: smtpConfiguration.EnableSMTPNotify, - Host: smtpConfiguration.Host, - Port: smtpConfiguration.Port, - Username: smtpConfiguration.Username, - IsSkipVerify: smtpConfiguration.IsSkipVerify, - }, + Data: dmsV1.SMTPConfigurationResData{ + EnableSMTPNotify: smtpConfiguration.EnableSMTPNotify, + Host: smtpConfiguration.Host, + Port: smtpConfiguration.Port, + Username: smtpConfiguration.Username, + IsSkipVerify: smtpConfiguration.IsSkipVerify, }, }, nil } @@ -252,13 +266,9 @@ func (d *DMSService) TestSMTPConfiguration(ctx context.Context, req *dmsV1.TestS } return &dmsV1.TestSMTPConfigurationReply{ - Payload: struct { - Data dmsV1.TestSMTPConfigurationResData `json:"data"` - }{ - Data: dmsV1.TestSMTPConfigurationResData{ - IsSMTPSendNormal: isSMTPSendNormal, - SendErrorMessage: sendErrorMessage, - }, + Data: dmsV1.TestSMTPConfigurationResData{ + IsSMTPSendNormal: isSMTPSendNormal, + SendErrorMessage: sendErrorMessage, }, }, nil } @@ -275,25 +285,17 @@ func (d *DMSService) GetWeChatConfiguration(ctx context.Context) (reply *dmsV1.G } if !exist { return &dmsV1.GetWeChatConfigurationReply{ - Payload: struct { - Data dmsV1.WeChatConfigurationResData `json:"data"` - }{ - Data: dmsV1.WeChatConfigurationResData{}, - }, + Data: dmsV1.WeChatConfigurationResData{}, }, nil } return &dmsV1.GetWeChatConfigurationReply{ - Payload: struct { - Data dmsV1.WeChatConfigurationResData `json:"data"` - }{ - Data: dmsV1.WeChatConfigurationResData{ - EnableWeChatNotify: wechatConfiguration.EnableWeChatNotify, - CorpID: wechatConfiguration.CorpID, - AgentID: wechatConfiguration.AgentID, - SafeEnabled: wechatConfiguration.SafeEnabled, - ProxyIP: wechatConfiguration.ProxyIP, - }, + Data: dmsV1.WeChatConfigurationResData{ + EnableWeChatNotify: wechatConfiguration.EnableWeChatNotify, + CorpID: wechatConfiguration.CorpID, + AgentID: wechatConfiguration.AgentID, + SafeEnabled: wechatConfiguration.SafeEnabled, + ProxyIP: wechatConfiguration.ProxyIP, }, }, nil } @@ -323,13 +325,9 @@ func (d *DMSService) TestWeChatConfiguration(ctx context.Context, req *dmsV1.Tes } return &dmsV1.TestWeChatConfigurationReply{ - Payload: struct { - Data dmsV1.TestWeChatConfigurationResData `json:"data"` - }{ - Data: dmsV1.TestWeChatConfigurationResData{ - IsWeChatSendNormal: isWeChatSendNormal, - SendErrorMessage: sendErrorMessage, - }, + Data: dmsV1.TestWeChatConfigurationResData{ + IsWeChatSendNormal: isWeChatSendNormal, + SendErrorMessage: sendErrorMessage, }, }, nil } @@ -346,22 +344,13 @@ func (d *DMSService) GetFeishuConfiguration(ctx context.Context) (reply *dmsV1.G } if !exist { return &dmsV1.GetFeishuConfigurationReply{ - Payload: struct { - Data dmsV1.FeishuConfigurationResData `json:"data"` - }{ - Data: dmsV1.FeishuConfigurationResData{}, - }, + Data: dmsV1.FeishuConfigurationResData{}, }, nil } - return &dmsV1.GetFeishuConfigurationReply{ - Payload: struct { - Data dmsV1.FeishuConfigurationResData `json:"data"` - }{ - Data: dmsV1.FeishuConfigurationResData{ - AppID: feishuConfiguration.AppKey, - IsFeishuNotificationEnabled: feishuConfiguration.IsEnable, - }, + Data: dmsV1.FeishuConfigurationResData{ + AppID: feishuConfiguration.AppKey, + IsFeishuNotificationEnabled: feishuConfiguration.IsEnable, }, }, nil } @@ -407,48 +396,31 @@ func (d *DMSService) TestFeishuConfiguration(ctx context.Context, req *dmsV1.Tes } return &dmsV1.TestFeishuConfigurationReply{ - Payload: struct { - Data dmsV1.TestFeishuConfigurationResData `json:"data"` - }{ - Data: dmsV1.TestFeishuConfigurationResData{ - IsMessageSentNormally: isFeishuSendNormal, - ErrorMessage: sendErrorMessage, - }, + Data: dmsV1.TestFeishuConfigurationResData{ + IsMessageSentNormally: isFeishuSendNormal, + ErrorMessage: sendErrorMessage, }, }, nil } func (d *DMSService) GetWebHookConfiguration(ctx context.Context) (reply *dmsV1.GetWebHookConfigurationReply, err error) { - d.log.Infof("GetWebHookConfiguration") - defer func() { - d.log.Infof("GetWebHookConfiguration.reply=%v;error=%v", reply, err) - }() - webhookConfiguration, exist, err := d.WebHookConfigurationUsecase.GetWebHookConfiguration(ctx) if err != nil { return nil, err } if !exist { return &dmsV1.GetWebHookConfigurationReply{ - Payload: struct { - Data dmsV1.WebHookConfigurationData `json:"data"` - }{ - Data: dmsV1.WebHookConfigurationData{}, - }, + Data: dmsV1.GetWebHookConfigurationReplyItem{}, }, nil } return &dmsV1.GetWebHookConfigurationReply{ - Payload: struct { - Data dmsV1.WebHookConfigurationData `json:"data"` - }{ - Data: dmsV1.WebHookConfigurationData{ - Enable: &webhookConfiguration.Enable, - MaxRetryTimes: &webhookConfiguration.MaxRetryTimes, - RetryIntervalSeconds: &webhookConfiguration.RetryIntervalSeconds, - Token: &webhookConfiguration.Token, - URL: &webhookConfiguration.URL, - }, + Data: dmsV1.GetWebHookConfigurationReplyItem{ + Enable: webhookConfiguration.Enable, + MaxRetryTimes: webhookConfiguration.MaxRetryTimes, + RetryIntervalSeconds: webhookConfiguration.RetryIntervalSeconds, + Token: webhookConfiguration.Token, + URL: webhookConfiguration.URL, }, }, nil } @@ -478,17 +450,78 @@ func (d *DMSService) TestWebHookConfiguration(ctx context.Context) (reply *dmsV1 } return &dmsV1.TestWebHookConfigurationReply{ - Payload: struct { - Data dmsV1.TestWebHookConfigurationResData `json:"data"` - }{ - Data: dmsV1.TestWebHookConfigurationResData{ - IsMessageSentNormally: isWebHookSendNormal, - SendErrorMessage: sendErrorMessage, - }, + Data: dmsV1.TestWebHookConfigurationResData{ + IsMessageSentNormally: isWebHookSendNormal, + SendErrorMessage: sendErrorMessage, + }, + }, nil +} + +func (d *DMSService) UpdateSmsConfiguration(ctx context.Context, req *dmsV1.UpdateSmsConfigurationReq) (err error) { + d.log.Infof("UpdateSmsConfiguration") + defer func() { + d.log.Infof("UpdateSmsConfiguration;error=%v", err) + }() + return d.SmsConfigurationUseCase.UpdateSmsConfiguration(ctx, req.UpdateSmsConfiguration.EnableSms, req.UpdateSmsConfiguration.Url, req.UpdateSmsConfiguration.SmsType, req.UpdateSmsConfiguration.Configuration) +} + +func (d *DMSService) TestSmsConfiguration(ctx context.Context, req *dmsV1.TestSmsConfigurationReq) (reply *dmsV1.TestSmsConfigurationReply, err error) { + d.log.Infof("TestSmsConfiguration") + defer func() { + d.log.Infof("TestSmsConfiguration;error=%v", err) + }() + isSmsSendNormal, sendErrorMessage := true, "ok" + err = d.SmsConfigurationUseCase.TestSmsConfiguration(ctx, req.TestSmsConfiguration.RecipientPhone) + if err != nil { + isSmsSendNormal = false + sendErrorMessage = err.Error() + } + return &dmsV1.TestSmsConfigurationReply{ + Data: dmsV1.TestSmsConfigurationResData{ + IsSmsSendNormal: isSmsSendNormal, + SendErrorMessage: sendErrorMessage, }, }, nil } +func (d *DMSService) GetSmsConfiguration(ctx context.Context) (reply *dmsV1.GetSmsConfigurationReply, err error) { + smsConfiguration, exist, err := d.SmsConfigurationUseCase.GetSmsConfiguration(ctx) + if err != nil { + return nil, err + } + if !exist { + return &dmsV1.GetSmsConfigurationReply{ + Data: dmsV1.GetSmsConfigurationReplyItem{}, + }, nil + } + configuration := map[string]string{} + err = json.Unmarshal([]byte(smsConfiguration.Configuration), &configuration) + return &dmsV1.GetSmsConfigurationReply{ + Data: dmsV1.GetSmsConfigurationReplyItem{ + Enable: smsConfiguration.Enable, + Url: smsConfiguration.Url, + Configuration: configuration, + SmsType: smsConfiguration.Type, + }, + }, nil +} + +func (d *DMSService) SendSmsCode(ctx context.Context, username string) (reply *dmsV1.SendSmsCodeReply, err error) { + d.log.Infof("send sms code") + defer func() { + d.log.Infof("send sms code;error=%v", err) + }() + return d.SmsConfigurationUseCase.SendSmsCode(ctx, username) +} + +func (d *DMSService) VerifySmsCode(request *dmsV1.VerifySmsCodeReq) (reply *dmsV1.VerifySmsCodeReply) { + d.log.Infof("verify sms code") + defer func() { + d.log.Infof("verify sms code %v", reply) + }() + return d.SmsConfigurationUseCase.VerifySmsCode(request.Code, request.Username) +} + func (d *DMSService) NotifyMessage(ctx context.Context, req *dmsCommonV1.NotificationReq) (err error) { d.log.Infof("notifyMessage") defer func() { @@ -496,21 +529,32 @@ func (d *DMSService) NotifyMessage(ctx context.Context, req *dmsCommonV1.Notific }() users, _, err := d.UserUsecase.ListUser(ctx, &biz.ListUsersOption{ - FilterBy: []pkgConst.FilterCondition{ - { - Field: string(biz.UserFieldUID), - Operator: pkgConst.FilterOperatorIn, - Value: req.Notification.UserUids, - }, - }, - OrderBy: biz.UserFieldName, + FilterByOptions: pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd, + pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(biz.UserFieldUID), + Operator: pkgConst.FilterOperatorIn, + Value: req.Notification.UserUids, + }, + ), + ), + OrderBy: biz.UserFieldName, PageNumber: 1, LimitPerPage: uint32(len(req.Notification.UserUids)), }) + + lang2Users := make(map[language.Tag][]*biz.User, len(locale.Bundle.LanguageTags())) + for _, user := range users { + langTag := locale.Bundle.MatchLangTag(user.Language) + lang2Users[langTag] = append(lang2Users[langTag], user) + } + for _, n := range biz.Notifiers { - err = n.Notify(ctx, req.Notification.NotificationSubject, req.Notification.NotificationBody, users) - if err != nil { - return err + for langTag, u := range lang2Users { + err = n.Notify(ctx, req.Notification.NotificationSubject.GetStrInLang(langTag), req.Notification.NotificationBody.GetStrInLang(langTag), u) + if err != nil { + return err + } } } return nil @@ -524,3 +568,116 @@ func (d *DMSService) WebHookSendMessage(ctx context.Context, req *dmsCommonV1.We return d.WebHookConfigurationUsecase.SendWebHookMessage(ctx, string(req.WebHookMessage.TriggerEventType), req.WebHookMessage.Message) } + +// GetSystemVariables 获取系统变量 +func (d *DMSService) GetSystemVariables(ctx context.Context, currentUserUid string) (reply *dmsCommonV1.GetSystemVariablesReply, err error) { + d.log.Infof("GetSystemVariables") + defer func() { + d.log.Infof("GetSystemVariables.reply=%v;error=%v", reply, err) + }() + + canViewGlobal, err := d.OpPermissionVerifyUsecase.CanViewGlobal(ctx, currentUserUid) + if err != nil { + return nil, fmt.Errorf("failed to check user can view global") + } + if !canViewGlobal { + return nil, fmt.Errorf("user can not get system variables") + } + + variables, err := d.SystemVariableUsecase.GetSystemVariables(ctx) + if err != nil { + return nil, err + } + + operationRecordExpiredHours, err := strconv.Atoi(variables[biz.SystemVariableOperationRecordExpiredHours].Value) + if err != nil { + return nil, err + } + + cbOperationLogsExpiredHours, err := strconv.Atoi(variables[biz.SystemVariableCbOperationLogsExpiredHours].Value) + if err != nil { + return nil, err + } + + systemVariableWorkflowExpiredHours, err := strconv.Atoi(variables[biz.SystemVariableWorkflowExpiredHours].Value) + if err != nil { + return nil, err + } + + return &dmsCommonV1.GetSystemVariablesReply{ + Data: dmsCommonV1.SystemVariablesResV1{ + Url: variables[biz.SystemVariableSqleUrl].Value, + OperationRecordExpiredHours: operationRecordExpiredHours, + CbOperationLogsExpiredHours: cbOperationLogsExpiredHours, + SystemVariableSSHPrimaryKey: variables[biz.SystemVariableSSHPrimaryKey].Value, + SystemVariableWorkflowExpiredHours: systemVariableWorkflowExpiredHours, + }, + }, nil +} + +// UpdateSystemVariables 更新系统变量 +func (d *DMSService) UpdateSystemVariables(ctx context.Context, req *dmsCommonV1.UpdateSystemVariablesReqV1, currentUserUid string) (err error) { + d.log.Infof("UpdateSystemVariables.req=%v", req) + defer func() { + d.log.Infof("UpdateSystemVariables.req=%v;error=%v", req, err) + }() + + canOpGlobal, err := d.OpPermissionVerifyUsecase.CanOpGlobal(ctx, currentUserUid) + if err != nil { + return fmt.Errorf("failed to check user can op global") + } + if !canOpGlobal { + return fmt.Errorf("user can not update system variables") + } + + // 构建要更新的系统变量列表 + var variables []*biz.SystemVariable + + if req.Url != nil { + variables = append(variables, &biz.SystemVariable{ + Key: biz.SystemVariableSqleUrl, + Value: *req.Url, + }) + } + + if req.OperationRecordExpiredHours != nil { + variables = append(variables, &biz.SystemVariable{ + Key: biz.SystemVariableOperationRecordExpiredHours, + Value: fmt.Sprintf("%d", *req.OperationRecordExpiredHours), + }) + } + + if req.CbOperationLogsExpiredHours != nil { + variables = append(variables, &biz.SystemVariable{ + Key: biz.SystemVariableCbOperationLogsExpiredHours, + Value: fmt.Sprintf("%d", *req.CbOperationLogsExpiredHours), + }) + } + + if req.SystemVariableSSHPrimaryKey != nil { + variables = append(variables, &biz.SystemVariable{ + Key: biz.SystemVariableSSHPrimaryKey, + Value: *req.SystemVariableSSHPrimaryKey, + }) + } + + if req.SystemVariableWorkflowExpiredHours != nil { + variables = append(variables, &biz.SystemVariable{ + Key: biz.SystemVariableWorkflowExpiredHours, + Value: fmt.Sprintf("%d", *req.SystemVariableWorkflowExpiredHours), + }) + } + + if req.SystemVariableSqlManageRawExpiredHours != nil { + variables = append(variables, &biz.SystemVariable{ + Key: biz.SystemVariableSqlManageRawExpiredHours, + Value: fmt.Sprintf("%d", *req.SystemVariableSqlManageRawExpiredHours), + }) + } + + if len(variables) == 0 { + return nil // 没有需要更新的变量 + } + + return d.SystemVariableUsecase.UpdateSystemVariables(ctx, variables) +} diff --git a/internal/dms/service/data_export_workflow.go b/internal/dms/service/data_export_workflow.go new file mode 100644 index 000000000..78dfba7f0 --- /dev/null +++ b/internal/dms/service/data_export_workflow.go @@ -0,0 +1,377 @@ +package service + +import ( + "context" + "fmt" + "strings" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/pkg/locale" +) + +func (d *DMSService) AddDataExportWorkflow(ctx context.Context, req *dmsV1.AddDataExportWorkflowReq, currentUserUid string) (reply *dmsV1.AddDataExportWorkflowReply, err error) { + // generate biz args + tasks := make([]biz.Task, 0) + for _, t := range req.DataExportWorkflow.Tasks { + tasks = append(tasks, biz.Task{UID: t.Uid}) + } + args := &biz.Workflow{ + Name: req.DataExportWorkflow.Name, + Desc: req.DataExportWorkflow.Desc, + Tasks: tasks, + ProjectUID: req.ProjectUid, + } + uid, err := d.DataExportWorkflowUsecase.AddDataExportWorkflow(ctx, currentUserUid, args) + if err != nil { + return nil, fmt.Errorf("add data export workflow failed: %w", err) + } + + return &dmsV1.AddDataExportWorkflowReply{ + Data: struct { + Uid string `json:"export_data_workflow_uid"` + }{Uid: uid}}, nil +} + +func (d *DMSService) ListDataExportWorkflow(ctx context.Context, req *dmsV1.ListDataExportWorkflowsReq, currentUserUid string) (reply *dmsV1.ListDataExportWorkflowsReply, err error) { + // default order by + orderBy := biz.WorkflowFieldCreateTime + + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.WorkflowFieldWorkflowType), + Operator: pkgConst.FilterOperatorEqual, + Value: biz.DataExportWorkflowEventType.String(), + }) + + if req.FilterByCreateUserUid != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.WorkflowFieldCreateUserUID), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterByCreateUserUid, + }) + } + + if req.FilterCreateTimeFrom != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.WorkflowFieldCreateTime), + Operator: pkgConst.FilterOperatorGreaterThanOrEqual, + Value: req.FilterCreateTimeFrom, + }) + } + + if req.FilterCreateTimeTo != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.WorkflowFieldCreateTime), + Operator: pkgConst.FilterOperatorLessThanOrEqual, + Value: req.FilterCreateTimeTo, + }) + } + + if req.ProjectUid != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.WorkflowFieldProjectUID), + Operator: pkgConst.FilterOperatorEqual, + Value: req.ProjectUid, + }) + } + + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + + if req.FuzzyKeyword != "" { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicOr, + pkgConst.FilterCondition{ + Field: string(biz.WorkflowFieldName), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + pkgConst.FilterCondition{ + Field: string(biz.WorkflowFieldUID), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + )) + } + + listOption := &biz.ListWorkflowsOption{ + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, + } + + workflows, total, err := d.DataExportWorkflowUsecase.ListDataExportWorkflows(ctx, listOption, currentUserUid, req.FilterByDBServiceUid, req.FilterCurrentStepAssigneeUserUid, string(req.FilterByStatus), req.ProjectUid) + if nil != err { + return nil, err + } + + // 收集所有唯一的项目UID + projectUIDs := make(map[string]bool) + for _, w := range workflows { + if w.ProjectUID != "" { + projectUIDs[w.ProjectUID] = true + } + } + + // 批量获取项目信息 + projectMap := make(map[string]string) + for projectUID := range projectUIDs { + project, err := d.ProjectUsecase.GetProject(ctx, projectUID) + if err != nil { + // 如果获取项目失败,记录错误但继续处理 + projectMap[projectUID] = "Unknown Project" + } else { + projectMap[projectUID] = project.Name + } + } + + ret := make([]*dmsV1.ListDataExportWorkflow, len(workflows)) + for i, w := range workflows { + ret[i] = &dmsV1.ListDataExportWorkflow{ + ProjectUid: w.ProjectUID, + ProjectName: projectMap[w.ProjectUID], + WorkflowID: w.UID, + WorkflowName: w.Name, + Description: w.Desc, + CreatedAt: w.CreatedAt, + Status: dmsV1.DataExportWorkflowStatus(w.WorkflowRecord.Status), + } + creater := convertBizUidWithName(d.UserUsecase.GetBizUserWithNameByUids(ctx, []string{w.CreateUserUID})) + if len(creater) > 0 { + ret[i].Creater = creater[0] + } + if w.WorkflowRecord.WorkflowSteps[w.WorkflowRecord.CurrentWorkflowStepId-1].State == "init" { + ret[i].CurrentStepAssigneeUsers = convertBizUidWithName(d.UserUsecase.GetBizUserIncludeDeletedWithNameByUids(ctx, w.WorkflowRecord.WorkflowSteps[w.WorkflowRecord.CurrentWorkflowStepId-1].Assignees)) + } + + } + + return &dmsV1.ListDataExportWorkflowsReply{ + Data: ret, + Total: total, + }, nil +} + +func (d *DMSService) GetGlobalWorkflowsList(ctx context.Context, req *dmsV1.FilterGlobalDataExportWorkflowReq) ( + *dmsV1.GetGlobalDataExportWorkflowsReply, error) { + + limit, offset := d.GetLimitAndOffset(req.PageIndex, req.PageSize) + workflows, total, err := d.DataExportWorkflowUsecase.GetGlobalWorkflowsList(ctx, req, limit, offset) + if err != nil { + return nil, err + } + + // 收集所有唯一的项目UID + projectUIDs := make(map[string]bool) + for _, w := range workflows { + if w.ProjectUID != "" { + projectUIDs[w.ProjectUID] = true + } + } + + ret := make([]*dmsV1.GlobalDataExportWorkflow, len(workflows)) + for i, w := range workflows { + ret[i] = &dmsV1.GlobalDataExportWorkflow{ + ProjectInfo: w.ProjectInfo, + WorkflowID: w.UID, + WorkflowName: w.Name, + Description: w.Desc, + CreatedAt: w.CreatedAt, + Status: dmsV1.DataExportWorkflowStatus(w.WorkflowRecord.Status), + DBServiceInfos: w.DBServiceInfos, + } + + creater := convertBizUidWithName(d.UserUsecase.GetBizUserIncludeDeletedWithNameByUids(ctx, []string{w.CreateUserUID})) + if len(creater) > 0 { + ret[i].Creater = creater[0] + } + if w.WorkflowRecord.WorkflowSteps[w.WorkflowRecord.CurrentWorkflowStepId-1].State == "init" { + ret[i].CurrentStepAssigneeUsers = convertBizUidWithName(d.UserUsecase.GetBizUserIncludeDeletedWithNameByUids(ctx, w.WorkflowRecord.WorkflowSteps[w.WorkflowRecord.CurrentWorkflowStepId-1].Assignees)) + } + } + + return &dmsV1.GetGlobalDataExportWorkflowsReply{ + Data: ret, + Total: total, + }, nil +} + +func (d *DMSService) GetDataExportWorkflow(ctx context.Context, req *dmsV1.GetDataExportWorkflowReq, currentUserUid string) (reply *dmsV1.GetDataExportWorkflowReply, err error) { + w, err := d.DataExportWorkflowUsecase.GetDataExportWorkflow(ctx, req.DataExportWorkflowUid, currentUserUid) + if err != nil { + return nil, fmt.Errorf("get data export workflow error: %v", err) + } + + data := &dmsV1.GetDataExportWorkflow{ + Name: w.Name, + WorkflowID: w.UID, + Desc: w.Desc, + CreateUser: convertBizUidWithName(d.UserUsecase.GetBizUserWithNameByUids(ctx, []string{w.CreateUserUID}))[0], + CreateTime: &w.CreateTime, + WorkflowRecord: dmsV1.WorkflowRecord{ + CurrentStepNumber: uint(w.WorkflowRecord.CurrentWorkflowStepId), + Status: dmsV1.DataExportWorkflowStatus(w.WorkflowRecord.Status), + }, + } + + for _, task := range w.WorkflowRecord.Tasks { + data.WorkflowRecord.Tasks = append(data.WorkflowRecord.Tasks, &dmsV1.Task{ + Uid: task.UID, + }) + } + for _, v := range w.WorkflowRecord.WorkflowSteps { + step := &dmsV1.WorkflowStep{ + Number: v.StepId, + Users: convertBizUidWithName(d.UserUsecase.GetBizUserWithNameByUids(ctx, v.Assignees)), + OperationTime: v.OperateAt, + State: dmsV1.WorkflowStepStatus(v.State), + Reason: v.Reason, + } + if v.OperationUserUid != "" && v.State != "init" { + step.OperationUser = convertBizUidWithName(d.UserUsecase.GetBizUserWithNameByUids(ctx, []string{v.OperationUserUid}))[0] + } + data.WorkflowRecord.Steps = append(data.WorkflowRecord.Steps, step) + } + + return &dmsV1.GetDataExportWorkflowReply{ + Data: data, + }, nil +} + +func (d *DMSService) ExportDataExportWorkflow(ctx context.Context, req *dmsV1.ExportDataExportWorkflowReq, currentUserUid string) error { + return d.DataExportWorkflowUsecase.ExportDataExportWorkflow(ctx, req.ProjectUid, req.DataExportWorkflowUid, currentUserUid) + +} +func (d *DMSService) AddDataExportTask(ctx context.Context, req *dmsV1.AddDataExportTaskReq, currentUserUid string) (reply *dmsV1.AddDataExportTaskReply, err error) { + // generate biz arg + args := make([]*biz.DataExportTask, 0) + for _, task := range req.DataExportTasks { + args = append(args, &biz.DataExportTask{ + DBServiceUid: task.DBServiceUid, + CreateUserUID: currentUserUid, + DatabaseName: task.DatabaseName, + ExportType: "SQL", + ExportFileType: "CSV", + ExportSQL: task.ExportSQL, + ExportStatus: biz.DataExportTaskStatusInit, + }) + } + + uids, err := d.DataExportWorkflowUsecase.AddDataExportTasks(ctx, req.ProjectUid, currentUserUid, args) + if err != nil { + return nil, fmt.Errorf("add data export task failed: %v", err) + } + + return &dmsV1.AddDataExportTaskReply{ + Data: struct { + Uids []string `json:"data_export_task_uids"` + }{ + Uids: uids, + }, + }, nil +} + +func (d *DMSService) BatchGetDataExportTask(ctx context.Context, req *dmsV1.BatchGetDataExportTaskReq) (reply *dmsV1.BatchGetDataExportTaskReply, err error) { + taskUids := strings.Split(req.TaskUids, ",") + tasks, err := d.DataExportWorkflowUsecase.BatchGetDataExportTask(ctx, taskUids) + if err != nil { + return nil, fmt.Errorf("get data export workflow error: %v", err) + } + data := make([]*dmsV1.GetDataExportTask, 0) + for _, task := range tasks { + data = append(data, &dmsV1.GetDataExportTask{ + TaskUid: task.UID, + DBInfo: dmsV1.TaskDBInfo{UidWithName: convertBizUidWithName(d.DBServiceUsecase.GetBizDBWithNameByUids(ctx, []string{task.DBServiceUid}))[0], DBType: "", DatabaseName: task.DatabaseName}, + Status: dmsV1.DataExportTaskStatus(task.ExportStatus), + ExportStartTime: task.ExportStartTime, + ExportEndTime: task.ExportEndTime, + FileName: task.ExportFileName, + ExportType: task.ExportType, + ExportFileType: task.ExportFileType, + AuditResult: dmsV1.AuditTaskResult{ + AuditLevel: task.AuditLevel, + Score: task.AuditScore, + PassRate: task.AuditPassRate, + }, + }) + } + return &dmsV1.BatchGetDataExportTaskReply{ + Data: data, + }, nil +} + +func (d *DMSService) ListDataExportTaskSQLs(ctx context.Context, req *dmsV1.ListDataExportTaskSQLsReq, currentUserUid string) (reply *dmsV1.ListDataExportTaskSQLsReply, err error) { + + orderBy := biz.DataExportTaskRecordFieldNumber + + filterBy := []pkgConst.FilterCondition{{ + Field: string(biz.DataExportTaskRecordFieldDataExportTaskId), + Operator: pkgConst.FilterOperatorEqual, + Value: req.DataExportTaskUid, + }} + + listOption := &biz.ListDataExportTaskRecordOption{ + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: pkgConst.ConditionsToFilterOptions(filterBy), + } + + taskRecords, total, err := d.DataExportWorkflowUsecase.ListDataExportTaskRecords(ctx, listOption, currentUserUid) + if nil != err { + return nil, err + } + + ret := make([]*dmsV1.ListDataExportTaskSQL, len(taskRecords)) + for i, w := range taskRecords { + ret[i] = &dmsV1.ListDataExportTaskSQL{ + ID: w.Number, + ExportSQL: w.ExportSQL, + AuditLevel: w.AuditLevel, + ExportResult: w.ExportResult, + ExportSQLType: w.ExportSQLType, + } + if w.AuditSQLResults != nil { + for _, result := range w.AuditSQLResults { + ret[i].AuditSQLResult = append(ret[i].AuditSQLResult, dmsV1.AuditSQLResult{ + Level: result.Level, + Message: result.GetAuditMsgByLangTag(locale.Bundle.GetLangTagFromCtx(ctx)), + ErrorInfo: result.GetAuditErrorMsgByLangTag(locale.Bundle.GetLangTagFromCtx(ctx)), + ExecutionFailed: result.ExecutionFailed, + RuleName: result.RuleName, + }) + } + } + } + + return &dmsV1.ListDataExportTaskSQLsReply{ + Data: ret, + Total: total, + }, nil +} + +func (d *DMSService) ApproveDataExportWorkflow(ctx context.Context, req *dmsV1.ApproveDataExportWorkflowReq, userId string) (err error) { + return d.DataExportWorkflowUsecase.ApproveDataExportWorkflow(ctx, req.ProjectUid, req.DataExportWorkflowUid, userId) +} + +func (d *DMSService) RejectDataExportWorkflow(ctx context.Context, req *dmsV1.RejectDataExportWorkflowReq, userId string) (err error) { + return d.DataExportWorkflowUsecase.RejectDataExportWorkflow(ctx, req, userId) +} + +func (d *DMSService) CancelDataExportWorkflow(ctx context.Context, req *dmsV1.CancelDataExportWorkflowReq, userId string) (err error) { + return d.DataExportWorkflowUsecase.CancelDataExportWorkflow(ctx, userId, req) +} + +func (d *DMSService) DownloadDataExportTask(ctx context.Context, req *dmsV1.DownloadDataExportTaskReq, userId string) (bool, string, error) { + return d.DataExportWorkflowUsecase.DownloadDataExportTask(ctx, userId, req) +} + +func (d *DMSService) DownloadDataExportTaskSQLs(ctx context.Context, req *dmsV1.DownloadDataExportTaskSQLsReq, userId string) (string, []byte, error) { + return d.DataExportWorkflowUsecase.DownloadDataExportTaskSQLs(ctx, req, userId) +} diff --git a/internal/dms/service/data_masking_ce.go b/internal/dms/service/data_masking_ce.go new file mode 100644 index 000000000..04f176ea1 --- /dev/null +++ b/internal/dms/service/data_masking_ce.go @@ -0,0 +1,101 @@ +//go:build !dms + +package service + +import ( + "context" + "errors" + + v1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/dms/storage" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" +) + +var errNotSupportDataMasking = errors.New("DataMasking related functions are dms version functions") + +func (d *DMSService) ConfigureMaskingRules(ctx context.Context, req *v1.ConfigureMaskingRulesReq, currentUserUid string) error { + return errNotSupportDataMasking +} + +func (d *DMSService) AddSensitiveDataDiscoveryTask(ctx context.Context, req *v1.AddSensitiveDataDiscoveryTaskReq) (reply *v1.AddSensitiveDataDiscoveryTaskReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) UpdateSensitiveDataDiscoveryTask(ctx context.Context, req *v1.UpdateSensitiveDataDiscoveryTaskReq) (reply *v1.UpdateSensitiveDataDiscoveryTaskReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) DeleteSensitiveDataDiscoveryTask(ctx context.Context, req *v1.DeleteSensitiveDataDiscoveryTaskReq) error { + return errNotSupportDataMasking +} + +func (d *DMSService) GetMaskingOverviewTree(ctx context.Context, req *v1.GetMaskingOverviewTreeReq, currentUserUid string) (reply *v1.GetMaskingOverviewTreeReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) GetTableColumnMaskingDetails(ctx context.Context, req *v1.GetTableColumnMaskingDetailsReq) (reply *v1.GetTableColumnMaskingDetailsReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) ListSensitiveDataDiscoveryTasks(ctx context.Context, req *v1.ListSensitiveDataDiscoveryTasksReq) (reply *v1.ListSensitiveDataDiscoveryTasksReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) ListSensitiveDataDiscoveryTaskHistories(ctx context.Context, req *v1.ListSensitiveDataDiscoveryTaskHistoriesReq) (reply *v1.ListSensitiveDataDiscoveryTaskHistoriesReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) ListMaskingRules(ctx context.Context) (reply *dmsV1.ListMaskingRulesReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) ListMaskingTemplates(ctx context.Context, req *dmsV1.ListMaskingTemplatesReq) (reply *dmsV1.ListMaskingTemplatesReply, err error) { + return nil, errNotSupportDataMasking +} + +func (d *DMSService) AddMaskingTemplate(ctx context.Context, req *dmsV1.AddMaskingTemplateReq) error { + return errNotSupportDataMasking +} + +func (d *DMSService) UpdateMaskingTemplate(ctx context.Context, req *dmsV1.UpdateMaskingTemplateReq) error { + return errNotSupportDataMasking +} + +func (d *DMSService) DeleteMaskingTemplate(ctx context.Context, req *dmsV1.DeleteMaskingTemplateReq) error { + return errNotSupportDataMasking +} + +func (d *DMSService) ListCreatableDBServicesForMaskingTask(ctx context.Context, req *v1.ListCreatableDBServicesForMaskingTaskReq, currentUserUid string) (*v1.ListCreatableDBServicesForMaskingTaskReply, error) { + return nil, errNotSupportDataMasking +} + +func initDataMaskingUsecase(_ utilLog.Logger, _ *storage.Storage, _ *biz.DBServiceUsecase, _ *biz.ClusterUsecase, _ biz.ProxyTargetRepo) (*dataMaskingUsecase, func(), error) { + return nil, func() {}, nil +} + +func newCloudbeaverSQLResultMasker(_ utilLog.Logger, _ *storage.Storage, _ biz.ProxyTargetRepo) (biz.SQLResultMasker, error) { + return nil, nil +} + +type dataMaskingDiscoveryTaskUsecase interface { + ListMaskingTaskStatus(ctx context.Context, dbServiceUIDs []string) (map[string]bool, error) + + GetSupportedDBTypesForDiscovery() []pkgConst.DBType +} + +type dataMaskingUsecase struct { + DiscoveryTaskUsecase dataMaskingDiscoveryTaskUsecase +} + +func initDataExportMaskingConfigRepo(_ utilLog.Logger, _ *storage.Storage) biz.DataExportMaskingConfigRepo { + return nil +} + +// registerFunctionProvidersToRegistry 在 CE 版本中为空实现 +func registerFunctionProvidersToRegistry(_ *biz.FunctionSupportRegistry, _ *dataMaskingUsecase) { + // CE 版本无功能提供者需要注册 +} diff --git a/internal/dms/service/db_service.go b/internal/dms/service/db_service.go index 3cf3c91d6..33d29bca8 100644 --- a/internal/dms/service/db_service.go +++ b/internal/dms/service/db_service.go @@ -3,13 +3,18 @@ package service import ( "context" "fmt" + "time" dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + dmsV2 "github.com/actiontech/dms/api/dms/service/v2" "github.com/actiontech/dms/internal/dms/biz" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + dmsCommonV2 "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" pkgAes "github.com/actiontech/dms/pkg/dms-common/pkg/aes" "github.com/actiontech/dms/pkg/params" "github.com/actiontech/dms/pkg/periods" + "github.com/go-openapi/strfmt" ) func (d *DMSService) DelDBService(ctx context.Context, req *dmsV1.DelDBServiceReq, currentUserUid string) (err error) { @@ -25,13 +30,16 @@ func (d *DMSService) DelDBService(ctx context.Context, req *dmsV1.DelDBServiceRe return nil } -func (d *DMSService) UpdateDBService(ctx context.Context, req *dmsV1.UpdateDBServiceReq, currentUserUid string) (err error) { +func (d *DMSService) UpdateDBService(ctx context.Context, req *dmsV2.UpdateDBServiceReq, currentUserUid string) (err error) { d.log.Infof("UpdateDBService.req=%v", req) defer func() { d.log.Infof("UpdateDBService.req=%v;error=%v", req, err) }() - additionalParams := params.AdditionalParameter[string(req.DBService.DBType)] + additionalParams, err := d.DBServiceUsecase.GetDriverParamsByDBType(ctx, req.DBService.DBType) + if err != nil { + return err + } for _, additionalParam := range req.DBService.AdditionalParams { err = additionalParams.SetParamValue(additionalParam.Name, additionalParam.Value) if err != nil { @@ -39,41 +47,32 @@ func (d *DMSService) UpdateDBService(ctx context.Context, req *dmsV1.UpdateDBSer } } - var dbType pkgConst.DBType - switch req.DBService.DBType { - case dmsV1.DBTypeMySQL: - dbType = pkgConst.DBTypeMySQL - case dmsV1.DBTypeOceanBaseMySQL: - dbType = pkgConst.DBTypeOceanBaseMySQL - default: - return fmt.Errorf("invalid db type: %s", req.DBService.DBType) - } args := &biz.BizDBServiceArgs{ - DBType: dbType, + DBType: req.DBService.DBType, Desc: req.DBService.Desc, Host: req.DBService.Host, Port: req.DBService.Port, - AdminUser: req.DBService.User, - AdminPassword: req.DBService.Password, - Business: req.DBService.Business, + User: req.DBService.User, + Password: req.DBService.Password, + EnvironmentTagUID: req.DBService.EnvironmentTagUID, + EnableBackup: req.DBService.EnableBackup, + BackupMaxRows: autoChooseBackupMaxRows(req.DBService.EnableBackup, req.DBService.BackupMaxRows), MaintenancePeriod: d.convertMaintenanceTimeToPeriod(req.DBService.MaintenanceTimes), AdditionalParams: additionalParams, } sqleConfig := req.DBService.SQLEConfig if sqleConfig != nil { + args.AuditEnabled = sqleConfig.AuditEnabled args.RuleTemplateName = sqleConfig.RuleTemplateName args.RuleTemplateID = sqleConfig.RuleTemplateID + args.DataExportRuleTemplateName = sqleConfig.DataExportRuleTemplateName + args.DataExportRuleTemplateID = sqleConfig.DataExportRuleTemplateID if sqleConfig.SQLQueryConfig != nil { - args.SQLQueryConfig = &biz.SQLQueryConfig{ - MaxPreQueryRows: sqleConfig.SQLQueryConfig.MaxPreQueryRows, - QueryTimeoutSecond: sqleConfig.SQLQueryConfig.QueryTimeoutSecond, - AuditEnabled: sqleConfig.SQLQueryConfig.AuditEnabled, - AllowQueryWhenLessThanAuditLevel: string(sqleConfig.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel), - } + args.SQLQueryConfig = d.bizSQLQueryConfigFromAPI(sqleConfig.SQLQueryConfig) } } - if err := d.DBServiceUsecase.UpdateDBService(ctx, req.DBServiceUid, args, currentUserUid); err != nil { + if err := d.DBServiceUsecase.UpdateDBServiceByArgs(ctx, req.DBServiceUid, args, currentUserUid); err != nil { return fmt.Errorf("update db service failed: %v", err) } @@ -81,67 +80,217 @@ func (d *DMSService) UpdateDBService(ctx context.Context, req *dmsV1.UpdateDBSer } func (d *DMSService) CheckDBServiceIsConnectable(ctx context.Context, req *dmsV1.CheckDBServiceIsConnectableReq) (reply *dmsV1.CheckDBServiceIsConnectableReply, err error) { - d.log.Infof("CheckDBServiceIsConnectable.req=%v", req) - defer func() { - d.log.Infof("CheckDBServiceIsConnectable.req=%v; error=%v", req, err) - }() + results, err := d.DBServiceUsecase.IsConnectable(ctx, req.DBService) - dbType, err := pkgConst.ParseDBType(req.DBService.DBType) if err != nil { + d.log.Errorf("IsConnectable err: %v", err) return nil, err } - additionalParams := params.AdditionalParameter[req.DBService.DBType] - for _, additionalParam := range req.DBService.AdditionalParams { - err = additionalParams.SetParamValue(additionalParam.Name, additionalParam.Value) - if err != nil { - return nil, fmt.Errorf("set param value failed,invalid db type: %s", req.DBService.DBType) - } + ret := &dmsV1.CheckDBServiceIsConnectableReply{} + for _, item := range results { + ret.Data = append(ret.Data, dmsV1.CheckDBServiceIsConnectableReplyItem{ + IsConnectable: item.IsConnectable, + Component: item.Component, + ConnectErrorMessage: item.ConnectErrorMessage, + }) } - IsConnectableParams := biz.IsConnectableParams{ - DBType: dbType, - Host: req.DBService.Host, - Port: req.DBService.Port, - User: req.DBService.User, - Password: req.DBService.Password, - AdditionalParams: additionalParams, + return ret, nil +} + +func (d *DMSService) CheckDBServiceIsConnectableById(ctx context.Context, req *dmsV1.CheckDBServiceIsConnectableByIdReq) (reply *dmsV1.CheckDBServiceIsConnectableReply, err error) { + dbService, err := d.DBServiceUsecase.GetDBService(ctx, req.DBServiceUid) + if err != nil { + return nil, err } - isConnectable, err := d.DBServiceUsecase.IsConnectable(ctx, IsConnectableParams) + var additionParams []*dmsCommonV1.AdditionalParam + for _, item := range dbService.AdditionalParams { + additionParams = append(additionParams, &dmsCommonV1.AdditionalParam{ + Name: item.Key, + Value: item.Value, + }) + } - connectErrorMessage := "" + checkDbConnectableParams := dmsCommonV1.CheckDbConnectable{ + DBType: dbService.DBType, + User: dbService.User, + Host: dbService.Host, + Port: dbService.Port, + Password: dbService.Password, + AdditionalParams: additionParams, + } + results, err := d.DBServiceUsecase.IsConnectable(ctx, checkDbConnectableParams) if err != nil { d.log.Errorf("IsConnectable err: %v", err) - connectErrorMessage = err.Error() + d.updateConnectionStatus(ctx, false, err.Error(), dbService) + return nil, err + } + isSuccess, connectMsg := isConnectedSuccess(results) + d.updateConnectionStatus(ctx, isSuccess, connectMsg, dbService) + ret := &dmsV1.CheckDBServiceIsConnectableReply{} + for _, item := range results { + ret.Data = append(ret.Data, dmsV1.CheckDBServiceIsConnectableReplyItem{ + IsConnectable: item.IsConnectable, + Component: item.Component, + ConnectErrorMessage: item.ConnectErrorMessage, + }) + } + + return ret, nil +} + +func (d *DMSService) updateConnectionStatus(ctx context.Context, isSuccess bool, errorMsg string, dbService *biz.DBService) { + lastConnectionStatus := biz.LastConnectionStatusSuccess + lastConnectionTime := time.Now() + dbService.LastConnectionTime = &lastConnectionTime + if !isSuccess { + lastConnectionStatus = biz.LastConnectionStatusFailed + dbService.LastConnectionStatus = &lastConnectionStatus + dbService.LastConnectionErrorMsg = &errorMsg + } else { + lastConnectionStatus = biz.LastConnectionStatusSuccess + dbService.LastConnectionStatus = &lastConnectionStatus + dbService.LastConnectionErrorMsg = nil + } + err := d.DBServiceUsecase.UpdateDBService(ctx, dbService, pkgConst.UIDOfUserAdmin) + if err != nil { + d.log.Errorf("dbService name: %v,UpdateDBServiceByBiz err: %v", dbService.Name, err) + } +} + +func isConnectedSuccess(results []*biz.IsConnectableReply) (bool, string) { + if len(results) == 0 { + return false, "check db connectable failed" + } + for _, connectableResult := range results { + if !connectableResult.IsConnectable { + return false, connectableResult.ConnectErrorMessage + } + } + return true, "" +} + +func (d *DMSService) CheckDBServiceIsConnectableByIds(ctx context.Context, projectUID, currentUserUid string, dbServiceList []dmsV1.DbServiceConnections) (*dmsV1.DBServicesConnectionReqReply, error) { + if len(dbServiceList) == 0 { + return &dmsV1.DBServicesConnectionReqReply{ + Data: []dmsV1.DBServiceIsConnectableReply{}, + }, nil + } + + filterBy := make([]pkgConst.FilterCondition, 0) + var dbServiceUidList []string + for _, dbService := range dbServiceList { + dbServiceUidList = append(dbServiceUidList, dbService.DBServiceUid) + } + + filterBy = append(filterBy, pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldUID), + Operator: pkgConst.FilterOperatorIn, + Value: dbServiceUidList, + }) + + listOption := &biz.ListDBServicesOption{ + PageNumber: 1, + LimitPerPage: uint32(len(dbServiceList)), + OrderBy: biz.DBServiceFieldName, + FilterByOptions: pkgConst.ConditionsToFilterOptions(filterBy), + } + + DBServiceList, _, err := d.DBServiceUsecase.ListDBService(ctx, listOption, projectUID, currentUserUid) + if err != nil { + return nil, err } - return &dmsV1.CheckDBServiceIsConnectableReply{ - Payload: struct { - IsConnectable bool `json:"is_connectable"` - ConnectErrorMessage string `json:"connect_error_message,omitempty"` - }{IsConnectable: isConnectable, ConnectErrorMessage: connectErrorMessage}, + resp := d.DBServiceUsecase.TestDbServiceConnections(ctx, DBServiceList, currentUserUid) + + return &dmsV1.DBServicesConnectionReqReply{ + Data: resp, }, nil } +const DefaultBackupMaxRows uint64 = 1000 + +// autoChooseBackupMaxRows 函数根据是否启用备份以及备份最大行数的设置来确定最终的备份最大行数。 +// 参数: +// - enableBackup: 是否启用备份。 +// - backupMaxRows: 备份最大行数的设置,如果未设置,则为 nil。 +// +// 返回值: +// - int64: 最终确定的备份最大行数。 +func autoChooseBackupMaxRows(enableBackup bool, backupMaxRows *uint64) uint64 { + // 如果启用了备份并且备份最大行数的设置不为 nil,则返回设置的备份最大行数。 + if enableBackup && backupMaxRows != nil { + return *backupMaxRows + } + // 如果未启用备份或者备份最大行数的设置为 nil,则返回默认的备份最大行数 DefaultBackupMaxRows。 + return DefaultBackupMaxRows +} + +// Deprecated func (d *DMSService) AddDBService(ctx context.Context, req *dmsV1.AddDBServiceReq, currentUserUid string) (reply *dmsV1.AddDBServiceReply, err error) { d.log.Infof("AddDBServices.req=%v", req) defer func() { d.log.Infof("AddDBServices.req=%v;reply=%v;error=%v", req, reply, err) }() - // TODO 预期这里不做校验,从dms同步出去的数据自行判断数据源类型是否支持 - var dbType pkgConst.DBType - switch req.DBService.DBType { - case dmsV1.DBTypeMySQL: - dbType = pkgConst.DBTypeMySQL - case dmsV1.DBTypeOceanBaseMySQL: - dbType = pkgConst.DBTypeOceanBaseMySQL - default: - return nil, fmt.Errorf("invalid db type: %s", req.DBService.DBType) + additionalParams, err := d.DBServiceUsecase.GetDriverParamsByDBType(ctx, req.DBService.DBType) + for _, additionalParam := range req.DBService.AdditionalParams { + err = additionalParams.SetParamValue(additionalParam.Name, additionalParam.Value) + if err != nil { + return nil, fmt.Errorf("set param value failed,invalid db type: %s", req.DBService.DBType) + } } - additionalParams := params.AdditionalParameter[string(req.DBService.DBType)] + args := &biz.BizDBServiceArgs{ + Name: req.DBService.Name, + Desc: &req.DBService.Desc, + DBType: req.DBService.DBType, + Host: req.DBService.Host, + Port: req.DBService.Port, + User: req.DBService.User, + Password: &req.DBService.Password, + // Business: req.DBService.Business, + MaintenancePeriod: d.convertMaintenanceTimeToPeriod(req.DBService.MaintenanceTimes), + ProjectUID: req.ProjectUid, + Source: string(pkgConst.DBServiceSourceNameSQLE), + AdditionalParams: additionalParams, + EnableBackup: req.DBService.EnableBackup, + BackupMaxRows: autoChooseBackupMaxRows(req.DBService.EnableBackup, req.DBService.BackupMaxRows), + } + + sqleConfig := req.DBService.SQLEConfig + if sqleConfig != nil { + args.AuditEnabled = sqleConfig.AuditEnabled + args.RuleTemplateName = sqleConfig.RuleTemplateName + args.RuleTemplateID = sqleConfig.RuleTemplateID + args.DataExportRuleTemplateName = sqleConfig.DataExportRuleTemplateName + args.DataExportRuleTemplateID = sqleConfig.DataExportRuleTemplateID + if sqleConfig.SQLQueryConfig != nil { + args.SQLQueryConfig = d.bizSQLQueryConfigFromAPI(sqleConfig.SQLQueryConfig) + } + } + uid, err := d.DBServiceUsecase.CreateDBService(ctx, args, currentUserUid) + if err != nil { + return nil, fmt.Errorf("create db service failed: %w", err) + } + + return &dmsV1.AddDBServiceReply{ + Data: struct { + // db service UID + Uid string `json:"uid"` + }{Uid: uid}, + }, nil +} + +func (d *DMSService) AddDBServiceV2(ctx context.Context, req *dmsV2.AddDBServiceReq, currentUserUid string) (reply *dmsV1.AddDBServiceReply, err error) { + d.log.Infof("AddDBServices.req=%v", req) + defer func() { + d.log.Infof("AddDBServices.req=%v;reply=%v;error=%v", req, reply, err) + }() + + additionalParams, err := d.DBServiceUsecase.GetDriverParamsByDBType(ctx, req.DBService.DBType) for _, additionalParam := range req.DBService.AdditionalParams { err = additionalParams.SetParamValue(additionalParam.Name, additionalParam.Value) if err != nil { @@ -152,28 +301,29 @@ func (d *DMSService) AddDBService(ctx context.Context, req *dmsV1.AddDBServiceRe args := &biz.BizDBServiceArgs{ Name: req.DBService.Name, Desc: &req.DBService.Desc, - DBType: dbType, + DBType: req.DBService.DBType, Host: req.DBService.Host, Port: req.DBService.Port, - AdminUser: req.DBService.User, - AdminPassword: &req.DBService.Password, - Business: req.DBService.Business, + User: req.DBService.User, + Password: &req.DBService.Password, + EnvironmentTagUID: req.DBService.EnvironmentTagUID, MaintenancePeriod: d.convertMaintenanceTimeToPeriod(req.DBService.MaintenanceTimes), - NamespaceUID: req.DBService.NamespaceUID, + ProjectUID: req.ProjectUid, + Source: string(pkgConst.DBServiceSourceNameSQLE), AdditionalParams: additionalParams, + EnableBackup: req.DBService.EnableBackup, + BackupMaxRows: autoChooseBackupMaxRows(req.DBService.EnableBackup, req.DBService.BackupMaxRows), } sqleConfig := req.DBService.SQLEConfig if sqleConfig != nil { + args.AuditEnabled = sqleConfig.AuditEnabled args.RuleTemplateName = sqleConfig.RuleTemplateName args.RuleTemplateID = sqleConfig.RuleTemplateID + args.DataExportRuleTemplateName = sqleConfig.DataExportRuleTemplateName + args.DataExportRuleTemplateID = sqleConfig.DataExportRuleTemplateID if sqleConfig.SQLQueryConfig != nil { - args.SQLQueryConfig = &biz.SQLQueryConfig{ - MaxPreQueryRows: sqleConfig.SQLQueryConfig.MaxPreQueryRows, - QueryTimeoutSecond: sqleConfig.SQLQueryConfig.QueryTimeoutSecond, - AuditEnabled: sqleConfig.SQLQueryConfig.AuditEnabled, - AllowQueryWhenLessThanAuditLevel: string(sqleConfig.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel), - } + args.SQLQueryConfig = d.bizSQLQueryConfigFromAPI(sqleConfig.SQLQueryConfig) } } uid, err := d.DBServiceUsecase.CreateDBService(ctx, args, currentUserUid) @@ -182,14 +332,45 @@ func (d *DMSService) AddDBService(ctx context.Context, req *dmsV1.AddDBServiceRe } return &dmsV1.AddDBServiceReply{ - Payload: struct { + Data: struct { // db service UID Uid string `json:"uid"` }{Uid: uid}, }, nil } -func (d *DMSService) convertMaintenanceTimeToPeriod(mt []*dmsV1.MaintenanceTime) periods.Periods { +func (d *DMSService) bizSQLQueryConfigFromAPI(src *dmsCommonV1.SQLQueryConfig) *biz.SQLQueryConfig { + if src == nil { + return nil + } + maintenancePeriods := d.convertMaintenanceTimeToPeriod(src.MaintenanceTimes) + return &biz.SQLQueryConfig{ + MaxPreQueryRows: src.MaxPreQueryRows, + QueryTimeoutSecond: src.QueryTimeoutSecond, + AuditEnabled: src.AuditEnabled, + WorkflowExecEnabled: src.WorkflowExecEnabled, + AllowQueryWhenLessThanAuditLevel: string(src.AllowQueryWhenLessThanAuditLevel), + RuleTemplateID: src.RuleTemplateID, + RuleTemplateName: src.RuleTemplateName, + MaintenancePeriods: maintenancePeriods, + } +} + +func (d *DMSService) fillAPISQLQueryConfig(dst *dmsCommonV1.SQLQueryConfig, src *biz.SQLQueryConfig) { + if src == nil { + return + } + dst.MaxPreQueryRows = src.MaxPreQueryRows + dst.QueryTimeoutSecond = src.QueryTimeoutSecond + dst.AuditEnabled = src.AuditEnabled + dst.WorkflowExecEnabled = src.WorkflowExecEnabled + dst.AllowQueryWhenLessThanAuditLevel = dmsCommonV1.SQLAllowQueryAuditLevel(src.AllowQueryWhenLessThanAuditLevel) + dst.RuleTemplateID = src.RuleTemplateID + dst.RuleTemplateName = src.RuleTemplateName + dst.MaintenanceTimes = d.convertPeriodToMaintenanceTime(src.MaintenancePeriods) +} + +func (d *DMSService) convertMaintenanceTimeToPeriod(mt []*dmsCommonV1.MaintenanceTime) periods.Periods { ps := make(periods.Periods, len(mt)) for i, time := range mt { ps[i] = &periods.Period{ @@ -202,15 +383,15 @@ func (d *DMSService) convertMaintenanceTimeToPeriod(mt []*dmsV1.MaintenanceTime) return ps } -func (d *DMSService) convertPeriodToMaintenanceTime(p periods.Periods) []*dmsV1.MaintenanceTime { - periods := make([]*dmsV1.MaintenanceTime, len(p)) +func (d *DMSService) convertPeriodToMaintenanceTime(p periods.Periods) []*dmsCommonV1.MaintenanceTime { + periods := make([]*dmsCommonV1.MaintenanceTime, len(p)) for i, time := range p { - periods[i] = &dmsV1.MaintenanceTime{ - MaintenanceStartTime: &dmsV1.Time{ + periods[i] = &dmsCommonV1.MaintenanceTime{ + MaintenanceStartTime: &dmsCommonV1.Time{ Hour: time.StartHour, Minute: time.StartMinute, }, - MaintenanceStopTime: &dmsV1.Time{ + MaintenanceStopTime: &dmsCommonV1.Time{ Hour: time.EndHour, Minute: time.EndMinute, }, @@ -219,31 +400,132 @@ func (d *DMSService) convertPeriodToMaintenanceTime(p periods.Periods) []*dmsV1. return periods } -func (d *DMSService) ListDBServices(ctx context.Context, req *dmsV1.ListDBServiceReq, currentUserUid string) (reply *dmsV1.ListDBServiceReply, err error) { - d.log.Infof("ListDBServices.req=%v", req) - defer func() { - d.log.Infof("ListDBServices.req=%v;reply=%v;error=%v", req, reply, err) - }() +func (d *DMSService) convertBizDBServiceArgs2ImportDBService(dbs []*biz.BizDBServiceArgs) []*dmsV2.ImportDBService { + ret := make([]*dmsV2.ImportDBService, len(dbs)) + for i, u := range dbs { + ret[i] = &dmsV2.ImportDBService{ + Name: u.Name, + DBType: u.DBType, + Host: u.Host, + Port: u.Port, + User: u.User, + Password: *u.Password, + MaintenanceTimes: d.convertPeriodToMaintenanceTime(u.MaintenancePeriod), + Desc: *u.Desc, + Source: u.Source, + ProjectUID: u.ProjectUID, + SQLEConfig: &dmsCommonV1.SQLEConfig{ + AuditEnabled: u.AuditEnabled, + RuleTemplateName: u.RuleTemplateName, + RuleTemplateID: u.RuleTemplateID, + DataExportRuleTemplateName: u.DataExportRuleTemplateName, + DataExportRuleTemplateID: u.DataExportRuleTemplateID, + SQLQueryConfig: nil, + }, + AdditionalParams: nil, + EnvironmentTagName: u.EnvironmentTagName, + } + + if u.AdditionalParams != nil { + additionalParams := make([]*dmsCommonV1.AdditionalParam, 0, len(u.AdditionalParams)) + for _, item := range u.AdditionalParams { + additionalParams = append(additionalParams, &dmsCommonV1.AdditionalParam{ + Name: item.Key, + Value: item.Value, + Description: item.Desc, + Type: string(item.Type), + }) + } + ret[i].AdditionalParams = additionalParams + } + + if u.SQLQueryConfig != nil { + ret[i].SQLEConfig.SQLQueryConfig = &dmsCommonV1.SQLQueryConfig{} + d.fillAPISQLQueryConfig(ret[i].SQLEConfig.SQLQueryConfig, u.SQLQueryConfig) + } + } + return ret +} + +func (d *DMSService) convertImportDBService2BizDBService(ctx context.Context, importDbs []dmsV2.ImportDBService, currentUserUid string) ([]*biz.DBService, error) { + ret := make([]*biz.DBService, len(importDbs)) + for i, u := range importDbs { + ret[i] = &biz.DBService{ + UID: "", + Name: u.Name, + Desc: u.Desc, + DBType: u.DBType, + Host: u.Host, + Port: u.Port, + User: u.User, + Password: u.Password, + AdditionalParams: nil, + ProjectUID: u.ProjectUID, + MaintenancePeriod: d.convertMaintenanceTimeToPeriod(u.MaintenanceTimes), + Source: u.Source, + SQLEConfig: nil, + AccountPurpose: "", + } + tag, err := d.EnvironmentTagUsecase.GetOrCreateEnvironmentTag(ctx, u.ProjectUID, u.EnvironmentTagName) + if err != nil { + return nil, fmt.Errorf("get or create environment tag failed: %v", err) + } + ret[i].EnvironmentTag = &dmsCommonV1.EnvironmentTag{ + UID: tag.UID, + } + if u.AdditionalParams != nil { + additionalParams := make([]*params.Param, 0, len(u.AdditionalParams)) + for _, item := range u.AdditionalParams { + additionalParams = append(additionalParams, ¶ms.Param{ + Key: item.Name, + Value: item.Value, + Desc: item.Description, + Type: params.ParamType(item.Type), + }) + } + ret[i].AdditionalParams = additionalParams + } + + if u.SQLEConfig != nil { + sqlConfig := &biz.SQLEConfig{ + AuditEnabled: u.SQLEConfig.AuditEnabled, + RuleTemplateName: u.SQLEConfig.RuleTemplateName, + RuleTemplateID: u.SQLEConfig.RuleTemplateID, + DataExportRuleTemplateName: u.SQLEConfig.DataExportRuleTemplateName, + DataExportRuleTemplateID: u.SQLEConfig.DataExportRuleTemplateID, + } + if u.SQLEConfig.SQLQueryConfig != nil { + sqlConfig.SQLQueryConfig = d.bizSQLQueryConfigFromAPI(u.SQLEConfig.SQLQueryConfig) + } + ret[i].SQLEConfig = sqlConfig + } + } + return ret, nil +} + +func (d *DMSService) ListDBServices(ctx context.Context, req *dmsCommonV2.ListDBServiceReq, currentUserUid string) (reply *dmsCommonV2.ListDBServiceReply, err error) { var orderBy biz.DBServiceField switch req.OrderBy { - case dmsV1.DBServiceOrderByName: + case dmsCommonV1.DBServiceOrderByName: orderBy = biz.DBServiceFieldName default: orderBy = biz.DBServiceFieldName } - filterBy := make([]pkgConst.FilterCondition, 0) - if req.FilterByBusiness != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ - Field: string(biz.DBServiceFieldBusiness), - Operator: pkgConst.FilterOperatorContains, - Value: req.FilterByBusiness, + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) + if req.FilterByEnvironmentTagUID != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldEnvironmentTagUID), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterByEnvironmentTagUID, }) } if req.FilterByHost != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.DBServiceFieldHost), Operator: pkgConst.FilterOperatorEqual, Value: req.FilterByHost, @@ -251,15 +533,23 @@ func (d *DMSService) ListDBServices(ctx context.Context, req *dmsV1.ListDBServic } if req.FilterByUID != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.DBServiceFieldUID), Operator: pkgConst.FilterOperatorEqual, Value: req.FilterByUID, }) } + if req.FilterByName != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldName), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterByName, + }) + } + if req.FilterByPort != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.DBServiceFieldPort), Operator: pkgConst.FilterOperatorEqual, Value: req.FilterByPort, @@ -267,76 +557,209 @@ func (d *DMSService) ListDBServices(ctx context.Context, req *dmsV1.ListDBServic } if req.FilterByDBType != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.DBServiceFieldDBType), Operator: pkgConst.FilterOperatorEqual, Value: req.FilterByDBType, }) } - if req.FilterByNamespaceUid != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ - Field: string(biz.DBServiceFieldNamespaceUID), + if req.ProjectUid != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldProjectUID), + Operator: pkgConst.FilterOperatorEqual, + Value: req.ProjectUid, + }) + } + if req.FilterLastConnectionTestStatus != nil { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldLastConnectionStatus), Operator: pkgConst.FilterOperatorEqual, - Value: req.FilterByNamespaceUid, + Value: *req.FilterLastConnectionTestStatus, + }) + } + if len(req.FilterByDBServiceIds) > 0 { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldUID), + Operator: pkgConst.FilterOperatorIn, + Value: req.FilterByDBServiceIds, }) } + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + + if req.FuzzyKeyword != "" { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicOr, + pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldPort), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + pkgConst.FilterCondition{ + Field: string(biz.DBServiceFieldHost), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + )) + } + listOption := &biz.ListDBServicesOption{ - PageNumber: req.PageIndex, - LimitPerPage: req.PageSize, - OrderBy: orderBy, - FilterBy: filterBy, + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, } - service, total, err := d.DBServiceUsecase.ListDBService(ctx, listOption, req.FilterByNamespaceUid, currentUserUid) + hasPermission, err := d.OpPermissionVerifyUsecase.HasViewPermission(ctx, currentUserUid, req.ProjectUid, pkgConst.UIdOfOpPermissionManageProjectDataSource) + if err != nil { + return nil, fmt.Errorf("check user has permission manageDataSource: %v", err) + } + if !hasPermission { + return nil, fmt.Errorf("user is not admin or data source management permission") + } + + service, total, err := d.DBServiceUsecase.ListDBService(ctx, listOption, req.ProjectUid, currentUserUid) if nil != err { return nil, err } - ret := make([]*dmsV1.ListDBService, len(service)) + var dbServiceUids []string + for _, u := range service { + dbServiceUids = append(dbServiceUids, u.UID) + } + maskingTaskStatusMap := make(map[string]bool) + if d.DataMaskingUsecase != nil && d.DataMaskingUsecase.DiscoveryTaskUsecase != nil { + maskingTaskStatusMap, _ = d.DataMaskingUsecase.DiscoveryTaskUsecase.ListMaskingTaskStatus(ctx, dbServiceUids) + } + + ret := make([]*dmsCommonV2.ListDBService, len(service)) for i, u := range service { - password, err := pkgAes.AesEncrypt(u.AdminPassword) + password, err := pkgAes.AesEncrypt(u.Password) if err != nil { return nil, fmt.Errorf("failed to encrypt password: %w", err) } - ret[i] = &dmsV1.ListDBService{ - DBServiceUid: u.GetUID(), - Name: u.Name, - DBType: dmsV1.DBType(u.DBType), - Host: u.Host, - Port: u.Port, - User: u.AdminUser, - Password: password, - Business: u.Business, - MaintenanceTimes: d.convertPeriodToMaintenanceTime(u.MaintenancePeriod), - Desc: u.Desc, - Source: u.Source, - NamespaceUID: u.NamespaceUID, - // TODO 从provision获取 - // LastSyncDataResult: "TODO", - // LastSyncDataTime:"". + ret[i] = &dmsCommonV2.ListDBService{ + DBServiceUid: u.GetUID(), + Name: u.Name, + DBType: u.DBType, + Host: u.Host, + Port: u.Port, + User: u.User, + Password: password, + EnvironmentTag: u.EnvironmentTag, + MaintenanceTimes: d.convertPeriodToMaintenanceTime(u.MaintenancePeriod), + Desc: u.Desc, + Source: u.Source, + ProjectUID: u.ProjectUID, + IsEnableMasking: maskingTaskStatusMap[u.UID], + InstanceAuditPlanID: u.InstanceAuditPlanID, + AuditPlanTypes: u.AuditPlanTypes, + EnableBackup: u.EnableBackup, + BackupMaxRows: u.BackupMaxRows, } + + if u.LastConnectionTime != nil { + ret[i].LastConnectionTestTime = strfmt.DateTime(*u.LastConnectionTime) + } + if u.LastConnectionStatus != nil { + ret[i].LastConnectionTestStatus = dmsCommonV1.LastConnectionTestStatus(*u.LastConnectionStatus) + } + if u.LastConnectionErrorMsg != nil { + ret[i].LastConnectionTestErrorMessage = *u.LastConnectionErrorMsg + } + + if u.AdditionalParams != nil { + additionalParams := make([]*dmsCommonV1.AdditionalParam, 0, len(u.AdditionalParams)) + for _, item := range u.AdditionalParams { + additionalParams = append(additionalParams, &dmsCommonV1.AdditionalParam{ + Name: item.Key, + Value: item.Value, + Description: item.Desc, + Type: string(item.Type), + }) + } + ret[i].AdditionalParams = additionalParams + } + if u.SQLEConfig != nil { - sqlConfig := &dmsV1.SQLEConfig{ - RuleTemplateName: u.SQLEConfig.RuleTemplateName, - RuleTemplateID: u.SQLEConfig.RuleTemplateID, - SQLQueryConfig: &dmsV1.SQLQueryConfig{}, + sqlConfig := &dmsCommonV1.SQLEConfig{ + AuditEnabled: u.SQLEConfig.AuditEnabled, + RuleTemplateName: u.SQLEConfig.RuleTemplateName, + RuleTemplateID: u.SQLEConfig.RuleTemplateID, + DataExportRuleTemplateName: u.SQLEConfig.DataExportRuleTemplateName, + DataExportRuleTemplateID: u.SQLEConfig.DataExportRuleTemplateID, + SQLQueryConfig: &dmsCommonV1.SQLQueryConfig{}, } if u.SQLEConfig.SQLQueryConfig != nil { - sqlConfig.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel = dmsV1.SQLAllowQueryAuditLevel(u.SQLEConfig.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel) - sqlConfig.SQLQueryConfig.AuditEnabled = u.SQLEConfig.SQLQueryConfig.AuditEnabled - sqlConfig.SQLQueryConfig.MaxPreQueryRows = u.SQLEConfig.SQLQueryConfig.MaxPreQueryRows - sqlConfig.SQLQueryConfig.QueryTimeoutSecond = u.SQLEConfig.SQLQueryConfig.QueryTimeoutSecond + d.fillAPISQLQueryConfig(sqlConfig.SQLQueryConfig, u.SQLEConfig.SQLQueryConfig) } ret[i].SQLEConfig = sqlConfig } } - return &dmsV1.ListDBServiceReply{ - Payload: struct { - DBServices []*dmsV1.ListDBService `json:"db_services"` - Total int64 `json:"total"` - }{DBServices: ret, Total: total}, + return &dmsCommonV2.ListDBServiceReply{ + Data: ret, + Total: total, }, nil } + +func (d *DMSService) ListDBServiceTips(ctx context.Context, req *dmsV1.ListDBServiceTipsReq, userId string) (reply *dmsV1.ListDBServiceTipsReply, err error) { + dbServices, err := d.DBServiceUsecase.ListDBServiceTips(ctx, req, userId) + if err != nil { + return nil, err + } + + ret := make([]*dmsV1.ListDBServiceTipItem, 0, len(dbServices)) + for _, item := range dbServices { + ret = append(ret, &dmsV1.ListDBServiceTipItem{ + Id: item.UID, + Name: item.Name, + Host: item.Host, + Port: item.Port, + Type: item.DBType, + }) + } + + return &dmsV1.ListDBServiceTipsReply{ + Data: ret, + }, nil +} + +func (d *DMSService) ListDBServiceDriverOption(ctx context.Context) (reply *dmsV1.ListDBServiceDriverOptionReply, err error) { + options, err := d.DBServiceUsecase.ListDBServiceDriverOption(ctx) + if err != nil { + return nil, err + } + + ret := make([]*dmsV1.DatabaseDriverOption, 0, len(options)) + for _, item := range options { + ret = append(ret, &dmsV1.DatabaseDriverOption{ + DBType: item.DBType, + LogoPath: item.LogoPath, + Params: item.Params, + }) + } + + return &dmsV1.ListDBServiceDriverOptionReply{ + Data: ret, + }, nil +} + +func (d *DMSService) ListGlobalDBServices(ctx context.Context, req *dmsV2.ListGlobalDBServicesReq, currentUserUid string) (reply *dmsV2.ListGlobalDBServicesReply, err error) { + return d.listGlobalDBServices(ctx, req, currentUserUid) +} + +func (d *DMSService) ListGlobalDBServicesTips(ctx context.Context, req *dmsV1.ListGlobalDBServicesTipsReq, currentUserUid string) (reply *dmsV1.ListGlobalDBServicesTipsReply, err error) { + return d.listGlobalDBServicesTips(ctx, req, currentUserUid) +} + +func (d *DMSService) ImportDBServicesOfOneProjectCheck(ctx context.Context, userUid, projectUid, fileContent string) (*dmsV2.ImportDBServicesCheckReply, []byte, error) { + return d.importDBServicesOfOneProjectCheck(ctx, userUid, projectUid, fileContent) +} + +func (d *DMSService) ImportDBServicesOfOneProject(ctx context.Context, req *dmsV2.ImportDBServicesOfOneProjectReq, uid string) error { + return d.importDBServicesOfOneProject(ctx, req, uid) +} diff --git a/internal/dms/service/db_service_ce.go b/internal/dms/service/db_service_ce.go new file mode 100644 index 000000000..c7a052cb6 --- /dev/null +++ b/internal/dms/service/db_service_ce.go @@ -0,0 +1,30 @@ +//go:build !enterprise + +package service + +import ( + "context" + "errors" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + dmsV2 "github.com/actiontech/dms/api/dms/service/v2" +) + +var errNotSupportImportDBServices = errors.New("ImportDBServices related functions are enterprise version functions") +var errNotSupportGlobalDBServices = errors.New("GlobalDBServices related functions are enterprise version functions") + +func (d *DMSService) importDBServicesOfOneProjectCheck(ctx context.Context, userUid, projectUid, fileContent string) (*dmsV2.ImportDBServicesCheckReply, []byte, error) { + return nil, nil, errNotSupportImportDBServices +} + +func (d *DMSService) importDBServicesOfOneProject(ctx context.Context, req *dmsV2.ImportDBServicesOfOneProjectReq, uid string) error { + return errNotSupportImportDBServices +} + +func (d *DMSService) listGlobalDBServices(ctx context.Context, req *dmsV2.ListGlobalDBServicesReq, currentUserUid string) (reply *dmsV2.ListGlobalDBServicesReply, err error) { + return nil, errNotSupportGlobalDBServices +} + +func (d *DMSService) listGlobalDBServicesTips(ctx context.Context, req *dmsV1.ListGlobalDBServicesTipsReq, currentUserUid string) (reply *dmsV1.ListGlobalDBServicesTipsReply, err error) { + return nil, errNotSupportGlobalDBServices +} diff --git a/internal/dms/service/db_service_sync_task.go b/internal/dms/service/db_service_sync_task.go new file mode 100644 index 000000000..e177313d5 --- /dev/null +++ b/internal/dms/service/db_service_sync_task.go @@ -0,0 +1,172 @@ +package service + +import ( + "context" + "fmt" + + v1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +func (d *DMSService) AddDBServiceSyncTask(ctx context.Context, req *v1.AddDBServiceSyncTaskReq, currentUserId string) (reply *v1.AddDBServiceSyncTaskReply, err error) { + syncTask := d.toBizDBServiceSyncTask(&req.DBServiceSyncTask) + + uid, err := d.DBServiceSyncTaskUsecase.AddDBServiceSyncTask(ctx, syncTask, currentUserId) + if err != nil { + return nil, fmt.Errorf("create db_service_sync_task failed: %w", err) + } + + return &v1.AddDBServiceSyncTaskReply{ + Data: struct { + Uid string `json:"uid"` + }{Uid: uid}, + }, nil +} + +func (d *DMSService) toBizDBServiceSyncTask(syncTask *v1.DBServiceSyncTask) *biz.DBServiceSyncTask { + ret := &biz.DBServiceSyncTask{ + Name: syncTask.Name, + Source: syncTask.Source, + URL: syncTask.URL, + DbType: syncTask.DbType, + CronExpress: syncTask.CronExpress, + AdditionalParam: syncTask.AdditionalParam, + } + if syncTask.SQLEConfig != nil { + ret.SQLEConfig = &biz.SQLEConfig{ + AuditEnabled: syncTask.SQLEConfig.AuditEnabled, + RuleTemplateName: syncTask.SQLEConfig.RuleTemplateName, + RuleTemplateID: syncTask.SQLEConfig.RuleTemplateID, + DataExportRuleTemplateName: syncTask.SQLEConfig.DataExportRuleTemplateName, + DataExportRuleTemplateID: syncTask.SQLEConfig.DataExportRuleTemplateID, + } + if syncTask.SQLEConfig.SQLQueryConfig != nil { + ret.SQLEConfig.SQLQueryConfig = d.bizSQLQueryConfigFromAPI(syncTask.SQLEConfig.SQLQueryConfig) + } + } + if syncTask.AdditionalParam != nil { + ret.AdditionalParam = syncTask.AdditionalParam + } + return ret +} + +func (svc *DMSService) UpdateDBServiceSyncTask(ctx context.Context, req *v1.UpdateDBServiceSyncTaskReq, currentUserId string) error { + syncTask := svc.toBizDBServiceSyncTask(&req.DBServiceSyncTask) + err := svc.DBServiceSyncTaskUsecase.UpdateDBServiceSyncTask(ctx, req.DBServiceSyncTaskUid, syncTask, currentUserId) + if err != nil { + return fmt.Errorf("update db_service_sync_task failed: %w", err) + } + return nil +} + +func (d *DMSService) ListDBServiceSyncTask(ctx context.Context, currentUserUid string) (reply *v1.ListDBServiceSyncTasksReply, err error) { + syncTasks, err := d.DBServiceSyncTaskUsecase.ListDBServiceSyncTasks(ctx, currentUserUid) + if nil != err { + return nil, err + } + + ret := make([]*v1.ListDBServiceSyncTask, 0, len(syncTasks)) + for _, syncTask := range syncTasks { + ret = append(ret, &v1.ListDBServiceSyncTask{ + UID: syncTask.UID, + DBServiceSyncTask: toApiDBServiceSyncTask(d, syncTask), + LastSyncErr: syncTask.LastSyncErr, + LastSyncSuccessTime: syncTask.LastSyncSuccessTime, + }) + } + + return &v1.ListDBServiceSyncTasksReply{ + Data: ret, + }, nil +} + +func toApiDBServiceSyncTask(d *DMSService, syncTask *biz.DBServiceSyncTask) v1.DBServiceSyncTask { + return v1.DBServiceSyncTask{ + Name: syncTask.Name, + Source: syncTask.Source, + URL: syncTask.URL, + DbType: syncTask.DbType, + CronExpress: syncTask.CronExpress, + AdditionalParam: syncTask.AdditionalParam, + SQLEConfig: d.buildReplySqleConfig(syncTask.SQLEConfig), + } +} + +func (d *DMSService) buildReplySqleConfig(params *biz.SQLEConfig) *dmsCommonV1.SQLEConfig { + if params == nil { + return nil + } + + sqlConfig := &dmsCommonV1.SQLEConfig{ + AuditEnabled: params.AuditEnabled, + RuleTemplateName: params.RuleTemplateName, + RuleTemplateID: params.RuleTemplateID, + DataExportRuleTemplateName: params.DataExportRuleTemplateName, + DataExportRuleTemplateID: params.DataExportRuleTemplateID, + SQLQueryConfig: &dmsCommonV1.SQLQueryConfig{}, + } + if params.SQLQueryConfig != nil { + d.fillAPISQLQueryConfig(sqlConfig.SQLQueryConfig, params.SQLQueryConfig) + } + + return sqlConfig +} + +func (d *DMSService) ListDBServiceSyncTaskTips(ctx context.Context) (*v1.ListDBServiceSyncTaskTipsReply, error) { + tips, err := d.DBServiceSyncTaskUsecase.ListDBServiceSyncTaskTips(ctx) + if err != nil { + return nil, fmt.Errorf("list db_service_sync_task tips failed: %w", err) + } + data := make([]v1.DBServiceSyncTaskTip, 0, len(tips)) + for _, tip := range tips { + data = append(data, toApiDBServiceSyncTaskTips(tip)) + } + return &v1.ListDBServiceSyncTaskTipsReply{ + Data: data, + }, nil +} + +func toApiDBServiceSyncTaskTips(meta biz.ListDBServiceSyncTaskTips) v1.DBServiceSyncTaskTip { + return v1.DBServiceSyncTaskTip{ + Type: meta.Type, + Desc: meta.Desc, + DBType: meta.DBTypes, + Params: meta.Params, + } +} + +func (d *DMSService) GetDBServiceSyncTask(ctx context.Context, req *v1.GetDBServiceSyncTaskReq, currentUserUid string) (reply *v1.GetDBServiceSyncTaskReply, err error) { + syncTask, err := d.DBServiceSyncTaskUsecase.GetDBServiceSyncTask(ctx, req.DBServiceSyncTaskUid, currentUserUid) + if nil != err { + return nil, err + } + + item := &v1.GetDBServiceSyncTask{ + UID: syncTask.UID, + DBServiceSyncTask: toApiDBServiceSyncTask(d, syncTask), + } + + return &v1.GetDBServiceSyncTaskReply{ + Data: item, + }, nil +} + +func (d *DMSService) DeleteDBServiceSyncTask(ctx context.Context, req *v1.DeleteDBServiceSyncTaskReq, currentUserId string) (err error) { + err = d.DBServiceSyncTaskUsecase.DeleteDBServiceSyncTask(ctx, req.DBServiceSyncTaskUid, currentUserId) + if err != nil { + return fmt.Errorf("delete db_service_sync_task failed: %w", err) + } + + return nil +} + +func (d *DMSService) SyncDBServices(ctx context.Context, req *v1.SyncDBServicesReq, currentUserId string) (err error) { + err = d.DBServiceSyncTaskUsecase.SyncDBServices(ctx, req.DBServiceSyncTaskUid, currentUserId) + if err != nil { + d.log.Errorf("sync db_service_sync_task failed: %v", err) + return fmt.Errorf("sync db_service_sync_task failed: %v", err) + } + + return nil +} diff --git a/internal/dms/service/environment_tag.go b/internal/dms/service/environment_tag.go new file mode 100644 index 000000000..c16e4e0e1 --- /dev/null +++ b/internal/dms/service/environment_tag.go @@ -0,0 +1,93 @@ +package service + +import ( + "context" + "fmt" + + v1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +func (d *DMSService) CreateEnvironmentTag(ctx context.Context, projectUid, currentUserUid, environmentTagName string) (err error) { + d.log.Infof("CreateEnvironmentTag.req=%v", environmentTagName) + defer func() { + d.log.Infof("CreateEnvironmentTag.req=%v;error=%v", environmentTagName, err) + }() + + if err := d.EnvironmentTagUsecase.CreateEnvironmentTag(ctx, projectUid, currentUserUid, environmentTagName); err != nil { + return fmt.Errorf("create environment tag failed: %w", err) + } + + return nil +} + +func (d *DMSService) UpdateEnvironmentTag(ctx context.Context, projectUid, currentUserUid string, environmentTagUID, environmentTagName string) (err error) { + d.log.Infof("UpdateEnvironmentTag.req=%v", environmentTagName) + defer func() { + d.log.Infof("UpdateEnvironmentTag.req=%v;error=%v", environmentTagName, err) + }() + + if err := d.EnvironmentTagUsecase.UpdateEnvironmentTag(ctx, projectUid, currentUserUid, environmentTagUID, environmentTagName); err != nil { + return fmt.Errorf("update environment tag failed: %w", err) + } + return nil +} + +func (d *DMSService) DeleteEnvironmentTag(ctx context.Context, projectUid, currentUserUid string, environmentTagUID string) (err error) { + d.log.Infof("DeleteEnvironmentTag.req=%v", environmentTagUID) + defer func() { + d.log.Infof("DeleteEnvironmentTag.req=%v;error=%v", environmentTagUID, err) + }() + + // 环境标签被数据源关联时,不允许删除 + filterBy := []pkgConst.FilterCondition{ + { + Field: string(biz.DBServiceFieldEnvironmentTagUID), + Operator: pkgConst.FilterOperatorEqual, + Value: environmentTagUID, + }, + } + + _, total, err := d.DBServiceUsecase.ListDBService(ctx, &biz.ListDBServicesOption{FilterByOptions: pkgConst.ConditionsToFilterOptions(filterBy)}, projectUid, currentUserUid) + if err != nil { + return fmt.Errorf("list project failed: %w", err) + } + if total > 0 { + return fmt.Errorf("environment tag is used by db service, please detach environment tag with db service first") + } + + if err := d.EnvironmentTagUsecase.DeleteEnvironmentTag(ctx, projectUid, currentUserUid, environmentTagUID); err != nil { + return fmt.Errorf("delete environment tag failed: %w", err) + } + + return nil +} + +func (d *DMSService) ListEnvironmentTags(ctx context.Context, req *v1.ListEnvironmentTagReq) (reply *v1.ListEnvironmentTagsReply, err error) { + d.log.Infof("ListEnvironmentTags.req=%v", *req) + defer func() { + d.log.Infof("ListEnvironmentTags.req=%v;error=%v", *req, err) + }() + limit, offset := d.GetLimitAndOffset(req.PageIndex, req.PageSize) + bizEnvironmentTags, count, err := d.EnvironmentTagUsecase.ListEnvironmentTags(ctx, &biz.ListEnvironmentTagsOption{ + Limit: limit, + Offset: offset, + ProjectUID: req.ProjectUID, + }) + if err != nil { + return nil, fmt.Errorf("list environment tags failed: %w", err) + } + environmentTags := make([]*dmsCommonV1.EnvironmentTag, 0, len(bizEnvironmentTags)) + for _, bizEnvironmentTag := range bizEnvironmentTags { + environmentTags = append(environmentTags, &dmsCommonV1.EnvironmentTag{ + UID: bizEnvironmentTag.UID, + Name: bizEnvironmentTag.Name, + }) + } + return &v1.ListEnvironmentTagsReply{ + Data: environmentTags, + Total: count, + }, nil +} diff --git a/internal/dms/service/gateway_ce.go b/internal/dms/service/gateway_ce.go new file mode 100644 index 000000000..eb457af66 --- /dev/null +++ b/internal/dms/service/gateway_ce.go @@ -0,0 +1,40 @@ +//go:build !enterprise + +package service + +import ( + "context" + "errors" + + v1 "github.com/actiontech/dms/api/dms/service/v1" +) + +var errNotSupportGateways = errors.New("gateways related functions are enterprise version functions") + +func (d *DMSService) AddGateway(ctx context.Context, req *v1.Gateway) (err error) { + return errNotSupportGateways +} + +func (d *DMSService) DeleteGateway(ctx context.Context, req *v1.DeleteGatewayReq) (err error) { + return errNotSupportGateways +} + +func (d *DMSService) UpdateGateway(ctx context.Context, req *v1.UpdateGatewayReq) (err error) { + return errNotSupportGateways +} + +func (d *DMSService) SyncGateways(ctx context.Context, req *v1.SyncGatewayReq) (err error) { + return errNotSupportGateways +} + +func (d *DMSService) GetGateway(ctx context.Context, req *v1.GetGatewayReq) (reply *v1.GetGatewayReply, err error) { + return nil, errNotSupportGateways +} + +func (d *DMSService) GetGatewayTips(ctx context.Context) (reply *v1.GetGatewayTipsReply, err error) { + return nil, errNotSupportGateways +} + +func (d *DMSService) ListGateways(ctx context.Context, req *v1.ListGatewaysReq) (reply *v1.ListGatewaysReply, err error) { + return nil, errNotSupportGateways +} diff --git a/internal/dms/service/license.go b/internal/dms/service/license.go new file mode 100644 index 000000000..fc53e6e7e --- /dev/null +++ b/internal/dms/service/license.go @@ -0,0 +1,27 @@ +package service + +import ( + "context" + + v1 "github.com/actiontech/dms/api/dms/service/v1" +) + +func (d *DMSService) GetLicense(ctx context.Context) (*v1.GetLicenseReply, error) { + return d.LicenseUsecase.GetLicense(ctx) +} + +func (d *DMSService) GetLicenseInfo(ctx context.Context) ([]byte, error) { + return d.LicenseUsecase.GetLicenseInfo(ctx) +} + +func (d *DMSService) SetLicense(ctx context.Context, data string) error { + return d.LicenseUsecase.SetLicense(ctx, data) +} + +func (d *DMSService) CheckLicense(ctx context.Context, data string) (*v1.CheckLicenseReply, error) { + return d.LicenseUsecase.CheckLicense(ctx, data) +} + +func (d *DMSService) GetLicenseUsage(ctx context.Context) (*v1.GetLicenseUsageReply, error) { + return d.LicenseUsecase.GetLicenseUsage(ctx) +} diff --git a/internal/dms/service/member.go b/internal/dms/service/member.go index e3094beff..fd46b1f9e 100644 --- a/internal/dms/service/member.go +++ b/internal/dms/service/member.go @@ -3,6 +3,7 @@ package service import ( "context" "fmt" + "github.com/actiontech/dms/internal/pkg/locale" dmsV1 "github.com/actiontech/dms/api/dms/service/v1" "github.com/actiontech/dms/internal/dms/biz" @@ -12,6 +13,13 @@ import ( ) func (d *DMSService) AddMember(ctx context.Context, currentUserUid string, req *dmsV1.AddMemberReq) (reply *dmsV1.AddMemberReply, err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasManagePermission(ctx, currentUserUid, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return nil, fmt.Errorf("check user has permission manage member: %v", err) + } + if !hasPermission { + return nil, fmt.Errorf("no permission to add member") + } d.log.Infof("AddMembers.req=%v", req) defer func() { d.log.Infof("AddMembers.req=%v;reply=%v;error=%v", req, reply, err) @@ -30,25 +38,79 @@ func (d *DMSService) AddMember(ctx context.Context, currentUserUid string, req * }) } - uid, err := d.MemberUsecase.CreateMember(ctx, currentUserUid, req.Member.UserUid, req.Member.NamespaceUid, req.Member.IsNamespaceAdmin, roles) + uid, err := d.MemberUsecase.CreateMember(ctx, currentUserUid, req.Member.UserUid, req.ProjectUid, req.Member.IsProjectAdmin, roles, req.Member.ProjectManagePermissions) if err != nil { return nil, fmt.Errorf("create member failed: %w", err) } return &dmsV1.AddMemberReply{ - Payload: struct { + Data: struct { // member UID Uid string `json:"uid"` }{Uid: uid}, }, nil } -func (d *DMSService) ListMembers(ctx context.Context, req *dmsV1.ListMemberReq) (reply *dmsV1.ListMemberReply, err error) { - d.log.Infof("ListMembers.req=%v", req) - defer func() { - d.log.Infof("ListMembers.req=%v;reply=%v;error=%v", req, reply, err) - }() +func (d *DMSService) ListMemberTips(ctx context.Context, projectId string) (reply *dmsV1.ListMemberTipsReply, err error) { + members, err := d.OpPermissionVerifyUsecase.ListUsersInProject(ctx, projectId) + if nil != err { + return nil, err + } + + ret := make([]dmsV1.ListMemberTipsItem, len(members)) + for i, m := range members { + + ret[i] = dmsV1.ListMemberTipsItem{ + UserId: m.UserUid, + UserName: m.UserName, + } + } + + return &dmsV1.ListMemberTipsReply{ + Data: ret, + }, nil +} +func (d *DMSService) ListMemberGroupTips(ctx context.Context, projectId string) (reply *dmsV1.ListMemberGroupTipsReply, err error) { + orderBy := biz.MemberGroupFieldName + listOption := &biz.ListMemberGroupsOption{ + PageNumber: 1, + LimitPerPage: 9999, + OrderBy: orderBy, + FilterByOptions: pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd, + pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(biz.MemberGroupFieldProjectUID), + Operator: pkgConst.FilterOperatorEqual, + Value: projectId, + }, + ), + ), + } + memberGroups, _, err := d.MemberGroupUsecase.ListMemberGroups(ctx, listOption, projectId) + if nil != err { + return nil, err + } + ret := make([]dmsV1.UidWithName, len(memberGroups)) + for i, memberGroup := range memberGroups { + ret[i] = dmsV1.UidWithName{ + Uid: memberGroup.UID, + Name: memberGroup.Name, + } + } + return &dmsV1.ListMemberGroupTipsReply{ + Data: ret, + }, nil +} + +func (d *DMSService) ListMembers(ctx context.Context, req *dmsV1.ListMemberReq, currentUserId string) (reply *dmsV1.ListMemberReply, err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasViewPermission(ctx, currentUserId, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return nil, err + } + if !hasPermission { + return nil, fmt.Errorf("no permission to view project members") + } var orderBy biz.MemberField switch req.OrderBy { case dmsV1.MemberOrderByUserUid: @@ -57,30 +119,36 @@ func (d *DMSService) ListMembers(ctx context.Context, req *dmsV1.ListMemberReq) orderBy = biz.MemberFieldUserUID } - filterBy := make([]pkgConst.FilterCondition, 0) + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) if req.FilterByUserUid != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.MemberFieldUserUID), - Operator: pkgConst.FilterOperatorContains, + Operator: pkgConst.FilterOperatorEqual, Value: req.FilterByUserUid, }) } - if req.NamespaceUid != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ - Field: string(biz.MemberFieldNamespaceUID), + if req.ProjectUid != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.MemberFieldProjectUID), Operator: pkgConst.FilterOperatorEqual, - Value: req.NamespaceUid, + Value: req.ProjectUid, }) } + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + listOption := &biz.ListMembersOption{ - PageNumber: req.PageIndex, - LimitPerPage: req.PageSize, - OrderBy: orderBy, - FilterBy: filterBy, + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, } - members, total, err := d.MemberUsecase.ListMember(ctx, listOption, req.NamespaceUid) + members, total, err := d.MemberUsecase.ListMember(ctx, listOption, req.ProjectUid) if nil != err { return nil, err } @@ -91,72 +159,173 @@ func (d *DMSService) ListMembers(ctx context.Context, req *dmsV1.ListMemberReq) if err != nil { return nil, fmt.Errorf("get user failed: %v", err) } + isGroupMember := false + memberGroups, err := d.MemberGroupUsecase.GetMemberGroupsByUserIDAndProjectID(ctx, m.UserUID, req.ProjectUid) + if err != nil { + return nil, fmt.Errorf("get member groups failed: %v", err) + } + if len(memberGroups) > 0 { + isGroupMember = true + } + + roleWithOpRanges, err := d.buildRoleWithOpRanges(ctx, m.RoleWithOpRanges, nil) + if err != nil { + return nil, err + } + projectManagePermissions := make([]dmsV1.ProjectManagePermission, 0, len(m.OpPermissions)) + projectManagePermissionMap := make(map[string]struct{}, len(m.OpPermissions)) + memberGroupRoleWithOpRanges := make([]dmsV1.ListMemberRoleWithOpRange, 0) + // 转换所有用户组的RoleWithOpRanges + for _, memberGroup := range memberGroups { + memberRoleWithOpRanges, err := d.buildRoleWithOpRanges(ctx, memberGroup.RoleWithOpRanges, memberGroup) + if err != nil { + return nil, err + } + memberGroupRoleWithOpRanges = append(memberGroupRoleWithOpRanges, memberRoleWithOpRanges...) + for _, permission := range memberGroup.OpPermissions { + projectManagePermissions = append(projectManagePermissions, dmsV1.ProjectManagePermission{ + Uid: permission.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[permission.GetUID()]), + MemberGroup: memberGroup.Name, + }) + projectManagePermissionMap[permission.GetUID()] = struct{}{} + } + } + + projectOpPermissions := d.aggregateRoleByDataSource(roleWithOpRanges, memberGroupRoleWithOpRanges) + for _, permission := range m.OpPermissions { + // 如果成员组中已经有了项目权限那么就跳过,避免权限重复展示 + if _, exist := projectManagePermissionMap[permission.GetUID()]; exist { + continue + } + projectManagePermissions = append(projectManagePermissions, dmsV1.ProjectManagePermission{ + Uid: permission.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[permission.GetUID()]), + }) + } ret[i] = &dmsV1.ListMember{ - MemberUid: m.GetUID(), - User: dmsV1.UidWithName{Uid: user.GetUID(), Name: user.Name}, + MemberUid: m.GetUID(), + User: dmsV1.UidWithName{Uid: user.GetUID(), Name: user.Name}, + RoleWithOpRanges: roleWithOpRanges, + Projects: m.Projects, + IsGroupMember: isGroupMember, + CurrentProjectOpPermissions: projectOpPermissions, + CurrentProjectAdmin: d.buildMemberCurrentProjectAdmin(m, memberGroups), + CurrentProjectManagePermissions: projectManagePermissions, } - // 遍历成员的角色&权限范围用于展示 for _, r := range m.RoleWithOpRanges { - // 获取角色 - role, err := d.RoleUsecase.GetRole(ctx, r.RoleUID) - if err != nil { - return nil, fmt.Errorf("get role failed: %v", err) + if r.RoleUID == pkgConst.UIDOfRoleProjectAdmin { + ret[i].IsProjectAdmin = true } + } - isAdmin, err := d.MemberUsecase.IsMemberNamespaceAdmin(ctx, m.GetUID()) - if err != nil { - return nil, fmt.Errorf("check member is namespace admin failed: %v", err) + // 获取用户的权限 + ops, err := d.UserUsecase.GetUserOpPermissions(ctx, m.UserUID) + if err != nil { + return nil, err + } + for _, op := range ops { + if op.RangeType == biz.OpRangeTypeGlobal { + ret[i].PlatformRoles = append(ret[i].PlatformRoles, dmsV1.UidWithName{ + Uid: op.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[op.GetUID()]), + }) } + } + } + return &dmsV1.ListMemberReply{ + Data: ret, + Total: total, + }, + nil +} + +func (d *DMSService) buildMemberCurrentProjectAdmin(member *biz.Member, memberGroups []*biz.MemberGroup) dmsV1.CurrentProjectAdmin { + isProjectAdmin := false + for _, r := range member.RoleWithOpRanges { + if r.RoleUID == pkgConst.UIDOfRoleProjectAdmin { + isProjectAdmin = true + } + } + memberGroupNames := make([]string, 0, len(memberGroups)) + for _, group := range memberGroups { + memberGroupNames = append(memberGroupNames, group.Name) + for _, r := range group.RoleWithOpRanges { + if r.RoleUID == pkgConst.UIDOfRoleProjectAdmin { + isProjectAdmin = true + } + } + } + return dmsV1.CurrentProjectAdmin{ + IsAdmin: isProjectAdmin, + MemberGroups: memberGroupNames, + } +} - // 如果是空间管理员namespace admin,则表示拥有该空间的所有权限 - if isAdmin { - ret[i].IsNamespaceAdmin = true +func (d *DMSService) aggregateRoleByDataSource(roleWithOpRanges []dmsV1.ListMemberRoleWithOpRange, memberGroupRoleWithOpRanges []dmsV1.ListMemberRoleWithOpRange) []dmsV1.ProjectOpPermission { + dataSourceRolesMap := make(map[string][]dmsV1.ProjectRole) + for _, role := range roleWithOpRanges { + for _, dataSource := range role.RangeUIDs { + projectRole := dmsV1.ProjectRole{ + Uid: role.RoleUID.Uid, + Name: role.RoleUID.Name, + OpPermissions: role.OpPermissions, + } + if _, exists := dataSourceRolesMap[dataSource.Name]; exists { + dataSourceRolesMap[dataSource.Name] = append(dataSourceRolesMap[dataSource.Name], projectRole) + } else { + dataSourceRolesMap[dataSource.Name] = []dmsV1.ProjectRole{projectRole} + } + } + } - // 如果不是空间管理员namespace admin,则展示具体的权限范围 + for _, groupRole := range memberGroupRoleWithOpRanges { + projectRole := dmsV1.ProjectRole{ + Uid: groupRole.RoleUID.Uid, + Name: groupRole.RoleUID.Name, + OpPermissions: groupRole.OpPermissions, + MemberGroup: groupRole.MemberGroup, + } + for _, dataSource := range groupRole.RangeUIDs { + if _, exists := dataSourceRolesMap[dataSource.Name]; exists { + dataSourceRolesMap[dataSource.Name] = append(dataSourceRolesMap[dataSource.Name], projectRole) } else { - // 获取权限范围类型 - opRangeTyp, err := dmsV1.ParseOpRangeType(r.OpRangeType.String()) - if err != nil { - return nil, fmt.Errorf("parse op range type failed: %v", err) - } - - // 获取权限范围 - rangeUidWithNames := []dmsV1.UidWithName{} - for _, uid := range r.RangeUIDs { - switch r.OpRangeType { - case biz.OpRangeTypeDBService: - dbService, err := d.DBServiceUsecase.GetDBService(ctx, uid) - if err != nil { - return nil, fmt.Errorf("get db service failed: %v", err) - } - rangeUidWithNames = append(rangeUidWithNames, dmsV1.UidWithName{Uid: dbService.GetUID(), Name: dbService.Name}) - // 成员目前只支持配置数据源范围的权限 - case biz.OpRangeTypeNamespace, biz.OpRangeTypeGlobal: - return nil, fmt.Errorf("member currently only support the db service op range type, but got type: %v", r.OpRangeType) - default: - return nil, fmt.Errorf("unsupported op range type: %v", r.OpRangeType) - } - } - - ret[i].RoleWithOpRanges = append(ret[i].RoleWithOpRanges, dmsV1.ListMemberRoleWithOpRange{ - RoleUID: dmsV1.UidWithName{Uid: role.GetUID(), Name: role.Name}, - OpRangeType: opRangeTyp, - RangeUIDs: rangeUidWithNames, - }) + dataSourceRolesMap[dataSource.Name] = []dmsV1.ProjectRole{projectRole} } } } + projectOpPermissions := make([]dmsV1.ProjectOpPermission, 0, len(dataSourceRolesMap)) + for dataSource, roles := range dataSourceRolesMap { + projectOpPermissions = append(projectOpPermissions, dmsV1.ProjectOpPermission{DataSource: dataSource, Roles: roles}) + } + return projectOpPermissions +} - return &dmsV1.ListMemberReply{ - Payload: struct { - Members []*dmsV1.ListMember `json:"members"` - Total int64 `json:"total"` - }{Members: ret, Total: total}, - }, nil +func convert2ProjectMemberGroup(memberGroup *biz.MemberGroup, memberGroupOpPermissions []dmsV1.UidWithName) *dmsV1.ProjectMemberGroup { + if memberGroup == nil { + return nil + } + users := make([]dmsV1.UidWithName, 0, len(memberGroup.Users)) + for _, user := range memberGroup.Users { + users = append(users, dmsV1.UidWithName{Uid: user.Uid, Name: user.Name}) + } + return &dmsV1.ProjectMemberGroup{ + Uid: memberGroup.UID, + Name: memberGroup.Name, + Users: users, + OpPermissions: memberGroupOpPermissions, + } } func (d *DMSService) UpdateMember(ctx context.Context, currentUserUid string, req *dmsV1.UpdateMemberReq) (err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasManagePermission(ctx, currentUserUid, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return fmt.Errorf("check user has permission manage member: %v", err) + } + if !hasPermission { + return fmt.Errorf("no permission to add member") + } d.log.Infof("UpdateMember.req=%v", req) defer func() { d.log.Infof("UpdateMember.req=%v;error=%v", req, err) @@ -176,8 +345,8 @@ func (d *DMSService) UpdateMember(ctx context.Context, currentUserUid string, re }) } - if err = d.MemberUsecase.UpdateMember(ctx, currentUserUid, req.MemberUid, pkgConst.UIDOfNamespaceDefault, /*暂时只支持默认namespace*/ - req.Member.IsNamespaceAdmin, roles); nil != err { + if err = d.MemberUsecase.UpdateMember(ctx, currentUserUid, req.MemberUid, pkgConst.UIDOfProjectDefault, /*暂时只支持默认project*/ + req.Member.IsProjectAdmin, roles, req.Member.ProjectManagePermissions); nil != err { return fmt.Errorf("update member failed: %v", err) } @@ -185,6 +354,13 @@ func (d *DMSService) UpdateMember(ctx context.Context, currentUserUid string, re } func (d *DMSService) DelMember(ctx context.Context, currentUserUid string, req *dmsV1.DelMemberReq) (err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasManagePermission(ctx, currentUserUid, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return fmt.Errorf("check user has permission manage member: %v", err) + } + if !hasPermission { + return fmt.Errorf("no permission to add member") + } d.log.Infof("DelMember.req=%v", req) defer func() { d.log.Infof("DelMember.req=%v;error=%v", req, err) @@ -198,17 +374,12 @@ func (d *DMSService) DelMember(ctx context.Context, currentUserUid string, req * } func (d *DMSService) ListMembersForInternal(ctx context.Context, req *dmsCommonV1.ListMembersForInternalReq) (reply *dmsCommonV1.ListMembersForInternalReply, err error) { - d.log.Infof("ListMembersForInternal.req=%v", req) - defer func() { - d.log.Infof("ListMembersForInternal.req=%v;reply=%v;error=%v", req, reply, err) - }() - listOption := &biz.ListMembersOpPermissionOption{ PageNumber: req.PageIndex, LimitPerPage: req.PageSize, } - members, total, err := d.OpPermissionVerifyUsecase.ListMembersOpPermissionInNamespace(ctx, req.NamespaceUid, listOption) + members, total, err := d.OpPermissionVerifyUsecase.ListUsersOpPermissionInProject(ctx, req.ProjectUid, listOption) if nil != err { return nil, err } @@ -244,13 +415,12 @@ func (d *DMSService) ListMembersForInternal(ctx context.Context, req *dmsCommonV }) } - isAdmin, err := d.OpPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, m.UserUid, req.NamespaceUid) + isAdmin, err := d.OpPermissionVerifyUsecase.IsUserProjectAdmin(ctx, m.UserUid, req.ProjectUid) if err != nil { - return nil, fmt.Errorf("check user namespace admin error: %v", err) + return nil, fmt.Errorf("check user project admin error: %v", err) } ret[i] = &dmsCommonV1.ListMembersForInternalItem{ - MemberUid: m.MemberUid, User: dmsCommonV1.UidWithName{Uid: m.UserUid, Name: m.UserName}, IsAdmin: isAdmin, MemberOpPermissionList: opPermission, @@ -258,9 +428,6 @@ func (d *DMSService) ListMembersForInternal(ctx context.Context, req *dmsCommonV } return &dmsCommonV1.ListMembersForInternalReply{ - Payload: struct { - Members []*dmsCommonV1.ListMembersForInternalItem `json:"members"` - Total int64 `json:"total"` - }{Members: ret, Total: total}, + Data: ret, Total: total, }, nil } diff --git a/internal/dms/service/member_group.go b/internal/dms/service/member_group.go new file mode 100644 index 000000000..d7d632198 --- /dev/null +++ b/internal/dms/service/member_group.go @@ -0,0 +1,332 @@ +package service + +import ( + "context" + "fmt" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/pkg/locale" +) + +func (d *DMSService) ListMemberGroups(ctx context.Context, req *dmsV1.ListMemberGroupsReq, currentUserId string) (reply *dmsV1.ListMemberGroupsReply, err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasViewPermission(ctx, currentUserId, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return nil, fmt.Errorf("check user has permission manage member: %v", err) + } + + if !hasPermission { + return nil, fmt.Errorf("user is not admin or manage member permission") + } + var orderBy biz.MemberGroupField + switch req.OrderBy { + case dmsV1.MemberGroupOrderByName: + orderBy = biz.MemberGroupFieldName + default: + orderBy = biz.MemberGroupFieldName + } + + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) + if req.FilterByName != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.MemberGroupFieldName), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterByName, + }) + } + if req.ProjectUid != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.MemberGroupFieldProjectUID), + Operator: pkgConst.FilterOperatorEqual, + Value: req.ProjectUid, + }) + } + + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + + listOption := &biz.ListMemberGroupsOption{ + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, + } + + memberGroups, total, err := d.MemberGroupUsecase.ListMemberGroups(ctx, listOption, req.ProjectUid) + if nil != err { + return nil, err + } + + ret := make([]*dmsV1.ListMemberGroup, 0, len(memberGroups)) + for _, memberGroup := range memberGroups { + isAdmin, err := d.MemberGroupUsecase.IsMemberGroupProjectAdmin(ctx, memberGroup.UID) + if err != nil { + return nil, fmt.Errorf("check member group is project admin failed: %v", err) + } + + users := make([]dmsV1.UidWithName, 0, len(memberGroup.Users)) + for _, user := range memberGroup.Users { + users = append(users, dmsV1.UidWithName{ + Uid: user.Uid, + Name: user.Name, + }) + } + + roleWithOpRanges, err := d.buildRoleWithOpRanges(ctx, memberGroup.RoleWithOpRanges, memberGroup) + if err != nil { + return nil, err + } + + projectOpPermissions := d.aggregateRoleByDataSource(nil, roleWithOpRanges) + + projectManagePermissions := make([]dmsV1.UidWithName, 0,len(memberGroup.OpPermissions)) + for _, permission := range memberGroup.OpPermissions { + projectManagePermissions = append(projectManagePermissions, dmsV1.UidWithName{ + Uid: permission.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[permission.GetUID()]), + }) + } + + item := &dmsV1.ListMemberGroup{ + Name: memberGroup.Name, + Uid: memberGroup.UID, + IsProjectAdmin: isAdmin, + Users: users, + RoleWithOpRanges: roleWithOpRanges, + CurrentProjectOpPermissions: projectOpPermissions, + CurrentProjectManagePermissions: projectManagePermissions, + } + + ret = append(ret, item) + } + + return &dmsV1.ListMemberGroupsReply{ + Data: ret, + Total: total, + }, nil +} + +func (d *DMSService) buildRoleWithOpRanges(ctx context.Context, roleWithOpRanges []biz.MemberRoleWithOpRange, memberGroup *biz.MemberGroup) ([]dmsV1.ListMemberRoleWithOpRange, error) { + ret := make([]dmsV1.ListMemberRoleWithOpRange, 0, len(roleWithOpRanges)) + + // 遍历成员的角色&权限范围用于展示 + for _, r := range roleWithOpRanges { + if r.RoleUID == pkgConst.UIDOfRoleProjectAdmin { + continue + } + + // 获取角色 + role, err := d.RoleUsecase.GetRole(ctx, r.RoleUID) + if err != nil { + return nil, fmt.Errorf("get role failed: %v", err) + } + + // 获取权限范围类型 + opRangeTyp, err := dmsV1.ParseOpRangeType(r.OpRangeType.String()) + if err != nil { + return nil, fmt.Errorf("parse op range type failed: %v", err) + } + + // 获取权限范围 + rangeUidWithNames := make([]dmsV1.UidWithName, 0) + for _, uid := range r.RangeUIDs { + switch r.OpRangeType { + case biz.OpRangeTypeDBService: + if uid != "" { + dbService, err := d.DBServiceUsecase.GetDBService(ctx, uid) + if err != nil { + return nil, fmt.Errorf("get db service failed: %v", err) + } + rangeUidWithNames = append(rangeUidWithNames, dmsV1.UidWithName{Uid: dbService.GetUID(), Name: dbService.Name}) + } + // 成员目前只支持配置数据源范围的权限 + case biz.OpRangeTypeProject, biz.OpRangeTypeGlobal: + //return nil, fmt.Errorf("member currently only support the db service op range type, but got type: %v", r.OpRangeType) + default: + return nil, fmt.Errorf("unsupported op range type: %v", r.OpRangeType) + } + } + if role.UID == pkgConst.UIDOfRoleProjectAdmin || role.UID == pkgConst.UIDOfRoleDevEngineer || role.UID == pkgConst.UIDOfRoleDevManager || role.UID == pkgConst.UIDOfRoleOpsEngineer { + // built in role, localize name and desc + role.Name = locale.Bundle.LocalizeMsgByCtx(ctx, RoleNameByUID[role.GetUID()]) + role.Desc = locale.Bundle.LocalizeMsgByCtx(ctx, RoleDescByUID[role.GetUID()]) + } + opPermissions := make([]dmsV1.UidWithName, 0) + for _, permission := range role.OpPermissions { + opPermissions = append(opPermissions, dmsV1.UidWithName{ + Uid: permission.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[permission.GetUID()]), + }) + } + memberGroupOpPermissions := make([]dmsV1.UidWithName, 0) + if memberGroup != nil { + for _, roleOpRange := range memberGroup.RoleWithOpRanges { + // 获取角色 + memberRole, err := d.RoleUsecase.GetRole(ctx, roleOpRange.RoleUID) + if err != nil { + return nil, fmt.Errorf("get role failed: %v", err) + } + for _, permission := range memberRole.OpPermissions { + memberGroupOpPermissions = append(memberGroupOpPermissions, dmsV1.UidWithName{ + Uid: permission.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[permission.GetUID()]), + }) + } + } + } + ret = append(ret, dmsV1.ListMemberRoleWithOpRange{ + RoleUID: dmsV1.UidWithName{Uid: role.GetUID(), Name: role.Name}, + OpRangeType: opRangeTyp, + RangeUIDs: rangeUidWithNames, + OpPermissions: opPermissions, + MemberGroup: convert2ProjectMemberGroup(memberGroup, memberGroupOpPermissions), + }) + } + + return ret, nil +} + +func (d *DMSService) GetMemberGroup(ctx context.Context, req *dmsV1.GetMemberGroupReq) (reply *dmsV1.GetMemberGroupReply, err error) { + memberGroup, err := d.MemberGroupUsecase.GetMemberGroup(ctx, req.MemberGroupUid, req.ProjectUid) + if err != nil { + return nil, err + } + + isAdmin, err := d.MemberGroupUsecase.IsMemberGroupProjectAdmin(ctx, memberGroup.UID) + if err != nil { + return nil, fmt.Errorf("check member group is project admin failed: %v", err) + } + + users := make([]dmsV1.UidWithName, 0, len(memberGroup.Users)) + for _, user := range memberGroup.Users { + users = append(users, dmsV1.UidWithName{ + Uid: user.Uid, + Name: user.Name, + }) + } + + roleWithOpRanges, err := d.buildRoleWithOpRanges(ctx, memberGroup.RoleWithOpRanges, memberGroup) + if err != nil { + return nil, err + } + + ret := &dmsV1.GetMemberGroup{ + Name: memberGroup.Name, + Uid: memberGroup.UID, + IsProjectAdmin: isAdmin, + Users: users, + RoleWithOpRanges: roleWithOpRanges, + } + + if err != nil { + return nil, err + } + + return &dmsV1.GetMemberGroupReply{ + Data: ret, + }, nil +} + +func (d *DMSService) AddMemberGroup(ctx context.Context, currentUserUid string, req *dmsV1.AddMemberGroupReq) (reply *dmsV1.AddMemberReply, err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasViewPermission(ctx, currentUserUid, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return nil, fmt.Errorf("check user has permission manage member: %v", err) + } + + if !hasPermission { + return nil, fmt.Errorf("user is not admin or manage member permission") + } + roles := make([]biz.MemberRoleWithOpRange, 0, len(req.MemberGroup.RoleWithOpRanges)) + for _, p := range req.MemberGroup.RoleWithOpRanges { + typ, err := biz.ParseOpRangeType(string(p.OpRangeType)) + if err != nil { + return nil, fmt.Errorf("parse op range type failed: %v", err) + } + roles = append(roles, biz.MemberRoleWithOpRange{ + RoleUID: p.RoleUID, + OpRangeType: typ, + RangeUIDs: p.RangeUIDs, + }) + } + + params := &biz.MemberGroup{ + IsProjectAdmin: req.MemberGroup.IsProjectAdmin, + Name: req.MemberGroup.Name, + ProjectUID: req.ProjectUid, + UserUids: req.MemberGroup.UserUids, + RoleWithOpRanges: roles, + ProjectManagePermissions: req.MemberGroup.ProjectManagePermissions, + } + + uid, err := d.MemberGroupUsecase.CreateMemberGroup(ctx, currentUserUid, params) + if err != nil { + return nil, fmt.Errorf("create member group failed: %w", err) + } + + return &dmsV1.AddMemberReply{ + Data: struct { + // member UID + Uid string `json:"uid"` + }{Uid: uid}, + }, nil +} + +func (d *DMSService) UpdateMemberGroup(ctx context.Context, currentUserUid string, req *dmsV1.UpdateMemberGroupReq) (err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasViewPermission(ctx, currentUserUid, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return fmt.Errorf("check user has permission manage member: %v", err) + } + + if !hasPermission { + return fmt.Errorf("user is not admin or manage member permission") + } + roles := make([]biz.MemberRoleWithOpRange, 0, len(req.MemberGroup.RoleWithOpRanges)) + for _, r := range req.MemberGroup.RoleWithOpRanges { + + typ, err := biz.ParseOpRangeType(string(r.OpRangeType)) + if err != nil { + return fmt.Errorf("parse op range type failed: %v", err) + } + roles = append(roles, biz.MemberRoleWithOpRange{ + RoleUID: r.RoleUID, + OpRangeType: typ, + RangeUIDs: r.RangeUIDs, + }) + } + + params := &biz.MemberGroup{ + UID: req.MemberGroupUid, + IsProjectAdmin: req.MemberGroup.IsProjectAdmin, + ProjectUID: req.ProjectUid, + UserUids: req.MemberGroup.UserUids, + RoleWithOpRanges: roles, + ProjectManagePermissions: req.MemberGroup.ProjectManagePermissions, + } + + err = d.MemberGroupUsecase.UpdateMemberGroup(ctx, currentUserUid, params) + if err != nil { + return fmt.Errorf("update member group failed: %w", err) + } + + return nil +} + +func (d *DMSService) DeleteMemberGroup(ctx context.Context, currentUserUid string, req *dmsV1.DeleteMemberGroupReq) (err error) { + hasPermission, err := d.OpPermissionVerifyUsecase.HasViewPermission(ctx, currentUserUid, req.ProjectUid, pkgConst.UIdOfOpPermissionManageMember) + if err != nil { + return fmt.Errorf("check user has permission manage member: %v", err) + } + + if !hasPermission { + return fmt.Errorf("user is not admin or manage member permission") + } + if err = d.MemberGroupUsecase.DeleteMemberGroup(ctx, currentUserUid, req.MemberGroupUid, req.ProjectUid); err != nil { + return fmt.Errorf("delete member group failed: %v", err) + } + + return nil +} diff --git a/internal/dms/service/namespace.go b/internal/dms/service/namespace.go deleted file mode 100644 index 95ef86338..000000000 --- a/internal/dms/service/namespace.go +++ /dev/null @@ -1,185 +0,0 @@ -package service - -import ( - "context" - "errors" - "fmt" - - dmsV1 "github.com/actiontech/dms/api/dms/service/v1" - "github.com/actiontech/dms/internal/dms/biz" - pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" - pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" - - dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - - "github.com/go-openapi/strfmt" -) - -func (d *DMSService) ListNamespaces(ctx context.Context, req *dmsCommonV1.ListNamespaceReq, currentUserUid string) (reply *dmsCommonV1.ListNamespaceReply, err error) { - d.log.Infof("ListNamespaces.req=%v", req) - defer func() { - d.log.Infof("ListNamespaces.req=%v;reply=%v;error=%v", req, reply, err) - }() - - var orderBy biz.NamespaceField - switch req.OrderBy { - case dmsCommonV1.NamespaceOrderByName: - orderBy = biz.NamespaceFieldName - default: - orderBy = biz.NamespaceFieldName - } - - filterBy := make([]pkgConst.FilterCondition, 0) - if req.FilterByName != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ - Field: string(biz.NamespaceFieldName), - Operator: pkgConst.FilterOperatorEqual, - Value: req.FilterByName, - }) - } - if req.FilterByUID != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ - Field: string(biz.NamespaceFieldUID), - Operator: pkgConst.FilterOperatorEqual, - Value: req.FilterByUID, - }) - } - - listOption := &biz.ListNamespacesOption{ - PageNumber: req.PageIndex, - LimitPerPage: req.PageSize, - OrderBy: orderBy, - FilterBy: filterBy, - } - - namespaces, total, err := d.NamespaceUsecase.ListNamespace(ctx, listOption, currentUserUid) - if nil != err { - return nil, err - } - - ret := make([]*dmsCommonV1.ListNamespace, len(namespaces)) - for i, n := range namespaces { - ret[i] = &dmsCommonV1.ListNamespace{ - NamespaceUid: n.UID, - Name: n.Name, - Archived: (n.Status == biz.NamespaceStatusArchived), - Desc: n.Desc, - CreateTime: strfmt.DateTime(n.CreateTime), - } - user, err := d.UserUsecase.GetUser(ctx, n.CreateUserUID) - if err != nil { - d.log.Errorf("get user error: %v", err) - continue - } - ret[i].CreateUser = dmsCommonV1.UidWithName{ - Uid: n.UID, - Name: user.Name, - } - - } - - return &dmsCommonV1.ListNamespaceReply{ - Payload: struct { - Namespaces []*dmsCommonV1.ListNamespace `json:"namespaces"` - Total int64 `json:"total"` - }{Namespaces: ret, Total: total}, - }, nil -} - -func (d *DMSService) AddNamespace(ctx context.Context, currentUserUid string, req *dmsV1.AddNamespaceReq) (reply *dmsV1.AddNamespaceReply, err error) { - d.log.Infof("AddNamespaces.req=%v", req) - defer func() { - d.log.Infof("AddNamespaces.req=%v;reply=%v;error=%v", req, reply, err) - }() - - // check - { - // check current user has enough permission - if canCreateNamespace, err := d.OpPermissionVerifyUsecase.CanCreateNamespace(ctx, currentUserUid); err != nil { - return nil, err - } else if !canCreateNamespace { - return nil, fmt.Errorf("current user can't create namespace") - } - - // check namespace is exist - _, err := d.NamespaceUsecase.GetNamespaceByName(ctx, req.Namespace.Name) - if err == nil { - return nil, fmt.Errorf("namespace %v is exist", req.Namespace.Name) - } - if !errors.Is(err, pkgErr.ErrStorageNoData) { - return nil, fmt.Errorf("failed to get namespace by name: %w", err) - } - } - - namespace, err := biz.NewNamespace(currentUserUid, req.Namespace.Name, req.Namespace.Desc) - if err != nil { - return nil, err - } - err = d.NamespaceUsecase.CreateNamespace(ctx, namespace, currentUserUid) - if err != nil { - return nil, fmt.Errorf("create namespace failed: %w", err) - } - - return &dmsV1.AddNamespaceReply{ - Payload: struct { - // namespace UID - Uid string `json:"uid"` - }{Uid: namespace.UID}, - }, nil -} - -func (d *DMSService) DeleteNamespace(ctx context.Context, currentUserUid string, req *dmsV1.DelNamespaceReq) (err error) { - d.log.Infof("DeleteNamespace.req=%v", req) - defer func() { - d.log.Infof("DeleteNamespace.req=%v;error=%v", req, err) - }() - - err = d.NamespaceUsecase.DeleteNamespace(ctx, currentUserUid, req.NamespaceUid) - if err != nil { - return fmt.Errorf("delete namespace failed: %w", err) - } - - return nil -} - -func (d *DMSService) UpdateNamespaceDesc(ctx context.Context, currentUserUid string, req *dmsV1.UpdateNamespaceReq) (err error) { - d.log.Infof("UpdateNamespaceDesc.req=%v", req) - defer func() { - d.log.Infof("UpdateNamespaceDesc.req=%v;error=%v", req, err) - }() - - err = d.NamespaceUsecase.UpdateNamespaceDesc(ctx, currentUserUid, req.NamespaceUid, req.Namespace.Desc) - if err != nil { - return fmt.Errorf("update namespace failed: %w", err) - } - - return nil -} - -func (d *DMSService) ArchivedNamespace(ctx context.Context, currentUserUid string, req *dmsV1.ArchiveNamespaceReq) (err error) { - d.log.Infof("ArchivedNamespace.req=%v", req) - defer func() { - d.log.Infof("ArchivedNamespace.req=%v;error=%v", req, err) - }() - - err = d.NamespaceUsecase.ArchivedNamespace(ctx, currentUserUid, req.NamespaceUid, true) - if err != nil { - return fmt.Errorf("archived namespace failed: %w", err) - } - - return nil -} - -func (d *DMSService) UnarchiveNamespace(ctx context.Context, currentUserUid string, req *dmsV1.UnarchiveNamespaceReq) (err error) { - d.log.Infof("UnarchiveNamespace.req=%v", req) - defer func() { - d.log.Infof("UnarchiveNamespace.req=%v;error=%v", req, err) - }() - - err = d.NamespaceUsecase.ArchivedNamespace(ctx, currentUserUid, req.NamespaceUid, false) - if err != nil { - return fmt.Errorf("unarchive namespace failed: %w", err) - } - - return nil -} diff --git a/internal/dms/service/op_permission.go b/internal/dms/service/op_permission.go index 0c49780b9..755c178ef 100644 --- a/internal/dms/service/op_permission.go +++ b/internal/dms/service/op_permission.go @@ -4,15 +4,96 @@ import ( "context" "fmt" + "github.com/actiontech/dms/internal/apiserver/conf" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/pkg/locale" + "github.com/nicksnyder/go-i18n/v2/i18n" + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" "github.com/actiontech/dms/internal/dms/biz" ) +var OpPermissionNameByUID = map[string]*i18n.Message{ + pkgConst.UIDOfOpPermissionCreateProject: locale.NameOpPermissionCreateProject, + pkgConst.UIDOfOpPermissionProjectAdmin: locale.NameOpPermissionProjectAdmin, + pkgConst.UIDOfOpPermissionCreateWorkflow: locale.NameOpPermissionCreateWorkflow, + pkgConst.UIDOfOpPermissionAuditWorkflow: locale.NameOpPermissionAuditWorkflow, + pkgConst.UIDOfOpPermissionAuthDBServiceData: locale.NameOpPermissionAuthDBServiceData, + pkgConst.UIDOfOpPermissionExecuteWorkflow: locale.NameOpPermissionExecuteWorkflow, + pkgConst.UIDOfOpPermissionViewOthersWorkflow: locale.NameOpPermissionViewOthersWorkflow, + pkgConst.UIDOfOpPermissionSaveAuditPlan: locale.NameOpPermissionSaveAuditPlan, + pkgConst.UIDOfOpPermissionViewOthersAuditPlan: locale.NameOpPermissionViewOthersAuditPlan, + pkgConst.UIDOfOpPermissionViewSQLInsight: locale.NameOpPermissionViewSQLInsight, + pkgConst.UIDOfOpPermissionSQLQuery: locale.NameOpPermissionSQLQuery, + pkgConst.UIDOfOpPermissionExportApprovalReject: locale.NameOpPermissionExportApprovalReject, + pkgConst.UIDOfOpPermissionExportCreate: locale.NameOpPermissionExportCreate, + pkgConst.UIDOfOpPermissionCreateOptimization: locale.NameOpPermissionCreateOptimization, + pkgConst.UIDOfOpPermissionViewOthersOptimization: locale.NameOpPermissionViewOthersOptimization, + pkgConst.UIDOfOpPermissionGlobalManagement: locale.NameOpPermissionGlobalManagement, + pkgConst.UIDOfOpPermissionGlobalView: locale.NameOpPermissionGlobalView, + pkgConst.UIDOfOpPermissionCreatePipeline: locale.NameOpPermissionCreatePipeline, + pkgConst.UIDOfOrdinaryUser: locale.NameOpPermissionOrdinaryUser, + pkgConst.UIDOfOpPermissionViewOperationRecord: locale.NameOpPermissionViewOperationRecord, + pkgConst.UIDOfOpPermissionViewExportTask: locale.NameOpPermissionViewExportTask, + pkgConst.UIDOfPermissionViewQuickAuditRecord: locale.NamePermissionViewQuickAuditRecord, + pkgConst.UIDOfOpPermissionViewIDEAuditRecord: locale.NameOpPermissionViewIDEAuditRecord, + pkgConst.UIDOfOpPermissionViewOptimizationRecord: locale.NameOpPermissionViewOptimizationRecord, + pkgConst.UIDOfOpPermissionViewVersionManage: locale.NameOpPermissionViewVersionManage, + pkgConst.UIDOfOpPermissionVersionManage: locale.NameOpPermissionVersionManage, + pkgConst.UIdOfOpPermissionViewPipeline: locale.NameOpPermissionViewPipeline, + pkgConst.UIdOfOpPermissionManageProjectDataSource: locale.NameOpPermissionManageProjectDataSource, + pkgConst.UIdOfOpPermissionManageAuditRuleTemplate: locale.NameOpPermissionManageAuditRuleTemplate, + pkgConst.UIdOfOpPermissionManageApprovalTemplate: locale.NameOpPermissionManageApprovalTemplate, + pkgConst.UIdOfOpPermissionManageMember: locale.NameOpPermissionManageMember, + pkgConst.UIdOfOpPermissionPushRule: locale.NameOpPermissionPushRule, + pkgConst.UIdOfOpPermissionMangeAuditSQLWhiteList: locale.NameOpPermissionMangeAuditSQLWhiteList, + pkgConst.UIdOfOpPermissionManageSQLMangeWhiteList: locale.NameOpPermissionManageSQLMangeWhiteList, + pkgConst.UIdOfOpPermissionManageRoleMange: locale.NameOpPermissionManageRoleMange, + pkgConst.UIdOfOpPermissionDesensitization: locale.NameOpPermissionDesensitization, + pkgConst.UIdOfOpPermissionMaskingAudit: locale.NameOpPermissionMaskingAudit, +} + +var OpPermissionDescByUID = map[string]*i18n.Message{ + pkgConst.UIDOfOpPermissionCreateProject: locale.DescOpPermissionCreateProject, + pkgConst.UIDOfOpPermissionProjectAdmin: locale.DescOpPermissionProjectAdmin, + pkgConst.UIDOfOpPermissionCreateWorkflow: locale.DescOpPermissionCreateWorkflow, + pkgConst.UIDOfOpPermissionAuditWorkflow: locale.DescOpPermissionAuditWorkflow, + pkgConst.UIDOfOpPermissionAuthDBServiceData: locale.DescOpPermissionAuthDBServiceData, + pkgConst.UIDOfOpPermissionExecuteWorkflow: locale.DescOpPermissionExecuteWorkflow, + pkgConst.UIDOfOpPermissionViewOthersWorkflow: locale.DescOpPermissionViewOthersWorkflow, + pkgConst.UIDOfOpPermissionSaveAuditPlan: locale.DescOpPermissionSaveAuditPlan, + pkgConst.UIDOfOpPermissionViewOthersAuditPlan: locale.DescOpPermissionViewOthersAuditPlan, + pkgConst.UIDOfOpPermissionViewSQLInsight: locale.DescOpPermissionViewSQLInsight, + pkgConst.UIDOfOpPermissionSQLQuery: locale.DescOpPermissionSQLQuery, + pkgConst.UIDOfOpPermissionExportApprovalReject: locale.DescOpPermissionExportApprovalReject, + pkgConst.UIDOfOpPermissionExportCreate: locale.DescOpPermissionExportCreate, + pkgConst.UIDOfOpPermissionCreateOptimization: locale.DescOpPermissionCreateOptimization, + pkgConst.UIDOfOpPermissionViewOthersOptimization: locale.DescOpPermissionViewOthersOptimization, + pkgConst.UIDOfOpPermissionGlobalManagement: locale.DescOpPermissionGlobalManagement, + pkgConst.UIDOfOpPermissionGlobalView: locale.DescOpPermissionGlobalView, + pkgConst.UIDOfOpPermissionCreatePipeline: locale.DescOpPermissionCreatePipeline, + pkgConst.UIDOfOrdinaryUser: locale.DescOpPermissionOrdinaryUser, + pkgConst.UIDOfOpPermissionViewOperationRecord: locale.DescOpPermissionViewOperationRecord, + pkgConst.UIDOfOpPermissionViewExportTask: locale.DescOpPermissionViewExportTask, + pkgConst.UIDOfPermissionViewQuickAuditRecord: locale.DescPermissionViewQuickAuditRecord, + pkgConst.UIDOfOpPermissionViewIDEAuditRecord: locale.DescOpPermissionViewIDEAuditRecord, + pkgConst.UIDOfOpPermissionViewOptimizationRecord: locale.DescOpPermissionViewOptimizationRecord, + pkgConst.UIDOfOpPermissionViewVersionManage: locale.DescOpPermissionViewVersionManage, + pkgConst.UIDOfOpPermissionVersionManage: locale.DescOpPermissionVersionManage, + pkgConst.UIdOfOpPermissionViewPipeline: locale.DescOpPermissionViewPipeline, + pkgConst.UIdOfOpPermissionManageProjectDataSource: locale.DescOpPermissionManageProjectDataSource, + pkgConst.UIdOfOpPermissionManageAuditRuleTemplate: locale.DescOpPermissionManageAuditRuleTemplate, + pkgConst.UIdOfOpPermissionManageApprovalTemplate: locale.DescOpPermissionManageApprovalTemplate, + pkgConst.UIdOfOpPermissionManageMember: locale.DescOpPermissionManageMember, + pkgConst.UIdOfOpPermissionPushRule: locale.DescOpPermissionPushRule, + pkgConst.UIdOfOpPermissionMangeAuditSQLWhiteList: locale.DescOpPermissionMangeAuditSQLWhiteList, + pkgConst.UIdOfOpPermissionManageSQLMangeWhiteList: locale.DescOpPermissionManageSQLMangeWhiteList, + pkgConst.UIdOfOpPermissionManageRoleMange: locale.DescOpPermissionManageRoleMange, + pkgConst.UIdOfOpPermissionDesensitization: locale.DescOpPermissionDesensitization, + pkgConst.UIdOfOpPermissionMaskingAudit: locale.DescOpPermissionMaskingAudit, +} + func (d *DMSService) ListOpPermissions(ctx context.Context, req *dmsV1.ListOpPermissionReq) (reply *dmsV1.ListOpPermissionReply, err error) { - d.log.Infof("ListOpPermissions.req=%v", req) - defer func() { - d.log.Infof("ListOpPermissions.req=%v;reply=%v;error=%v", req, reply, err) - }() var orderBy biz.OpPermissionField switch req.OrderBy { @@ -22,16 +103,57 @@ func (d *DMSService) ListOpPermissions(ctx context.Context, req *dmsV1.ListOpPer orderBy = biz.OpPermissionFieldName } + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) + // 不支持智能调优时,隐藏相关权限 + if !conf.IsOptimizationEnabled() { + andConditions = append(andConditions, + pkgConst.FilterCondition{ + Field: string(biz.OpPermissionFieldUID), + Operator: pkgConst.FilterOperatorNotEqual, + Value: pkgConst.UIDOfOpPermissionCreateOptimization, + }, + pkgConst.FilterCondition{ + Field: string(biz.OpPermissionFieldUID), + Operator: pkgConst.FilterOperatorNotEqual, + Value: pkgConst.UIDOfOpPermissionViewOthersOptimization, + }) + } + + if req.Service != nil { + andConditions = append(andConditions, + pkgConst.FilterCondition{ + Field: string(biz.OpPermissionFieldService), + Operator: pkgConst.FilterOperatorEqual, + Value: *req.Service, + }) + } + + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + listOption := &biz.ListOpPermissionsOption{ - PageNumber: req.PageIndex, - LimitPerPage: req.PageSize, - OrderBy: orderBy, + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, } var ops []*biz.OpPermission var total int64 switch req.FilterByTarget { case dmsV1.OpPermissionTargetAll: + andConditions = append(andConditions, + pkgConst.FilterCondition{ + Field: string(biz.OpPermissionFieldRangeType), + Operator: pkgConst.FilterOperatorNotEqual, + Value: biz.OpRangeTypeGlobal, + }) + if len(andConditions) > 0 { + listOption.FilterByOptions.Groups = append(listOption.FilterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } ops, total, err = d.OpPermissionUsecase.ListOpPermissions(ctx, listOption) if nil != err { return nil, err @@ -46,6 +168,11 @@ func (d *DMSService) ListOpPermissions(ctx context.Context, req *dmsV1.ListOpPer if nil != err { return nil, err } + case dmsV1.OpPermissionTargetProject: + ops, total, err = d.OpPermissionUsecase.ListProjectOpPermissions(ctx, listOption) + if nil != err { + return nil, err + } default: return nil, fmt.Errorf("invalid filter by target: %v", req.FilterByTarget) } @@ -56,17 +183,30 @@ func (d *DMSService) ListOpPermissions(ctx context.Context, req *dmsV1.ListOpPer if err != nil { return nil, fmt.Errorf("parse op range type failed: %v", err) } + + opPermissionName := o.Name + if msg, ok := OpPermissionNameByUID[o.GetUID()]; ok && msg != nil { + opPermissionName = locale.Bundle.LocalizeMsgByCtx(ctx, msg) + } + + opPermissionDesc := "" + if msg, ok := OpPermissionDescByUID[o.GetUID()]; ok && msg != nil { + opPermissionDesc = locale.Bundle.LocalizeMsgByCtx(ctx, msg) + } + ret[i] = &dmsV1.ListOpPermission{ - OpPermission: dmsV1.UidWithName{Uid: o.GetUID(), Name: o.Name}, - Description: o.Desc, - RangeType: opRangeTyp, + OpPermission: dmsV1.UidWithName{ + Uid: o.GetUID(), + Name: opPermissionName, + }, + Description: opPermissionDesc, + RangeType: opRangeTyp, + Module: string(o.Module), + Service: o.Service, } } return &dmsV1.ListOpPermissionReply{ - Payload: struct { - OpPermissions []*dmsV1.ListOpPermission `json:"op_permissions"` - Total int64 `json:"total"` - }{OpPermissions: ret, Total: total}, + Data: ret, Total: total, }, nil } diff --git a/internal/dms/service/operation_record_ce.go b/internal/dms/service/operation_record_ce.go new file mode 100644 index 000000000..2bbe50e26 --- /dev/null +++ b/internal/dms/service/operation_record_ce.go @@ -0,0 +1,28 @@ +//go:build !enterprise + +package service + +import ( + "context" + "errors" + + aV1 "github.com/actiontech/dms/api/dms/service/v1" + apiError "github.com/actiontech/dms/internal/apiserver/pkg/error" +) + +var errNotSupportOperationRecord = errors.New("OperationRecord related functions are enterprise version functions") + +func (d *DMSService) AddOperationRecord(ctx context.Context, req *aV1.AddOperationRecordReq) (reply *aV1.AddOperationRecordReply, err error) { + reply = &aV1.AddOperationRecordReply{} + reply.GenericResp.SetCode(int(apiError.DMSServiceErr)) + reply.GenericResp.SetMsg(errNotSupportOperationRecord.Error()) + return reply, nil +} + +func (d *DMSService) GetOperationRecordList(ctx context.Context, req *aV1.GetOperationRecordListReq, currentUserUid string) (reply *aV1.GetOperationRecordListReply, err error) { + return nil, errNotSupportOperationRecord +} + +func (d *DMSService) ExportOperationRecordList(ctx context.Context, req *aV1.ExportOperationRecordListReq, currentUserUid string) (reply []byte, err error) { + return nil, errNotSupportOperationRecord +} diff --git a/internal/dms/service/plugin.go b/internal/dms/service/plugin.go index 04362ff0b..2acdaf451 100644 --- a/internal/dms/service/plugin.go +++ b/internal/dms/service/plugin.go @@ -17,14 +17,13 @@ func (d *DMSService) RegisterDMSPlugin(ctx context.Context, currentUserUid strin if err := d.PluginUsecase.RegisterPlugin(ctx, &biz.Plugin{ Name: req.Plugin.Name, - AddDBServicePreCheckUrl: req.Plugin.AddDBServicePreCheckUrl, - DelDBServicePreCheckUrl: req.Plugin.DelDBServicePreCheckUrl, - DelUserPreCheckUrl: req.Plugin.DelUserPreCheckUrl, - DelUserGroupPreCheckUrl: req.Plugin.DelUserGroupPreCheckUrl, OperateDataResourceHandleUrl: req.Plugin.OperateDataResourceHandleUrl, + GetDatabaseDriverOptionsUrl: req.Plugin.GetDatabaseDriverOptionsUrl, + GetDatabaseDriverLogosUrl: req.Plugin.GetDatabaseDriverLogosUrl, }, currentUserUid); err != nil { return fmt.Errorf("register dms plugin failed: %v", err) } - + // 当有plugin注册时,初始化切片,重新调用接口获取数据库选项 + d.PluginUsecase.ClearDatabaseDriverOptionsCache() return nil } diff --git a/internal/dms/service/project.go b/internal/dms/service/project.go new file mode 100644 index 000000000..5b5f24b5a --- /dev/null +++ b/internal/dms/service/project.go @@ -0,0 +1,293 @@ +package service + +import ( + "context" + "errors" + "fmt" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + dmsV2 "github.com/actiontech/dms/api/dms/service/v2" + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + dmsCommonV2 "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + "github.com/go-openapi/strfmt" +) + +func (d *DMSService) ListProjects(ctx context.Context, req *dmsCommonV2.ListProjectReq, currentUserUid string) (reply *dmsCommonV2.ListProjectReply, err error) { + var orderBy biz.ProjectField + switch req.OrderBy { + case dmsCommonV1.ProjectOrderByName: + orderBy = biz.ProjectFieldName + default: + orderBy = biz.ProjectFieldName + } + + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) + if req.FilterByName != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.ProjectFieldName), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterByName, + }) + } + if req.FilterByUID != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.ProjectFieldUID), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterByUID, + }) + } + if req.FilterByProjectPriority != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.ProjectFieldPriority), + Operator: pkgConst.FilterOperatorEqual, + Value: dmsCommonV1.ToPriorityNum(req.FilterByProjectPriority), + }) + } + + if len(req.FilterByProjectUids) > 0 { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.ProjectFieldUID), + Operator: pkgConst.FilterOperatorIn, + Value: req.FilterByProjectUids, + }) + } + if req.FilterByDesc != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.ProjectFieldDesc), + Operator: pkgConst.FilterOperatorContains, + Value: req.FilterByDesc, + }) + } + + if req.FilterByBusinessTag != "" { + businessTag, err := d.BusinessTagUsecase.GetBusinessTagByName(ctx, req.FilterByBusinessTag) + if err != nil { + d.log.Errorf("get business tag failed: %v", err) + return nil, err + } + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.ProjectFieldBusinessTagUID), + Operator: pkgConst.FilterOperatorEqual, + Value: businessTag.UID, + }) + } + + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + + // 添加模糊搜索条件 + if req.FuzzyKeyword != "" { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicOr, + pkgConst.FilterCondition{ + Field: string(biz.ProjectFieldName), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + )) + } + + listOption := &biz.ListProjectsOption{ + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, + } + + projects, total, err := d.ProjectUsecase.ListProject(ctx, listOption, currentUserUid) + if nil != err { + return nil, err + } + + err = d.BusinessTagUsecase.LoadBusinessTagForProjects(ctx, projects) + if err != nil { + return nil, err + } + ret := make([]*dmsCommonV2.ListProject, len(projects)) + for i, n := range projects { + ret[i] = &dmsCommonV2.ListProject{ + ProjectUid: n.UID, + Name: n.Name, + Archived: (n.Status == biz.ProjectStatusArchived), + Desc: n.Desc, + CreateTime: strfmt.DateTime(n.CreateTime), + BusinessTag: &dmsCommonV2.BusinessTag{ + UID: n.BusinessTag.UID, + Name: n.BusinessTag.Name, + }, + ProjectPriority: n.Priority, + } + user, err := d.UserUsecase.GetUser(ctx, n.CreateUserUID) + if err != nil { + d.log.Errorf("get user error: %v", err) + continue + } + ret[i].CreateUser = dmsCommonV1.UidWithName{ + Uid: n.UID, + Name: user.Name, + } + } + + return &dmsCommonV2.ListProjectReply{ + Data: ret, Total: total, + }, nil +} + +func isStrInSlice(str string, slice []string) bool { + for _, s := range slice { + if s == str { + return true + } + } + return false +} + +func (d *DMSService) AddProject(ctx context.Context, currentUserUid string, req *dmsV2.AddProjectReq) (reply *dmsV2.AddProjectReply, err error) { + // check + { + // check current user has enough permission + if canCreateProject, err := d.OpPermissionVerifyUsecase.CanCreateProject(ctx, currentUserUid); err != nil { + return nil, err + } else if !canCreateProject { + return nil, fmt.Errorf("current user can't create project") + } + + // check project is exist + _, err := d.ProjectUsecase.GetProjectByName(ctx, req.Project.Name) + if err == nil { + return nil, fmt.Errorf("project %v is exist", req.Project.Name) + } + if !errors.Is(err, pkgErr.ErrStorageNoData) { + return nil, fmt.Errorf("failed to get project by name: %w", err) + } + // check business tag is exist + if req.Project.BusinessTag == nil || req.Project.BusinessTag.UID == "" { + return nil, fmt.Errorf("business tag is empty") + } + } + + project, err := biz.NewProject(currentUserUid, req.Project.Name, req.Project.Desc, req.Project.ProjectPriority, req.Project.BusinessTag.UID) + if err != nil { + return nil, err + } + err = d.ProjectUsecase.CreateProject(ctx, project, currentUserUid) + if err != nil { + return nil, fmt.Errorf("create project failed: %w", err) + } + + return &dmsV2.AddProjectReply{ + Data: struct { + // project UID + Uid string `json:"uid"` + }{Uid: project.UID}, + }, nil +} + +func (d *DMSService) DeleteProject(ctx context.Context, currentUserUid string, req *dmsV1.DelProjectReq) (err error) { + err = d.ProjectUsecase.DeleteProject(ctx, currentUserUid, req.ProjectUid) + if err != nil { + return fmt.Errorf("delete project failed: %w", err) + } + + return nil +} + +func (d *DMSService) UpdateProjectDesc(ctx context.Context, currentUserUid string, req *dmsV1.UpdateProjectReq) (err error) { + err = d.ProjectUsecase.UpdateProjectDesc(ctx, currentUserUid, req.ProjectUid, req.Project.Desc) + if err != nil { + return fmt.Errorf("update project failed: %w", err) + } + + return nil +} + +func (d *DMSService) UpdateProject(ctx context.Context, currentUserUid string, req *dmsV2.UpdateProjectReq) (err error) { + err = d.ProjectUsecase.UpdateProject(ctx, currentUserUid, req.ProjectUid, req.Project.Desc, req.Project.ProjectPriority, req.Project.BusinessTag.UID) + if err != nil { + return fmt.Errorf("update project failed: %w", err) + } + + return nil +} + +func (d *DMSService) ArchivedProject(ctx context.Context, currentUserUid string, req *dmsV1.ArchiveProjectReq) (err error) { + err = d.ProjectUsecase.ArchivedProject(ctx, currentUserUid, req.ProjectUid, true) + if err != nil { + return fmt.Errorf("archived project failed: %w", err) + } + + return nil +} + +func (d *DMSService) UnarchiveProject(ctx context.Context, currentUserUid string, req *dmsV1.UnarchiveProjectReq) (err error) { + err = d.ProjectUsecase.ArchivedProject(ctx, currentUserUid, req.ProjectUid, false) + if err != nil { + return fmt.Errorf("unarchive project failed: %w", err) + } + + return nil +} + +func (d *DMSService) ImportProjects(ctx context.Context, uid string, req *dmsV2.ImportProjectsReq) error { + return d.importProjects(ctx, uid, req) +} + +func (d *DMSService) GetImportProjectsTemplate(ctx context.Context, uid string) ([]byte, error) { + return d.getImportProjectsTemplate(ctx, uid) +} + +func (d *DMSService) PreviewImportProjects(ctx context.Context, uid string, file string) (reply *dmsV2.PreviewImportProjectsReply, err error) { + return d.previewImportProjects(ctx, uid, file) +} + +func (d *DMSService) ExportProjects(ctx context.Context, uid string, req *dmsV1.ExportProjectsReq) ([]byte, error) { + return d.exportProjects(ctx, uid, req) +} + +func (d *DMSService) GetImportDBServicesTemplate(ctx context.Context, uid string) ([]byte, error) { + return d.getImportDBServicesTemplate(ctx, uid) +} + +func (d *DMSService) ImportDBServicesOfProjectsCheck(ctx context.Context, userUid, fileContent string) (*dmsV2.ImportDBServicesCheckReply, []byte, error) { + return d.importDBServicesOfProjectsCheck(ctx, userUid, fileContent) +} + +func (d *DMSService) ImportDBServicesOfProjects(ctx context.Context, req *dmsV2.ImportDBServicesOfProjectsReq, uid string) error { + return d.importDBServicesOfProjects(ctx, req, uid) +} + +func (d *DMSService) DBServicesConnection(ctx context.Context, req *dmsV1.DBServiceConnectionReq, uid string) (*dmsV1.DBServicesConnectionReply, error) { + return d.dbServicesConnection(ctx, req, uid) +} + +func (d *DMSService) CheckDBServiceHasEnoughPrivileges(ctx context.Context, req dmsV1.CheckDBServicesPrivilegesReq) (*dmsV1.CheckDBServicesPrivilegesReply, error) { + checkdbServicePrivilegesResults, err := d.DBServiceUsecase.CheckDBServiceHasEnoughPrivileges(ctx, req.DBServices) + if err != nil { + return nil, err + } + checkDBServicesPrivileges := make([]dmsV1.CheckDBServicesPrivilegesItem, len(req.DBServices)) + for i, checkDBServicePrivilegesResult := range checkdbServicePrivilegesResults { + items := make([]dmsV1.CheckDBServiceIsConnectableReplyItem, 0) + for _, item := range checkDBServicePrivilegesResult.ComponentPrivilegesResult { + items = append(items, dmsV1.CheckDBServiceIsConnectableReplyItem{ + IsConnectable: item.IsConnectable, + Component: item.Component, + ConnectErrorMessage: item.ConnectErrorMessage, + }) + } + checkDBServicesPrivileges[i] = dmsV1.CheckDBServicesPrivilegesItem{ + CheckDBServicesPrivileges: items, + } + + } + + return &dmsV1.CheckDBServicesPrivilegesReply{ + Data: checkDBServicesPrivileges, + }, nil +} diff --git a/internal/dms/service/project_ce.go b/internal/dms/service/project_ce.go new file mode 100644 index 000000000..d6f9205c6 --- /dev/null +++ b/internal/dms/service/project_ce.go @@ -0,0 +1,45 @@ +//go:build !enterprise + +package service + +import ( + "context" + "errors" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + dmsV2 "github.com/actiontech/dms/api/dms/service/v2" +) + +var errNotSupportProject = errors.New("project related functions are enterprise version functions") + +func (d *DMSService) importProjects(ctx context.Context, uid string, req *dmsV2.ImportProjectsReq) error { + return errNotSupportProject +} + +func (d *DMSService) getImportProjectsTemplate(ctx context.Context, uid string) ([]byte, error) { + return nil, errNotSupportProject +} + +func (d *DMSService) previewImportProjects(ctx context.Context, uid string, file string) (reply *dmsV2.PreviewImportProjectsReply, err error) { + return nil, errNotSupportProject +} + +func (d *DMSService) exportProjects(ctx context.Context, uid string, req *dmsV1.ExportProjectsReq) ([]byte, error) { + return nil, errNotSupportProject +} + +func (d *DMSService) getImportDBServicesTemplate(ctx context.Context, uid string) ([]byte, error) { + return nil, errNotSupportProject +} + +func (d *DMSService) importDBServicesOfProjectsCheck(ctx context.Context, userUid, fileContent string) (*dmsV2.ImportDBServicesCheckReply, []byte, error) { + return nil, nil, errNotSupportProject +} + +func (d *DMSService) importDBServicesOfProjects(ctx context.Context, req *dmsV2.ImportDBServicesOfProjectsReq, uid string) error { + return errNotSupportProject +} + +func (d *DMSService) dbServicesConnection(ctx context.Context, req *dmsV1.DBServiceConnectionReq, uid string) (*dmsV1.DBServicesConnectionReply, error) { + return nil, errNotSupportProject +} diff --git a/internal/dms/service/proxy.go b/internal/dms/service/proxy.go index 16c37eed9..4ef6f3fbc 100644 --- a/internal/dms/service/proxy.go +++ b/internal/dms/service/proxy.go @@ -10,18 +10,36 @@ import ( ) func (d *DMSService) RegisterDMSProxyTarget(ctx context.Context, currentUserUid string, req *dmsV1.RegisterDMSProxyTargetReq) (err error) { - d.log.Infof("RegisterDMSProxyTarget.req=%v", req) + d.log.Infof("RegisterDMSProxyTarget.req=%v", *req) defer func() { - d.log.Infof("RegisterDMSProxyTarget.req=%v;error=%v", req, err) + d.log.Infof("RegisterDMSProxyTarget.req=%v;error=%v", *req, err) }() - + scenairo, err := convertProxyScenario(req.DMSProxyTarget.Scenario) + if err != nil { + return err + } if err := d.DmsProxyUsecase.RegisterDMSProxyTarget(ctx, currentUserUid, biz.RegisterDMSProxyTargetArgs{ Name: req.DMSProxyTarget.Name, Addr: req.DMSProxyTarget.Addr, + Version: req.DMSProxyTarget.Version, ProxyUrlPrefixs: req.DMSProxyTarget.ProxyUrlPrefixs, + Scenario: scenairo, }); err != nil { return fmt.Errorf("register dms proxy target failed: %v", err) } - return nil } + +func convertProxyScenario(scenario dmsV1.ProxyScenario) (biz.ProxyScenario, error) { + switch scenario { + case dmsV1.ProxyScenarioInternalService: + return biz.ProxyScenarioInternalService, nil + case dmsV1.ProxyScenarioThirdPartyIntegrate: + return biz.ProxyScenarioThirdPartyIntegrate, nil + case "": + // 兼容旧版本SQLE + return biz.ProxyScenarioInternalService, nil + default: + return "", biz.ErrUnknownProxyScenario + } +} diff --git a/internal/dms/service/resource_overview_ce.go b/internal/dms/service/resource_overview_ce.go new file mode 100644 index 000000000..00f2c930f --- /dev/null +++ b/internal/dms/service/resource_overview_ce.go @@ -0,0 +1,32 @@ +//go:build !enterprise + +package service + +import ( + "context" + "errors" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" +) + +var ErrNotSupportResourceOverview = errors.New("resource overview related functions are enterprise version functions") + +func (svc *DMSService) GetResourceOverviewStatistics(ctx context.Context, currentUserUid string) (resp *dmsV1.ResourceOverviewStatisticsRes, err error) { + return nil, ErrNotSupportResourceOverview +} + +func (svc *DMSService) GetResourceOverviewResourceTypeDistribution(ctx context.Context, currentUserUid string) (resp *dmsV1.ResourceOverviewResourceTypeDistributionRes, err error) { + return nil, ErrNotSupportResourceOverview +} + +func (svc *DMSService) GetResourceOverviewTopology(ctx context.Context, currentUserUid string, req *dmsV1.ResourceOverviewTopologyReq) (resp *dmsV1.ResourceOverviewTopologyRes, err error) { + return nil, ErrNotSupportResourceOverview +} + +func (svc *DMSService) GetResourceOverviewList(ctx context.Context, currentUserUid string, req *dmsV1.ResourceOverviewResourceListReq) (resp *dmsV1.ResourceOverviewResourceListRes, err error) { + return nil, ErrNotSupportResourceOverview +} + +func (svc *DMSService) DownloadResourceOverviewList(ctx context.Context, currentUserUid string, req *dmsV1.DownloadResourceOverviewListReq) ([]byte, error) { + return nil, ErrNotSupportResourceOverview +} \ No newline at end of file diff --git a/internal/dms/service/role.go b/internal/dms/service/role.go index fcf6317b0..ac25ff258 100644 --- a/internal/dms/service/role.go +++ b/internal/dms/service/role.go @@ -4,11 +4,30 @@ import ( "context" "fmt" + "github.com/actiontech/dms/internal/apiserver/conf" + "github.com/actiontech/dms/internal/pkg/locale" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/nicksnyder/go-i18n/v2/i18n" + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" "github.com/actiontech/dms/internal/dms/biz" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" ) +var RoleNameByUID = map[string]*i18n.Message{ + pkgConst.UIDOfRoleProjectAdmin: locale.NameRoleProjectAdmin, + pkgConst.UIDOfRoleDevEngineer: locale.NameRoleDevEngineer, + pkgConst.UIDOfRoleDevManager: locale.NameRoleDevManager, + pkgConst.UIDOfRoleOpsEngineer: locale.NameRoleOpsEngineer, +} + +var RoleDescByUID = map[string]*i18n.Message{ + pkgConst.UIDOfRoleProjectAdmin: locale.DescRoleProjectAdmin, + pkgConst.UIDOfRoleDevEngineer: locale.DescRoleDevEngineer, + pkgConst.UIDOfRoleDevManager: locale.DescRoleDevManager, + pkgConst.UIDOfRoleOpsEngineer: locale.DescRoleOpsEngineer, +} + func (d *DMSService) AddRole(ctx context.Context, currentUserUid string, req *dmsV1.AddRoleReq) (reply *dmsV1.AddRoleReply, err error) { d.log.Infof("AddRoles.req=%v", req) defer func() { @@ -21,7 +40,7 @@ func (d *DMSService) AddRole(ctx context.Context, currentUserUid string, req *dm } return &dmsV1.AddRoleReply{ - Payload: struct { + Data: struct { // role UID Uid string `json:"uid"` }{Uid: uid}, @@ -66,23 +85,40 @@ func (d *DMSService) ListRoles(ctx context.Context, req *dmsV1.ListRoleReq) (rep case dmsV1.RoleOrderByName: orderBy = biz.RoleFieldName default: - orderBy = biz.RoleFieldName + orderBy = biz.RoleFieldCreatedAt } - filterBy := make([]pkgConst.FilterCondition, 0) + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) if req.FilterByName != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.RoleFieldName), - Operator: pkgConst.FilterOperatorContains, + Operator: pkgConst.FilterOperatorEqual, Value: req.FilterByName, }) } + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + + if req.FuzzyKeyword != "" { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicOr, + pkgConst.FilterCondition{ + Field: string(biz.RoleFieldOpPermission), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + )) + } + listOption := &biz.ListRolesOption{ - PageNumber: req.PageIndex, - LimitPerPage: req.PageSize, - OrderBy: orderBy, - FilterBy: filterBy, + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, } roles, total, err := d.RoleUsecase.ListRole(ctx, listOption) @@ -92,6 +128,10 @@ func (d *DMSService) ListRoles(ctx context.Context, req *dmsV1.ListRoleReq) (rep ret := make([]*dmsV1.ListRole, len(roles)) for i, r := range roles { + if r.UID == pkgConst.UIDOfRoleProjectAdmin || r.UID == pkgConst.UIDOfRoleDevEngineer || r.UID == pkgConst.UIDOfRoleDevManager || r.UID == pkgConst.UIDOfRoleOpsEngineer { + // built in role, localize name and desc + r.Name = locale.Bundle.LocalizeMsgByCtx(ctx, RoleNameByUID[r.GetUID()]) + } ret[i] = &dmsV1.ListRole{ RoleUid: r.GetUID(), Name: r.Name, @@ -101,11 +141,11 @@ func (d *DMSService) ListRoles(ctx context.Context, req *dmsV1.ListRoleReq) (rep // 获取角色状态 switch r.Stat { case biz.RoleStatOK: - ret[i].Stat = dmsV1.StatOK + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatOK)) case biz.RoleStatDisable: - ret[i].Stat = dmsV1.StatDisable + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatDisable)) default: - ret[i].Stat = dmsV1.StatUnknown + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatUnknown)) } // 获取角色的操作权限 @@ -114,15 +154,21 @@ func (d *DMSService) ListRoles(ctx context.Context, req *dmsV1.ListRoleReq) (rep return nil, err } for _, op := range ops { - ret[i].OpPermissions = append(ret[i].OpPermissions, dmsV1.UidWithName{Uid: op.GetUID(), Name: op.Name}) + // 不支持智能调优时,隐藏相关权限 + if !conf.IsOptimizationEnabled() && + (op.UID == pkgConst.UIDOfOpPermissionCreateOptimization || op.UID == pkgConst.UIDOfOpPermissionViewOthersOptimization) { + continue + } + ret[i].OpPermissions = append(ret[i].OpPermissions, dmsV1.ListRoleOpPermission{ + Uid: op.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[op.GetUID()]), + Module: string(op.Module), + }) } } return &dmsV1.ListRoleReply{ - Payload: struct { - Roles []*dmsV1.ListRole `json:"roles"` - Total int64 `json:"total"` - }{Roles: ret, Total: total}, + Data: ret, Total: total, }, nil } diff --git a/internal/dms/service/service.go b/internal/dms/service/service.go index 8e6b17ad7..d4389600d 100644 --- a/internal/dms/service/service.go +++ b/internal/dms/service/service.go @@ -6,41 +6,63 @@ import ( "github.com/actiontech/dms/internal/apiserver/conf" "github.com/actiontech/dms/internal/dms/biz" - "github.com/actiontech/dms/internal/dms/storage" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" ) type DMSService struct { + BasicUsecase *biz.BasicUsecase + ResourceOverviewUsecase *biz.ResourceOverviewUsecase + BusinessTagUsecase *biz.BusinessTagUsecase PluginUsecase *biz.PluginUsecase DBServiceUsecase *biz.DBServiceUsecase + DBServiceSyncTaskUsecase *biz.DBServiceSyncTaskUsecase + EnvironmentTagUsecase *biz.EnvironmentTagUsecase + LoginConfigurationUsecase *biz.LoginConfigurationUsecase UserUsecase *biz.UserUsecase UserGroupUsecase *biz.UserGroupUsecase RoleUsecase *biz.RoleUsecase OpPermissionUsecase *biz.OpPermissionUsecase MemberUsecase *biz.MemberUsecase + MemberGroupUsecase *biz.MemberGroupUsecase OpPermissionVerifyUsecase *biz.OpPermissionVerifyUsecase - NamespaceUsecase *biz.NamespaceUsecase + ProjectUsecase *biz.ProjectUsecase DmsProxyUsecase *biz.DmsProxyUsecase Oauth2ConfigurationUsecase *biz.Oauth2ConfigurationUsecase + OAuth2SessionUsecase *biz.OAuth2SessionUsecase LDAPConfigurationUsecase *biz.LDAPConfigurationUsecase SMTPConfigurationUsecase *biz.SMTPConfigurationUsecase WeChatConfigurationUsecase *biz.WeChatConfigurationUsecase WebHookConfigurationUsecase *biz.WebHookConfigurationUsecase + SmsConfigurationUseCase *biz.SmsConfigurationUseCase IMConfigurationUsecase *biz.IMConfigurationUsecase + CompanyNoticeUsecase *biz.CompanyNoticeUsecase + LicenseUsecase *biz.LicenseUsecase + ClusterUsecase *biz.ClusterUsecase + DataExportWorkflowUsecase *biz.DataExportWorkflowUsecase + CbOperationLogUsecase *biz.CbOperationLogUsecase + DataMaskingUsecase *dataMaskingUsecase + FunctionSupportRegistry *biz.FunctionSupportRegistry + AuthAccessTokenUseCase *biz.AuthAccessTokenUsecase + SwaggerUseCase *biz.SwaggerUseCase + GatewayUsecase *biz.GatewayUsecase + SystemVariableUsecase *biz.SystemVariableUsecase + OperationRecordUsecase *biz.OperationRecordUsecase + MaintenanceTimeUsecase *biz.MaintenanceTimeUsecase log *utilLog.Helper shutdownCallback func() error } -func NewAndInitDMSService(logger utilLog.Logger, opts *conf.Options) (*DMSService, error) { +func NewAndInitDMSService(logger utilLog.Logger, opts *conf.DMSOptions) (*DMSService, error) { st, err := storage.NewStorage(logger, &storage.StorageConfig{ - User: opts.DMSServiceOpts.Data.Database.UserName, - Password: opts.DMSServiceOpts.Data.Database.Password, - Host: opts.DMSServiceOpts.Data.Database.Host, - Port: opts.DMSServiceOpts.Data.Database.Port, - Schema: opts.DMSServiceOpts.Data.Database.Database, - Debug: opts.DMSServiceOpts.Data.Database.Debug, + User: opts.ServiceOpts.Database.UserName, + Password: opts.ServiceOpts.Database.Password, + Host: opts.ServiceOpts.Database.Host, + Port: opts.ServiceOpts.Database.Port, + Schema: opts.ServiceOpts.Database.Database, + Debug: opts.ServiceOpts.Database.Debug, + AutoMigrate: opts.ServiceOpts.Database.AutoMigrate, }) if nil != err { return nil, fmt.Errorf("failed to new data: %v", err) @@ -56,61 +78,141 @@ func NewAndInitDMSService(logger utilLog.Logger, opts *conf.Options) (*DMSServic } // 预定义解决usecase循环依赖问题 memberUsecase := biz.MemberUsecase{} - - namespaceRepo := storage.NewNamespaceRepo(logger, st) - namespaceUsecase := biz.NewNamespaceUsecase(logger, tx, namespaceRepo, &memberUsecase, opPermissionVerifyUsecase, pluginUseCase) + environmentTagUsecase := biz.EnvironmentTagUsecase{} + businessTagUsecase := biz.NewBusinessTagUsecase(storage.NewBusinessTagRepo(logger, st), logger) + projectRepo := storage.NewProjectRepo(logger, st) + projectUsecase := biz.NewProjectUsecase(logger, tx, projectRepo, &memberUsecase, opPermissionVerifyUsecase, pluginUseCase, businessTagUsecase, &environmentTagUsecase) dbServiceRepo := storage.NewDBServiceRepo(logger, st) - dbServiceUseCase := biz.NewDBServiceUsecase(dbServiceRepo, pluginUseCase, opPermissionVerifyUsecase, namespaceUsecase) + dmsProxyTargetRepo := storage.NewProxyTargetRepo(logger, st) + resourceOverviewUsecase := biz.NewResourceOverviewUsecase(logger, projectRepo, dbServiceRepo, *opPermissionVerifyUsecase, storage.NewResourceOverviewRepo(logger, st), dmsProxyTargetRepo) + environmentTagUsecase = *biz.NewEnvironmentTagUsecase(storage.NewEnvironmentTagRepo(logger, st), logger, projectUsecase, opPermissionVerifyUsecase) + discoveryTaskRepo := storage.NewSensitiveDataDiscoveryTaskRepo(logger, st) + dbServiceUseCase := biz.NewDBServiceUsecase(logger, dbServiceRepo, discoveryTaskRepo, pluginUseCase, opPermissionVerifyUsecase, projectUsecase, dmsProxyTargetRepo, &environmentTagUsecase) + dbServiceTaskRepo := storage.NewDBServiceSyncTaskRepo(logger, st) + dbServiceTaskUsecase := biz.NewDBServiceSyncTaskUsecase(logger, dbServiceTaskRepo, opPermissionVerifyUsecase, projectUsecase, dbServiceUseCase, &environmentTagUsecase) ldapConfigurationRepo := storage.NewLDAPConfigurationRepo(logger, st) ldapConfigurationUsecase := biz.NewLDAPConfigurationUsecase(logger, tx, ldapConfigurationRepo) userRepo := storage.NewUserRepo(logger, st) userGroupRepo := storage.NewUserGroupRepo(logger, st) opPermissionRepo := storage.NewOpPermissionRepo(logger, st) opPermissionUsecase := biz.NewOpPermissionUsecase(logger, tx, opPermissionRepo, pluginUseCase) - userUsecase := biz.NewUserUsecase(logger, tx, userRepo, userGroupRepo, pluginUseCase, opPermissionUsecase, opPermissionVerifyUsecase, ldapConfigurationUsecase) + cloudbeaverRepo := storage.NewCloudbeaverRepo(logger, st) + loginConfigurationRepo := storage.NewLoginConfigurationRepo(logger, st) + loginConfigurationUsecase := biz.NewLoginConfigurationUsecase(logger, tx, loginConfigurationRepo) + + gatewayUsecase, err := biz.NewDmsGatewayUsecase(logger, storage.NewGatewayRepo(logger, st)) + if err != nil { + return nil, fmt.Errorf("failed to new dms gateway use case: %v", err) + } + + userUsecase := biz.NewUserUsecase(logger, tx, userRepo, userGroupRepo, pluginUseCase, opPermissionUsecase, opPermissionVerifyUsecase, loginConfigurationUsecase, ldapConfigurationUsecase, cloudbeaverRepo, gatewayUsecase) userGroupUsecase := biz.NewUserGroupUsecase(logger, tx, userGroupRepo, userRepo, pluginUseCase, opPermissionVerifyUsecase) roleRepo := storage.NewRoleRepo(logger, st) memberRepo := storage.NewMemberRepo(logger, st) roleUsecase := biz.NewRoleUsecase(logger, tx, roleRepo, opPermissionRepo, memberRepo, pluginUseCase, opPermissionVerifyUsecase) dmsConfigRepo := storage.NewDMSConfigRepo(logger, st) dmsConfigUsecase := biz.NewDMSConfigUseCase(logger, dmsConfigRepo) - memberUsecase = *biz.NewMemberUsecase(logger, tx, memberRepo, userUsecase, roleUsecase, dbServiceUseCase, opPermissionVerifyUsecase, namespaceUsecase) - dmsProxyTargetRepo := storage.NewProxyTargetRepo(logger, st) - dmsProxyUsecase, err := biz.NewDmsProxyUsecase(logger, dmsProxyTargetRepo, opts.APIServiceOpts.HTTP.Port) + memberUsecase = *biz.NewMemberUsecase(logger, tx, memberRepo, userUsecase, roleUsecase, dbServiceUseCase, opPermissionVerifyUsecase, projectUsecase, pluginUseCase) + memberGroupRepo := storage.NewMemberGroupRepo(logger, st) + memberGroupUsecase := biz.NewMemberGroupUsecase(logger, tx, memberGroupRepo, userUsecase, roleUsecase, dbServiceUseCase, opPermissionVerifyUsecase, projectUsecase, &memberUsecase, pluginUseCase) + dmsProxyUsecase, err := biz.NewDmsProxyUsecase(logger, dmsProxyTargetRepo, opts.APIServiceOpts, opPermissionUsecase, roleUsecase) + if err != nil { + return nil, fmt.Errorf("failed to new dms proxy usecase: %v", err) + } + oauth2SessionRepo := storage.NewOAuth2SessionRepo(logger, st) + oauth2SessionUsecase := biz.NewOAuth2SessionUsecase(logger, tx, oauth2SessionRepo) oauth2ConfigurationRepo := storage.NewOauth2ConfigurationRepo(logger, st) - oauth2ConfigurationUsecase := biz.NewOauth2ConfigurationUsecase(logger, tx, oauth2ConfigurationRepo, userUsecase) + oauth2ConfigurationUsecase := biz.NewOauth2ConfigurationUsecase(logger, tx, oauth2ConfigurationRepo, userUsecase, oauth2SessionUsecase) + companyNoticeRepo := storage.NewCompanyNoticeRepo(logger, st) + companyNoticeRepoUsecase := biz.NewCompanyNoticeUsecase(logger, tx, companyNoticeRepo, userUsecase) smtpConfigurationRepo := storage.NewSMTPConfigurationRepo(logger, st) smtpConfigurationUsecase := biz.NewSMTPConfigurationUsecase(logger, tx, smtpConfigurationRepo) wechatConfigurationRepo := storage.NewWeChatConfigurationRepo(logger, st) wechatConfigurationUsecase := biz.NewWeChatConfigurationUsecase(logger, tx, wechatConfigurationRepo) webhookConfigurationRepo := storage.NewWebHookConfigurationRepo(logger, st) webhookConfigurationUsecase := biz.NewWebHookConfigurationUsecase(logger, tx, webhookConfigurationRepo) + smsConfigurationRepo := storage.NewSmsConfigurationRepo(logger, st) + smsConfigurationUsecase := biz.NewSmsConfigurationUsecase(logger, tx, smsConfigurationRepo, userUsecase) imConfigurationRepo := storage.NewIMConfigurationRepo(logger, st) imConfigurationUsecase := biz.NewIMConfigurationUsecase(logger, tx, imConfigurationRepo) + basicConfigRepo := storage.NewBasicConfigRepo(logger, st) + basicUsecase := biz.NewBasicInfoUsecase(logger, dmsProxyUsecase, basicConfigRepo) + clusterRepo := storage.NewClusterRepo(logger, st) + clusterUsecase := biz.NewClusterUsecase(logger, tx, clusterRepo) + licenseRepo := storage.NewLicenseRepo(logger, st) + LicenseUsecase := biz.NewLicenseUsecase(logger, tx, licenseRepo, userUsecase, dbServiceUseCase, clusterUsecase) + dataExportTaskRepo := storage.NewDataExportTaskRepo(logger, st) + swaggerUseCase := biz.NewSwaggerUseCase(logger, dmsProxyUsecase) + systemVariableUsecase := biz.NewSystemVariableUsecase(logger, storage.NewSystemVariableRepo(logger, st)) + maintenanceTimeUsecase := biz.NewMaintenanceTimeUsecase(logger, opPermissionVerifyUsecase) + operationRecordRepo := storage.NewOperationRecordRepo(logger, st) + operationRecordUsecase := biz.NewOperationRecordUsecase(logger, operationRecordRepo, systemVariableUsecase) + cbOperationRepo := storage.NewCbOperationLogRepo(logger, st) + CbOperationLogUsecase := biz.NewCbOperationLogUsecase(logger, cbOperationRepo, opPermissionVerifyUsecase, dmsProxyTargetRepo, systemVariableUsecase) + workflowRepo := storage.NewWorkflowRepo(logger, st) + dataExportMaskingConfigRepo := initDataExportMaskingConfigRepo(logger, st) + DataExportWorkflowUsecase := biz.NewDataExportWorkflowUsecase(logger, tx, workflowRepo, dataExportTaskRepo, dbServiceRepo, dataExportMaskingConfigRepo, opPermissionVerifyUsecase, projectUsecase, dmsProxyTargetRepo, clusterUsecase, webhookConfigurationUsecase, userUsecase, systemVariableUsecase, discoveryTaskRepo, fmt.Sprintf("%s:%d", opts.ReportHost, opts.APIServiceOpts.Port)) + dataMaskingUsecase, stopDataMaskingScheduler, err := initDataMaskingUsecase(logger, st, dbServiceUseCase, clusterUsecase, dmsProxyTargetRepo) if err != nil { - return nil, fmt.Errorf("failed to new dms proxy usecase: %v", err) + return nil, fmt.Errorf("failed to initialize data masking usecase: %v", err) + } + + // 初始化功能支持注册中心 + functionSupportRegistry := biz.NewFunctionSupportRegistry() + // 在 DMS 版本中注册功能提供者(通过条件编译函数) + registerFunctionProvidersToRegistry(functionSupportRegistry, dataMaskingUsecase) + + authAccessTokenUsecase := biz.NewAuthAccessTokenUsecase(logger, userUsecase) + + cronTask := biz.NewCronTaskUsecase(logger, DataExportWorkflowUsecase, CbOperationLogUsecase, operationRecordUsecase, oauth2SessionUsecase) + err = cronTask.InitialTask() + if err != nil { + return nil, fmt.Errorf("failed to new cron task: %v", err) } s := &DMSService{ + BasicUsecase: basicUsecase, + ResourceOverviewUsecase: resourceOverviewUsecase, + BusinessTagUsecase: businessTagUsecase, + EnvironmentTagUsecase: &environmentTagUsecase, PluginUsecase: pluginUseCase, DBServiceUsecase: dbServiceUseCase, + DBServiceSyncTaskUsecase: dbServiceTaskUsecase, + LoginConfigurationUsecase: loginConfigurationUsecase, UserUsecase: userUsecase, UserGroupUsecase: userGroupUsecase, RoleUsecase: roleUsecase, OpPermissionUsecase: opPermissionUsecase, MemberUsecase: &memberUsecase, + MemberGroupUsecase: memberGroupUsecase, OpPermissionVerifyUsecase: opPermissionVerifyUsecase, - NamespaceUsecase: namespaceUsecase, + ProjectUsecase: projectUsecase, DmsProxyUsecase: dmsProxyUsecase, Oauth2ConfigurationUsecase: oauth2ConfigurationUsecase, + OAuth2SessionUsecase: oauth2SessionUsecase, LDAPConfigurationUsecase: ldapConfigurationUsecase, SMTPConfigurationUsecase: smtpConfigurationUsecase, WeChatConfigurationUsecase: wechatConfigurationUsecase, WebHookConfigurationUsecase: webhookConfigurationUsecase, IMConfigurationUsecase: imConfigurationUsecase, + SmsConfigurationUseCase: smsConfigurationUsecase, + CompanyNoticeUsecase: companyNoticeRepoUsecase, + LicenseUsecase: LicenseUsecase, + ClusterUsecase: clusterUsecase, + DataExportWorkflowUsecase: DataExportWorkflowUsecase, + CbOperationLogUsecase: CbOperationLogUsecase, + DataMaskingUsecase: dataMaskingUsecase, + FunctionSupportRegistry: functionSupportRegistry, + AuthAccessTokenUseCase: authAccessTokenUsecase, + SwaggerUseCase: swaggerUseCase, + GatewayUsecase: gatewayUsecase, + SystemVariableUsecase: systemVariableUsecase, + OperationRecordUsecase: operationRecordUsecase, + MaintenanceTimeUsecase: maintenanceTimeUsecase, log: utilLog.NewHelper(logger, utilLog.WithMessageKey("dms.service")), shutdownCallback: func() error { + stopDataMaskingScheduler() if err := st.Close(); nil != err { return fmt.Errorf("failed to close storage: %v", err) } @@ -121,7 +223,7 @@ func NewAndInitDMSService(logger utilLog.Logger, opts *conf.Options) (*DMSServic // init notification biz.Init(smtpConfigurationUsecase, wechatConfigurationUsecase, imConfigurationUsecase) // init env - if err := biz.EnvPrepare(context.TODO(), logger, tx, dmsConfigUsecase, opPermissionUsecase, userUsecase, roleUsecase, namespaceUsecase); nil != err { + if err := biz.EnvPrepare(context.TODO(), logger, tx, dmsConfigUsecase, opPermissionUsecase, userUsecase, roleUsecase, projectUsecase); nil != err { return nil, fmt.Errorf("failed to prepare env: %v", err) } s.log.Debug("env prepared") diff --git a/internal/dms/service/swgger.go b/internal/dms/service/swgger.go new file mode 100644 index 000000000..5690850c4 --- /dev/null +++ b/internal/dms/service/swgger.go @@ -0,0 +1,29 @@ +package service + +import ( + "github.com/actiontech/dms/api" + "github.com/actiontech/dms/internal/dms/biz" + "github.com/labstack/echo/v4" +) + +func (d *DMSService) RegisterSwagger(c echo.Context) error { + targets, err := d.DmsProxyUsecase.ListProxyTargetsByScenarios(c.Request().Context(), []biz.ProxyScenario{biz.ProxyScenarioInternalService}) + if err != nil { + return err + } + + for _, target := range targets { + targetName := api.SwaggerType(target.Name) + _, ok := api.GetSwaggerDoc(targetName) + if !ok { + reply, err := d.SwaggerUseCase.GetSwaggerContentByType(c, targetName) + if err != nil { + d.log.Errorf("failed to get swagger content by type: %s, err: %v", targetName, err) + continue + } + api.RegisterSwaggerDoc(targetName, reply) + } + } + + return nil +} diff --git a/internal/dms/service/user.go b/internal/dms/service/user.go index 05417019b..2878a216d 100644 --- a/internal/dms/service/user.go +++ b/internal/dms/service/user.go @@ -3,13 +3,18 @@ package service import ( "context" "fmt" + "strconv" "strings" + "time" dmsV1 "github.com/actiontech/dms/api/dms/service/v1" "github.com/actiontech/dms/internal/dms/biz" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" - + "github.com/actiontech/dms/internal/pkg/locale" dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + + jwtPkg "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/golang-jwt/jwt/v4" ) func (d *DMSService) VerifyUserLogin(ctx context.Context, req *dmsV1.VerifyUserLoginReq) (reply *dmsV1.VerifyUserLoginReply, err error) { @@ -19,18 +24,41 @@ func (d *DMSService) VerifyUserLogin(ctx context.Context, req *dmsV1.VerifyUserL }() var verifyFailedMsg string - uid, err := d.UserUsecase.UserLogin(ctx, req.UserName, req.Password) + uid, twoFactorEnabled, phone, err := d.UserUsecase.UserLogin(ctx, req.UserName, req.Password) if nil != err { verifyFailedMsg = err.Error() } + // TODO: 这里应该只根据twoFactorEnabled判断是否执行验证码校验 + // 目前这个VerifyUserLogin方法被controller层的VerifyUserLogin调用,前侧不传递验证码的时候只校验用户名密码 + if twoFactorEnabled && req.VerifyCode != nil { + // 如果启用了双因子认证,则需要验证短信验证码 + verifyCodeReply := d.VerifySmsCode(&dmsV1.VerifySmsCodeReq{ + Code: *req.VerifyCode, + Username: req.UserName, + }) + if !verifyCodeReply.Data.IsVerifyNormally { + return &dmsV1.VerifyUserLoginReply{ + Data: struct { + // If verify Successful, return empty string, otherwise return error message + VerifyFailedMsg string `json:"verify_failed_msg"` + // If verify Successful, return user uid + UserUid string `json:"user_uid"` + Phone string `json:"phone"` + TwoFactorEnabled bool `json:"two_factor_enabled"` + }{UserUid: uid, VerifyFailedMsg: verifyCodeReply.Data.VerifyErrorMessage, Phone: phone, TwoFactorEnabled: twoFactorEnabled}, + }, nil + } + } return &dmsV1.VerifyUserLoginReply{ - Payload: struct { + Data: struct { // If verify Successful, return empty string, otherwise return error message VerifyFailedMsg string `json:"verify_failed_msg"` // If verify Successful, return user uid - UserUid string `json:"user_uid"` - }{UserUid: uid, VerifyFailedMsg: verifyFailedMsg}, + UserUid string `json:"user_uid"` + Phone string `json:"phone"` + TwoFactorEnabled bool `json:"two_factor_enabled"` + }{UserUid: uid, VerifyFailedMsg: verifyFailedMsg, Phone: phone, TwoFactorEnabled: twoFactorEnabled}, }, nil } @@ -48,18 +76,13 @@ func (d *DMSService) AfterUserLogin(ctx context.Context, req *dmsV1.AfterUserLog } func (d *DMSService) GetCurrentUser(ctx context.Context, req *dmsV1.GetUserBySessionReq) (reply *dmsV1.GetUserBySessionReply, err error) { - d.log.Infof("GetCurrentUser,req=%v", req) - defer func() { - d.log.Infof("GetCurrentUser.req=%v,reply=%v;error=%v", req, reply, err) - }() - user, err := d.UserUsecase.GetUser(ctx, req.UserUid) if nil != err { return nil, err } return &dmsV1.GetUserBySessionReply{ - Payload: struct { + Data: struct { // User UID UserUid string `json:"user_uid"` // User name @@ -75,24 +98,28 @@ func (d *DMSService) AddUser(ctx context.Context, currentUserUid string, req *dm }() args := &biz.CreateUserArgs{ - Name: req.User.Name, - Desc: req.User.Desc, - Password: req.User.Password, - Email: req.User.Email, - Phone: req.User.Phone, - WxID: req.User.WxID, - IsDisabled: false, - UserGroupUIDs: req.User.UserGroupUids, - OpPermissionUIDs: req.User.OpPermissionUids, - } - - uid, err := d.UserUsecase.CreateUser(ctx, currentUserUid, args) + UID: req.User.UID, + Name: req.User.Name, + Desc: req.User.Desc, + Password: req.User.Password, + Email: req.User.Email, + Phone: req.User.Phone, + WxID: req.User.WxID, + IsDisabled: false, + UserGroupUIDs: req.User.UserGroupUids, + OpPermissionUIDs: req.User.OpPermissionUids, + ThirdPartyUserID: req.User.ThirdPartyUserID, + ThirdPartyUserInfo: req.User.ThirdPartyUserInfo, + UserAuthenticationType: biz.UserAuthenticationType(req.User.UserAuthenticationType), + } + + uid, err := d.UserUsecase.AddUser(ctx, currentUserUid, args) if err != nil { return nil, fmt.Errorf("create user failed: %w", err) } return &dmsV1.AddUserReply{ - Payload: struct { + Data: struct { // user UID Uid string `json:"uid"` }{Uid: uid}, @@ -100,13 +127,31 @@ func (d *DMSService) AddUser(ctx context.Context, currentUserUid string, req *dm } func (d *DMSService) UpdateUser(ctx context.Context, req *dmsV1.UpdateUserReq, currentUserUid string) (err error) { - d.log.Infof("UpdateUser.req=%v", req) - defer func() { - d.log.Infof("UpdateUser.req=%v;error=%v", req, err) - }() + /// TODO 当前保留了用户组概念,但暂时未有用户组实际应用场景.前端移除用户组相关功能,默认关联用户组为空 + if req.User.UserGroupUids == nil { + req.User.UserGroupUids = &[]string{} + } + + if err = d.UserUsecase.UpdateUser(ctx, currentUserUid, &biz.UpdateUserArgs{ + UserUID: req.UserUid, + IsDisabled: *req.User.IsDisabled, + Password: req.User.Password, + Email: req.User.Email, + Phone: req.User.Phone, + WxID: req.User.WxID, + Language: req.User.Language, + UserGroupUIDs: *req.User.UserGroupUids, + OpPermissionUIDs: *req.User.OpPermissionUids, + System: (*biz.UserSystem)(req.User.System), + }); nil != err { + return fmt.Errorf("update user failed: %v", err) + } - if err = d.UserUsecase.UpdateUser(ctx, currentUserUid, req.UserUid, *req.User.IsDisabled, - req.User.Password, req.User.Email, req.User.Phone, req.User.WxID, *req.User.UserGroupUids, *req.User.OpPermissionUids); nil != err { + return nil +} + +func (d *DMSService) UpdateCurrentUser(ctx context.Context, req *dmsV1.UpdateCurrentUserReq, currentUserUid string) (err error) { + if err = d.UserUsecase.UpdateCurrentUser(ctx, currentUserUid, req.User.OldPassword, req.User.Password, req.User.Email, req.User.Phone, req.User.WxID, req.User.Language, req.User.TwoFactorEnabled, (*biz.UserSystem)(req.User.System)); nil != err { return fmt.Errorf("update user failed: %v", err) } @@ -127,10 +172,6 @@ func (d *DMSService) DelUser(ctx context.Context, currentUserUid string, req *dm } func (d *DMSService) ListUsers(ctx context.Context, req *dmsCommonV1.ListUserReq) (reply *dmsCommonV1.ListUserReply, err error) { - d.log.Infof("ListUsers.req=%v", req) - defer func() { - d.log.Infof("ListUsers.req=%v;reply=%v;error=%v", req, reply, err) - }() var orderBy biz.UserField switch req.OrderBy { @@ -140,17 +181,19 @@ func (d *DMSService) ListUsers(ctx context.Context, req *dmsCommonV1.ListUserReq orderBy = biz.UserFieldName } - filterBy := make([]pkgConst.FilterCondition, 0) + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + + andConditions := make([]pkgConst.FilterCondition, 0) if req.FilterByName != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.UserFieldName), - Operator: pkgConst.FilterOperatorContains, + Operator: pkgConst.FilterOperatorEqual, Value: req.FilterByName, }) } if req.FilterByUids != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.UserFieldUID), Operator: pkgConst.FilterOperatorIn, Value: strings.Split(req.FilterByUids, ","), @@ -159,18 +202,104 @@ func (d *DMSService) ListUsers(ctx context.Context, req *dmsCommonV1.ListUserReq // 默认为false,不展示已删除用户 if !req.FilterDeletedUser { - filterBy = append(filterBy, pkgConst.FilterCondition{ + andConditions = append(andConditions, pkgConst.FilterCondition{ Field: string(biz.UserFieldDeletedAt), Operator: pkgConst.FilterOperatorIsNull, Value: nil, }) } + // 按邮箱过滤 + if req.FilterByEmail != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.UserFieldEmail), + Operator: pkgConst.FilterOperatorContains, + Value: req.FilterByEmail, + }) + } + + // 按手机号过滤 + if req.FilterByPhone != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.UserFieldPhone), + Operator: pkgConst.FilterOperatorContains, + Value: req.FilterByPhone, + }) + } + + // 按用户状态过滤 + if req.FilterByStat != "" { + // 将字符串枚举转换为 uint + var statValue uint + switch req.FilterByStat { + case dmsCommonV1.UserStatFilterNormal: + statValue = 0 + case dmsCommonV1.UserStatFilterDisabled: + statValue = 1 + default: + return nil, fmt.Errorf("invalid user stat filter: %s", req.FilterByStat) + } + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.UserFieldStat), + Operator: pkgConst.FilterOperatorEqual, + Value: statValue, + }) + } + + // 按认证类型过滤 + if req.FilterByAuthenticationType != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: string(biz.UserFieldUserAuthenticationType), + Operator: pkgConst.FilterOperatorEqual, + Value: string(req.FilterByAuthenticationType), + }) + } + + // 按用户系统过滤 + if req.FilterBySystem != "" { + andConditions = append(andConditions, pkgConst.FilterCondition{ + Field: "system", + Operator: pkgConst.FilterOperatorEqual, + Value: string(req.FilterBySystem), + }) + } + + if len(andConditions) > 0 { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup(pkgConst.FilterLogicAnd, andConditions...)) + } + + // 添加模糊搜索条件 + if req.FuzzyKeyword != "" { + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicOr, + pkgConst.FilterCondition{ + Field: string(biz.UserFieldName), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + pkgConst.FilterCondition{ + Field: string(biz.UserFieldUID), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + pkgConst.FilterCondition{ + Field: string(biz.UserFieldEmail), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + pkgConst.FilterCondition{ + Field: string(biz.UserFieldPhone), + Operator: pkgConst.FilterOperatorContains, + Value: req.FuzzyKeyword, + }, + )) + } + listOption := &biz.ListUsersOption{ - PageNumber: req.PageIndex, - LimitPerPage: req.PageSize, - OrderBy: orderBy, - FilterBy: filterBy, + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, } users, total, err := d.UserUsecase.ListUser(ctx, listOption) @@ -181,12 +310,15 @@ func (d *DMSService) ListUsers(ctx context.Context, req *dmsCommonV1.ListUserReq ret := make([]*dmsCommonV1.ListUser, len(users)) for i, u := range users { ret[i] = &dmsCommonV1.ListUser{ - UserUid: u.GetUID(), - Name: u.Name, - Email: u.Email, - Phone: u.Phone, - WxID: u.WxID, - IsDeleted: u.Deleted, + UserUid: u.GetUID(), + Name: u.Name, + Email: u.Email, + Phone: u.Phone, + WxID: u.WxID, + IsDeleted: u.Deleted, + ThirdPartyUserInfo: u.ThirdPartyUserInfo, + Projects: u.Projects, + System: dmsCommonV1.UserSystem(u.System), } // 已删除用户只有基础信息 if u.Deleted { @@ -195,11 +327,11 @@ func (d *DMSService) ListUsers(ctx context.Context, req *dmsCommonV1.ListUserReq // 获取用户状态 switch u.Stat { case biz.UserStatOK: - ret[i].Stat = dmsCommonV1.StatOK + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatOK)) case biz.UserStatDisable: - ret[i].Stat = dmsCommonV1.StatDisable + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatDisable)) default: - ret[i].Stat = dmsCommonV1.StatUnknown + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatUnknown)) } // 获取用户鉴权类型 @@ -229,16 +361,15 @@ func (d *DMSService) ListUsers(ctx context.Context, req *dmsCommonV1.ListUserReq return nil, err } for _, op := range ops { - ret[i].OpPermissions = append(ret[i].OpPermissions, dmsCommonV1.UidWithName{Uid: op.GetUID(), Name: op.Name}) + ret[i].OpPermissions = append(ret[i].OpPermissions, dmsCommonV1.UidWithName{ + Uid: op.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[op.GetUID()]), + }) } - } return &dmsCommonV1.ListUserReply{ - Payload: struct { - Users []*dmsCommonV1.ListUser `json:"users"` - Total int64 `json:"total"` - }{Users: ret, Total: total}, + Data: ret, Total: total, }, nil } @@ -260,7 +391,7 @@ func (d *DMSService) AddUserGroup(ctx context.Context, currentUserUid string, re } return &dmsV1.AddUserGroupReply{ - Payload: struct { + Data: struct { // user group UID Uid string `json:"uid"` }{Uid: uid}, @@ -295,10 +426,6 @@ func (d *DMSService) DelUserGroup(ctx context.Context, currentUserUid string, re } func (d *DMSService) ListUserGroups(ctx context.Context, req *dmsV1.ListUserGroupReq) (reply *dmsV1.ListUserGroupReply, err error) { - d.log.Infof("ListUserGroups.req=%v", req) - defer func() { - d.log.Infof("ListUserGroups.req=%v;reply=%v;error=%v", req, reply, err) - }() var orderBy biz.UserGroupField switch req.OrderBy { @@ -308,20 +435,24 @@ func (d *DMSService) ListUserGroups(ctx context.Context, req *dmsV1.ListUserGrou orderBy = biz.UserGroupFieldName } - filterBy := make([]pkgConst.FilterCondition, 0) + filterByOptions := pkgConst.NewFilterOptions(pkgConst.FilterLogicAnd) + if req.FilterByName != "" { - filterBy = append(filterBy, pkgConst.FilterCondition{ - Field: string(biz.UserGroupFieldName), - Operator: pkgConst.FilterOperatorContains, - Value: req.FilterByName, - }) + filterByOptions.Groups = append(filterByOptions.Groups, pkgConst.NewConditionGroup( + pkgConst.FilterLogicAnd, + pkgConst.FilterCondition{ + Field: string(biz.UserGroupFieldName), + Operator: pkgConst.FilterOperatorEqual, + Value: req.FilterByName, + }, + )) } listOption := &biz.ListUserGroupsOption{ - PageNumber: req.PageIndex, - LimitPerPage: req.PageSize, - OrderBy: orderBy, - FilterBy: filterBy, + PageNumber: req.PageIndex, + LimitPerPage: req.PageSize, + OrderBy: orderBy, + FilterByOptions: filterByOptions, } groups, total, err := d.UserGroupUsecase.ListUserGroup(ctx, listOption) @@ -340,11 +471,11 @@ func (d *DMSService) ListUserGroups(ctx context.Context, req *dmsV1.ListUserGrou // 获取用户组状态 switch g.Stat { case biz.UserGroupStatOK: - ret[i].Stat = dmsV1.StatOK + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatOK)) case biz.UserGroupStatDisable: - ret[i].Stat = dmsV1.StatDisable + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatDisable)) default: - ret[i].Stat = dmsV1.StatUnknown + ret[i].Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatUnknown)) } // 获取用户所属的用户组 @@ -359,30 +490,46 @@ func (d *DMSService) ListUserGroups(ctx context.Context, req *dmsV1.ListUserGrou } return &dmsV1.ListUserGroupReply{ - Payload: struct { - UserGroups []*dmsV1.ListUserGroup `json:"user_groups"` - Total int64 `json:"total"` - }{UserGroups: ret, Total: total}, + Data: ret, Total: total, }, nil } func (d *DMSService) GetUserOpPermission(ctx context.Context, req *dmsCommonV1.GetUserOpPermissionReq) (reply *dmsCommonV1.GetUserOpPermissionReply, err error) { - d.log.Infof("GetUserOpPermission.req=%v", req) - defer func() { - d.log.Infof("GetUserOpPermission.req=%v;error=%v", req, err) - }() + // 兼容新旧版本获取项目ID方式 + projectUid := req.ProjectUid + if projectUid == "" && req.UserOpPermission != nil { + projectUid = req.UserOpPermission.ProjectUid + } - isAdmin, err := d.OpPermissionVerifyUsecase.IsUserNamespaceAdmin(ctx, req.UserUid, req.UserOpPermission.NamespaceUid) + isAdmin, err := d.OpPermissionVerifyUsecase.IsUserProjectAdmin(ctx, req.UserUid, projectUid) if err != nil { return nil, fmt.Errorf("check user admin error: %v", err) } - permissions, err := d.OpPermissionVerifyUsecase.GetUserOpPermissionInNamespace(ctx, req.UserUid, req.UserOpPermission.NamespaceUid) + var permissions []biz.OpPermissionWithOpRange + + globalPermissions, err := d.OpPermissionVerifyUsecase.GetUserGlobalOpPermission(ctx, req.UserUid) if err != nil { - return nil, fmt.Errorf("get user op permission error: %v", err) + return nil, fmt.Errorf("get user global op permission error: %v", err) + } + permissions = append(permissions, globalPermissions...) + + if projectUid != "" { + projectPermissions, err := d.OpPermissionVerifyUsecase.GetUserOpPermissionInProject(ctx, req.UserUid, projectUid) + if err != nil { + return nil, fmt.Errorf("get user op permission error: %v", err) + } + permissions = append(permissions, projectPermissions...) + + } else { + projectPermissions, err := d.OpPermissionVerifyUsecase.GetUserOpPermission(ctx, req.UserUid) + if err != nil { + return nil, fmt.Errorf("get user op permission error: %v", err) + } + permissions = append(permissions, projectPermissions...) } - var replyOpPermission []dmsCommonV1.OpPermissionItem + var replyOpPermission = make([]dmsCommonV1.OpPermissionItem, 0, len(permissions)) for _, p := range permissions { opTyp, err := convertBizOpPermission(p.OpPermissionUID) @@ -408,47 +555,44 @@ func (d *DMSService) GetUserOpPermission(ctx context.Context, req *dmsCommonV1.G RangeType: dmsCommonRangeTyp, RangeUids: p.RangeUIDs, }) - } reply = &dmsCommonV1.GetUserOpPermissionReply{ - Payload: struct { + Data: struct { IsAdmin bool `json:"is_admin"` OpPermissionList []dmsCommonV1.OpPermissionItem `json:"op_permission_list"` }{IsAdmin: isAdmin, OpPermissionList: replyOpPermission}, } - d.log.Infof("GetUserOpPermission.resp=%v", reply) return reply, nil } func (d *DMSService) GetUser(ctx context.Context, req *dmsCommonV1.GetUserReq) (reply *dmsCommonV1.GetUserReply, err error) { - d.log.Infof("GetUser.req=%v", req) - defer func() { - d.log.Infof("GetUser.req=%v;error=%v", req, err) - }() - u, err := d.UserUsecase.GetUser(ctx, req.UserUid) if err != nil { return nil, fmt.Errorf("get user error: %v", err) } dmsCommonUser := &dmsCommonV1.GetUser{ - UserUid: u.GetUID(), - Name: u.Name, - Email: u.Email, - Phone: u.Phone, - WxID: u.WxID, + UserUid: u.GetUID(), + Name: u.Name, + Email: u.Email, + Phone: u.Phone, + WxID: u.WxID, + Language: u.Language, + TwoFactorEnabled: u.TwoFactorEnabled, + ThirdPartyUserInfo: u.ThirdPartyUserInfo, + System: dmsCommonV1.UserSystem(u.System), } // 获取用户状态 switch u.Stat { case biz.UserStatOK: - dmsCommonUser.Stat = dmsCommonV1.StatOK + dmsCommonUser.Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatOK)) case biz.UserStatDisable: - dmsCommonUser.Stat = dmsCommonV1.StatDisable + dmsCommonUser.Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatDisable)) default: - dmsCommonUser.Stat = dmsCommonV1.StatUnknown + dmsCommonUser.Stat = dmsCommonV1.Stat(locale.Bundle.LocalizeMsgByCtx(ctx, locale.StatUnknown)) } // 获取用户鉴权类型 @@ -478,48 +622,124 @@ func (d *DMSService) GetUser(ctx context.Context, req *dmsCommonV1.GetUserReq) ( return nil, err } for _, op := range ops { - dmsCommonUser.OpPermissions = append(dmsCommonUser.OpPermissions, dmsCommonV1.UidWithName{Uid: op.GetUID(), Name: op.Name}) + dmsCommonUser.OpPermissions = append(dmsCommonUser.OpPermissions, dmsCommonV1.UidWithName{ + Uid: op.GetUID(), + Name: locale.Bundle.LocalizeMsgByCtx(ctx, OpPermissionNameByUID[op.GetUID()]), + }) } isAdmin, err := d.UserUsecase.OpPermissionVerifyUsecase.IsUserDMSAdmin(ctx, u.GetUID()) if err != nil { return nil, fmt.Errorf("failed to check user is dms admin") } - dmsCommonUser.IsAdmin = isAdmin - // 获取管理空间 - userBindNamespaces := make([]dmsCommonV1.UserBindNamespace, 0) - if !isAdmin { - namespaceWithOpPermissions, err := d.OpPermissionVerifyUsecase.GetUserNamespaceOpPermission(ctx, u.GetUID()) - if err != nil { - return nil, fmt.Errorf("failed to get user namespace with op permission") - } - userBindNamespaces = d.OpPermissionVerifyUsecase.GetUserManagerNamespace(ctx, namespaceWithOpPermissions) - } else { - namespaces, _, err := d.NamespaceUsecase.ListNamespace(ctx, &biz.ListNamespacesOption{ + + canViewGlobal, err := d.UserUsecase.OpPermissionVerifyUsecase.CanViewGlobal(ctx, u.GetUID()) + if err != nil { + return nil, fmt.Errorf("failed to check user can view global") + } + + getGlobalProjectList := func() ([]*biz.Project, error) { + projects, _, err := d.ProjectUsecase.ListProject(ctx, &biz.ListProjectsOption{ PageNumber: 1, LimitPerPage: 999, - FilterBy: []pkgConst.FilterCondition{ - { - Field: string(biz.NamespaceFieldStatus), - Operator: pkgConst.FilterOperatorEqual, - Value: biz.NamespaceStatusActive, - }}, }, u.UID) if err != nil { return nil, err } - for _, namespace := range namespaces { - userBindNamespaces = append(userBindNamespaces, dmsCommonV1.UserBindNamespace{NamespaceID: namespace.UID, NamespaceName: namespace.Name, IsManager: true}) + return projects, nil + } + + getUserBindProjectList := func() ([]dmsCommonV1.UserBindProject, error) { + projectWithOpPermissions, err := d.OpPermissionVerifyUsecase.GetUserProjectOpPermission(ctx, u.GetUID()) + if err != nil { + return nil, fmt.Errorf("failed to get user project with op permission") + } + return d.OpPermissionVerifyUsecase.GetUserManagerProject(ctx, projectWithOpPermissions), nil + } + + dmsCommonUser.IsAdmin = isAdmin + // 获取管理项目 + userBindProjects := make([]dmsCommonV1.UserBindProject, 0) + if isAdmin { + projects, err := getGlobalProjectList() + if err != nil { + return nil, err + } + + for _, project := range projects { + userBindProjects = append(userBindProjects, dmsCommonV1.UserBindProject{ProjectID: project.UID, ProjectName: project.Name, IsManager: true}) + } + } else if canViewGlobal { + projects, err := getGlobalProjectList() + if err != nil { + return nil, err + } + + bindProjects, err := getUserBindProjectList() + if err != nil { + return nil, fmt.Errorf("failed to get user project with op permission") } + + for _, project := range projects { + var isManager bool + for _, bindProject := range bindProjects { + if bindProject.IsManager && project.UID == bindProject.ProjectID { + isManager = true + } + } + + userBindProjects = append(userBindProjects, dmsCommonV1.UserBindProject{ProjectID: project.UID, ProjectName: project.Name, IsManager: isManager}) + } + } else { + userBindProjects, err = getUserBindProjectList() + if err != nil { + return nil, fmt.Errorf("failed to get user project with op permission") + } + } + + dmsCommonUser.UserBindProjects = userBindProjects + + // 获取用户access token + tokenInfo, err := d.UserUsecase.GetAccessTokenByUser(ctx, u.UID) + if err != nil { + return nil, fmt.Errorf("failed to get user access token: %v", err) } - dmsCommonUser.UserBindNamespaces = userBindNamespaces + accessToken := dmsCommonV1.AccessTokenInfo{} + accessToken.AccessToken = tokenInfo.Token + accessToken.ExpiredTime = tokenInfo.ExpiredTime.Format("2006-01-02T15:04:05-07:00") + if tokenInfo.ExpiredTime.Before(time.Now()) { + accessToken.IsExpired = true + } + dmsCommonUser.AccessTokenInfo = accessToken reply = &dmsCommonV1.GetUserReply{ - Payload: struct { - User *dmsCommonV1.GetUser `json:"user"` - }{User: dmsCommonUser}, + Data: dmsCommonUser, + } + + return reply, nil +} + +func (d *DMSService) GenAccessToken(ctx context.Context, currentUserUid string, req *dmsCommonV1.GenAccessToken) (reply *dmsCommonV1.GenAccessTokenReply, err error) { + days, err := strconv.ParseUint(req.ExpirationDays, 10, 64) + if err != nil { + return nil, err + } + + expiredTime := time.Now().Add(time.Duration(days) * 24 * time.Hour) + token, err := jwtPkg.GenJwtTokenWithExpirationTime(jwt.NewNumericDate(expiredTime), jwtPkg.WithUserId(currentUserUid), jwtPkg.WithAccessTokenMark(biz.AccessTokenLogin)) + if err != nil { + return nil, fmt.Errorf("gen access token failed: %v", err) + } + if err := d.UserUsecase.SaveAccessToken(ctx, currentUserUid, token, expiredTime); err != nil { + return nil, fmt.Errorf("save access token failed: %v", err) + } + + reply = &dmsCommonV1.GenAccessTokenReply{ + Data: &dmsCommonV1.AccessTokenInfo{ + AccessToken: token, + ExpiredTime: expiredTime.Format("2006-01-02T15:04:05-07:00"), + }, } - d.log.Infof("GetUser.resp=%v", reply) return reply, nil } @@ -531,10 +751,14 @@ func convertBizOpPermission(opPermissionUid string) (apiOpPermissionTyp dmsCommo apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeAuditWorkflow case pkgConst.UIDOfOpPermissionAuthDBServiceData: apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeAuthDBServiceData - case pkgConst.UIDOfOpPermissionNamespaceAdmin: - apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeNamespaceAdmin - case pkgConst.UIDOfOpPermissionCreateNamespace: - apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeCreateNamespace + case pkgConst.UIDOfOpPermissionProjectAdmin: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeProjectAdmin + case pkgConst.UIDOfOpPermissionCreateProject: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeCreateProject + case pkgConst.UIDOfOpPermissionGlobalView: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeGlobalView + case pkgConst.UIDOfOpPermissionGlobalManagement: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeGlobalManagement case pkgConst.UIDOfOpPermissionExecuteWorkflow: apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeExecuteWorkflow case pkgConst.UIDOfOpPermissionViewOthersWorkflow: @@ -543,8 +767,58 @@ func convertBizOpPermission(opPermissionUid string) (apiOpPermissionTyp dmsCommo apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeSaveAuditPlan case pkgConst.UIDOfOpPermissionViewOthersAuditPlan: apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeViewOtherAuditPlan + case pkgConst.UIDOfOpPermissionViewSQLInsight: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeViewSQLInsight case pkgConst.UIDOfOpPermissionSQLQuery: apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeSQLQuery + case pkgConst.UIDOfOpPermissionExportApprovalReject: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeAuditExportWorkflow + case pkgConst.UIDOfOpPermissionExportCreate: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeExportCreate + case pkgConst.UIDOfOpPermissionCreateOptimization: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeCreateOptimization + case pkgConst.UIDOfOpPermissionViewOthersOptimization: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeViewOthersOptimization + case pkgConst.UIDOfOpPermissionCreatePipeline: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeCreatePipeline + case pkgConst.UIDOfOpPermissionViewOperationRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewOperationRecord + case pkgConst.UIDOfOpPermissionViewExportTask: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewExportTask + case pkgConst.UIDOfPermissionViewQuickAuditRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewQuickAuditRecord + case pkgConst.UIDOfOpPermissionViewIDEAuditRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewIDEAuditRecord + case pkgConst.UIDOfOpPermissionViewOptimizationRecord: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewOptimizationRecord + case pkgConst.UIDOfOpPermissionViewVersionManage: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewVersionManage + case pkgConst.UIDOfOpPermissionVersionManage: + apiOpPermissionTyp = dmsCommonV1.OpPermissionVersionManage + case pkgConst.UIdOfOpPermissionViewPipeline: + apiOpPermissionTyp = dmsCommonV1.OpPermissionViewPipeline + case pkgConst.UIdOfOpPermissionManageProjectDataSource: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageProjectDataSource + case pkgConst.UIdOfOpPermissionManageAuditRuleTemplate: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageAuditRuleTemplate + case pkgConst.UIdOfOpPermissionManageApprovalTemplate: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageApprovalTemplate + case pkgConst.UIdOfOpPermissionManageMember: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageMember + case pkgConst.UIdOfOpPermissionPushRule: + apiOpPermissionTyp = dmsCommonV1.OpPermissionPushRule + case pkgConst.UIdOfOpPermissionMangeAuditSQLWhiteList: + apiOpPermissionTyp = dmsCommonV1.OpPermissionMangeAuditSQLWhiteList + case pkgConst.UIdOfOpPermissionManageSQLMangeWhiteList: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageSQLMangeWhiteList + case pkgConst.UIdOfOpPermissionManageRoleMange: + apiOpPermissionTyp = dmsCommonV1.OpPermissionManageRoleMange + case pkgConst.UIdOfOpPermissionDesensitization: + apiOpPermissionTyp = dmsCommonV1.OpPermissionDesensitization + case pkgConst.UIdOfOpPermissionMaskingAudit: + apiOpPermissionTyp = dmsCommonV1.OpPermissionMaskingAudit + case pkgConst.UIDOfOrdinaryUser: + apiOpPermissionTyp = dmsCommonV1.OpPermissionTypeNone default: return dmsCommonV1.OpPermissionTypeUnknown, fmt.Errorf("get user op permission type error: invalid op permission uid: %v", opPermissionUid) @@ -556,8 +830,8 @@ func convertBizOpRangeType(bizOpRangeTyp biz.OpRangeType) (typ dmsV1.OpRangeType switch bizOpRangeTyp { case biz.OpRangeTypeGlobal: typ = dmsV1.OpRangeTypeGlobal - case biz.OpRangeTypeNamespace: - typ = dmsV1.OpRangeTypeNamespace + case biz.OpRangeTypeProject: + typ = dmsV1.OpRangeTypeProject case biz.OpRangeTypeDBService: typ = dmsV1.OpRangeTypeDBService default: @@ -566,3 +840,14 @@ func convertBizOpRangeType(bizOpRangeTyp biz.OpRangeType) (typ dmsV1.OpRangeType return typ, nil } + +func convertBizUidWithName(bizUidWithNames []biz.UIdWithName) []dmsV1.UidWithName { + ret := make([]dmsV1.UidWithName, 0) + for _, v := range bizUidWithNames { + ret = append(ret, dmsV1.UidWithName{ + Uid: v.Uid, + Name: v.Name, + }) + } + return ret +} diff --git a/internal/dms/storage/basic_config.go b/internal/dms/storage/basic_config.go new file mode 100644 index 000000000..ba2b29c6e --- /dev/null +++ b/internal/dms/storage/basic_config.go @@ -0,0 +1,48 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.BasicConfigRepo = (*BasicConfigRepo)(nil) + +type BasicConfigRepo struct { + *Storage + log *utilLog.Helper +} + +func NewBasicConfigRepo(log utilLog.Logger, s *Storage) *BasicConfigRepo { + return &BasicConfigRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.basic_config"))} +} + +func (d *BasicConfigRepo) GetBasicConfig(ctx context.Context) (*biz.BasicConfigParams, error) { + var basicConfig model.BasicConfig + err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Find(&basicConfig).Error; err != nil { + return fmt.Errorf("failed to get basic_config: %v", err) + } + return nil + }) + + if err != nil { + return nil, err + } + + return convertModelBasicConfig(&basicConfig), nil +} + +func (d *BasicConfigRepo) SaveBasicConfig(ctx context.Context, params *biz.BasicConfigParams) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(convertBizBasicConfig(params)).Error; err != nil { + return fmt.Errorf("failed to save basic config err: %v", err) + } + + return nil + }) +} diff --git a/internal/dms/storage/business_tag.go b/internal/dms/storage/business_tag.go new file mode 100644 index 000000000..ff0600f5b --- /dev/null +++ b/internal/dms/storage/business_tag.go @@ -0,0 +1,130 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.BusinessTagRepo = (*BusinessTagRepo)(nil) + +type BusinessTagRepo struct { + *Storage + log *utilLog.Helper +} + +func NewBusinessTagRepo(log utilLog.Logger, s *Storage) *BusinessTagRepo { + return &BusinessTagRepo{ + Storage: s, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.business_tag")), + } +} + +func (repo *BusinessTagRepo) toModel(businessTag *biz.BusinessTag) *model.BusinessTag { + return &model.BusinessTag{ + Name: businessTag.Name, + Model: model.Model{UID: businessTag.UID}, + } +} + +func (repo *BusinessTagRepo) toBiz(businessTag *model.BusinessTag) *biz.BusinessTag { + return &biz.BusinessTag{ + Name: businessTag.Name, + UID: businessTag.UID, + } +} + +func (repo *BusinessTagRepo) CreateBusinessTag(ctx context.Context, businessTag *biz.BusinessTag) error { + return transaction(repo.log, ctx, repo.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Create(repo.toModel(businessTag)).Error; err != nil { + return pkgErr.WrapStorageErr(repo.log, fmt.Errorf("failed to create business tag: %v", err)) + } + return nil + }) +} + +func (repo *BusinessTagRepo) UpdateBusinessTag(ctx context.Context, businessTagUID, businessTagName string) error { + return transaction(repo.log, ctx, repo.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.BusinessTag{}).Where("uid = ?", businessTagUID).Update("name", businessTagName).Error; err != nil { + return pkgErr.WrapStorageErr(repo.log, fmt.Errorf("failed to update business tag: %v", err)) + } + return nil + }) +} + +func (repo *BusinessTagRepo) DeleteBusinessTag(ctx context.Context, businessTagUID string) error { + return transaction(repo.log, ctx, repo.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("uid = ?", businessTagUID).Delete(&model.BusinessTag{}).Error; err != nil { + return pkgErr.WrapStorageErr(repo.log, fmt.Errorf("failed to delete business tag: %v", err)) + } + return nil + }) +} + +func (repo *BusinessTagRepo) GetBusinessTagByName(ctx context.Context, name string) (*biz.BusinessTag, error) { + var businessTag model.BusinessTag + if err := repo.db.WithContext(ctx).Where("name = ?", name).First(&businessTag).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return nil, pkgErr.ErrStorageNoData + } + return nil, fmt.Errorf("failed to get business tag by name: %w", err) + } + return repo.toBiz(&businessTag), nil +} + +func (repo *BusinessTagRepo) GetBusinessTagByUID(ctx context.Context, uid string) (*biz.BusinessTag, error) { + var businessTag model.BusinessTag + if err := repo.db.WithContext(ctx).Where("uid = ?", uid).First(&businessTag).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return nil, pkgErr.ErrStorageNoData + } + return nil, fmt.Errorf("failed to get business tag by uid: %w", err) + } + return repo.toBiz(&businessTag), nil +} +func (repo *BusinessTagRepo) ListBusinessTags(ctx context.Context, options *biz.ListBusinessTagsOption) ([]*biz.BusinessTag, int64, error) { + var businessTags []*model.BusinessTag + db := repo.db.WithContext(ctx) + + // 构建查询条件 + query := db.Model(&model.BusinessTag{}) + + // 添加模糊搜索条件 + if options.FuzzyKeyword != "" { + query = query.Where("name LIKE ?", "%"+options.FuzzyKeyword+"%") + } + + if options.Limit >= 0 { + query = query.Limit(options.Limit) + } + if options.Offset >= 0 { + query = query.Offset(options.Offset) + } + + // 获取分页结果 + if err := query.Find(&businessTags).Error; err != nil { + return nil, 0, fmt.Errorf("failed to list business tags: %w", err) + } + + // 获取总数(需要考虑模糊搜索条件) + var count int64 + countQuery := repo.db.WithContext(ctx).Model(&model.BusinessTag{}) + if options.FuzzyKeyword != "" { + countQuery = countQuery.Where("name LIKE ?", "%"+options.FuzzyKeyword+"%") + } + if err := countQuery.Count(&count).Error; err != nil { + return nil, 0, fmt.Errorf("failed to count business tags: %w", err) + } + + bizBusinessTags := make([]*biz.BusinessTag, 0, len(businessTags)) + for _, businessTag := range businessTags { + bizBusinessTags = append(bizBusinessTags, repo.toBiz(businessTag)) + } + + return bizBusinessTags, count, nil +} diff --git a/internal/dms/storage/cb_operation_log.go b/internal/dms/storage/cb_operation_log.go new file mode 100644 index 000000000..8f0c0c67a --- /dev/null +++ b/internal/dms/storage/cb_operation_log.go @@ -0,0 +1,135 @@ +package storage + +import ( + "context" + "fmt" + "time" + + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.CbOperationLogRepo = (*CbOperationLogRepo)(nil) + +type CbOperationLogRepo struct { + *Storage + log *utilLog.Helper +} + +func NewCbOperationLogRepo(log utilLog.Logger, s *Storage) *CbOperationLogRepo { + return &CbOperationLogRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.cbOperationLog"))} +} + +func (d *CbOperationLogRepo) SaveCbOperationLog(ctx context.Context, log *biz.CbOperationLog) error { + model := convertBizCbOperationLog(log) + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(model).Error; err != nil { + return fmt.Errorf("failed to save cb operation log: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *CbOperationLogRepo) UpdateCbOperationLog(ctx context.Context, operationLog *biz.CbOperationLog) error { + opLog := convertBizCbOperationLog(operationLog) + + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.CbOperationLog{}).Where("uid = ?", opLog.UID).Omit("created_at").Save(opLog).Error; err != nil { + return fmt.Errorf("failed to update cb operation log: %v", err) + } + return nil + }) +} + +func (d *CbOperationLogRepo) GetCbOperationLogByID(ctx context.Context, uid string) (*biz.CbOperationLog, error) { + var model model.CbOperationLog + if err := d.db.WithContext(ctx).Preload("Project").Preload("User").Preload("DbService").Where("uid = ?", uid).First(&model).Error; err != nil { + return nil, fmt.Errorf("failed to get cb operation log by uid: %v", err) + } + + operationLog, err := convertModelCbOperationLog(&model) + if err != nil { + return nil, err + } + + return operationLog, nil +} + +func (d *CbOperationLogRepo) ListCbOperationLogs(ctx context.Context, opt *biz.ListCbOperationLogOption) ([]*biz.CbOperationLog, int64, error) { + var models []*model.CbOperationLog + var total int64 + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find models + { + db := tx.WithContext(ctx).Preload("Project").Preload("User").Preload("DbService") + if opt.OrderBy != "" { + db = db.Order(fmt.Sprintf("%s DESC", opt.OrderBy)) + } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + if err := db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to list cb operation logs: %v", err) + } + } + + // find total + { + db := tx.WithContext(ctx).Model(&model.CbOperationLog{}) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count cb operation logs: %v", err) + } + } + return nil + }); err != nil { + return nil, 0, err + } + + ret := make([]*biz.CbOperationLog, 0) + for _, m := range models { + operationLog, err := convertModelCbOperationLog(m) + if err != nil { + return nil, 0, err + } + ret = append(ret, operationLog) + } + + return ret, total, nil +} + +func (d *CbOperationLogRepo) CleanCbOperationLogOpTimeBefore(ctx context.Context, t time.Time) (rowsAffected int64, err error) { + err = transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + result := tx.WithContext(ctx).Unscoped().Delete(&model.CbOperationLog{}, "op_time < ?", t) + if err := result.Error; err != nil { + return err + } + rowsAffected = result.RowsAffected + return nil + }) + return +} + +func (d *CbOperationLogRepo) CountOperationLogs(ctx context.Context, opt *biz.ListCbOperationLogOption) (int64, error) { + var total int64 + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + db := tx.WithContext(ctx).Model(&model.CbOperationLog{}) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count cb operation logs: %v", err) + } + return nil + }); err != nil { + return 0, err + } + + return total, nil +} diff --git a/internal/dms/storage/cloudbeaver.go b/internal/dms/storage/cloudbeaver.go index 67e7577c5..14c29cc83 100644 --- a/internal/dms/storage/cloudbeaver.go +++ b/internal/dms/storage/cloudbeaver.go @@ -6,6 +6,7 @@ import ( "github.com/actiontech/dms/internal/dms/biz" "github.com/actiontech/dms/internal/dms/storage/model" + "gorm.io/gorm/clause" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" @@ -52,10 +53,58 @@ func (cr *CloudbeaverRepo) UpdateCloudbeaverUserCache(ctx context.Context, u *bi }) } -func (cr *CloudbeaverRepo) GetCloudbeaverConnectionByDMSDBServiceIds(ctx context.Context, dmsDBServiceIds []string) ([]*biz.CloudbeaverConnection, error) { +func (cr *CloudbeaverRepo) GetDbServiceIdByConnectionId(ctx context.Context, connectionId string) (string, error) { + var cloudbeaverConnection model.CloudbeaverConnectionCache + err := transaction(cr.log, ctx, cr.db, func(tx *gorm.DB) error { + if err := tx.Where("cloudbeaver_connection_id = ?", connectionId).First(&cloudbeaverConnection).Error; err != nil { + return fmt.Errorf("failed to get cloudbeaver db_service_id: %v", err) + } + return nil + }) + + if err != nil { + return "", err + } + + return cloudbeaverConnection.DMSDBServiceID, nil +} + +func (cr *CloudbeaverRepo) GetAllCloudbeaverConnections(ctx context.Context) ([]*biz.CloudbeaverConnection, error) { var cloudbeaverConnections []*model.CloudbeaverConnectionCache err := transaction(cr.log, ctx, cr.db, func(tx *gorm.DB) error { - if err := tx.Find(&cloudbeaverConnections, dmsDBServiceIds).Error; err != nil { + if err := tx.Find(&cloudbeaverConnections).Error; err != nil { + return fmt.Errorf("failed to get cloudbeaver db service: %v", err) + } + return nil + }) + + if err != nil { + return nil, err + } + + return convertModelCloudbeaverConnection(cloudbeaverConnections), nil +} + +func (cr *CloudbeaverRepo) GetCloudbeaverConnectionsByUserIdAndDBServiceIds(ctx context.Context, userId string, dmsDBServiceIds []string) ([]*biz.CloudbeaverConnection, error) { + var cloudbeaverConnections []*model.CloudbeaverConnectionCache + err := transaction(cr.log, ctx, cr.db, func(tx *gorm.DB) error { + if err := tx.Where("dms_user_id = ? and dms_db_service_id in (?)", userId, dmsDBServiceIds).Find(&cloudbeaverConnections).Error; err != nil { + return fmt.Errorf("failed to get cloudbeaver db service: %v", err) + } + return nil + }) + + if err != nil { + return nil, err + } + + return convertModelCloudbeaverConnection(cloudbeaverConnections), nil +} + +func (cr *CloudbeaverRepo) GetCloudbeaverConnectionsByUserId(ctx context.Context, userId string) ([]*biz.CloudbeaverConnection, error) { + var cloudbeaverConnections []*model.CloudbeaverConnectionCache + err := transaction(cr.log, ctx, cr.db, func(tx *gorm.DB) error { + if err := tx.Where("dms_user_id = ?", userId).Find(&cloudbeaverConnections).Error; err != nil { return fmt.Errorf("failed to get cloudbeaver db service: %v", err) } return nil @@ -70,9 +119,41 @@ func (cr *CloudbeaverRepo) GetCloudbeaverConnectionByDMSDBServiceIds(ctx context func (cr *CloudbeaverRepo) UpdateCloudbeaverConnectionCache(ctx context.Context, u *biz.CloudbeaverConnection) error { return transaction(cr.log, ctx, cr.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Save(convertBizCloudbeaverConnection(u)).Error; err != nil { + if err := tx.WithContext(ctx).Clauses(clause.OnConflict{ + UpdateAll: true, + }).Create(convertBizCloudbeaverConnection(u)).Error; err != nil { return fmt.Errorf("failed to update cloudbeaver db Service: %v", err) } return nil }) } + +func (cr *CloudbeaverRepo) DeleteCloudbeaverConnectionCache(ctx context.Context, dbServiceId, userId, purpose string) error { + return transaction(cr.log, ctx, cr.db, func(tx *gorm.DB) error { + db := tx.WithContext(ctx).Where("dms_db_service_id = ?", dbServiceId) + if len(userId) > 0 { + db = db.Where("dms_user_id = ?", userId) + } + if len(purpose) > 0 { + db = db.Where("purpose = ?", purpose) + } + if err := db.Delete(&model.CloudbeaverConnectionCache{}).Error; err != nil { + return fmt.Errorf("failed to delete cloudbeaver db Service: %v", err) + } + return nil + }) +} + +func (cr *CloudbeaverRepo) DeleteAllCloudbeaverCachesByUserId(ctx context.Context, userId string) error { + return transaction(cr.log, ctx, cr.db, func(tx *gorm.DB) error { + err := tx.WithContext(ctx).Where("dms_user_id = ?", userId).Delete(&model.CloudbeaverConnectionCache{}).Error + if err != nil { + return fmt.Errorf("failed to delete cloudbeaver connection caches by user id %v err %v", userId, err) + } + err = tx.WithContext(ctx).Where("dms_user_id =?", userId).Delete(&model.CloudbeaverUserCache{}).Error + if err != nil { + return fmt.Errorf("failed to delete cloudbeaver user caches by user id %v err %v", userId, err) + } + return nil + }) +} diff --git a/internal/dms/storage/cluster.go b/internal/dms/storage/cluster.go new file mode 100644 index 000000000..ce68699b3 --- /dev/null +++ b/internal/dms/storage/cluster.go @@ -0,0 +1,91 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.ClusterRepo = (*ClusterRepo)(nil) + +type ClusterRepo struct { + *Storage + log *utilLog.Helper +} + +func NewClusterRepo(log utilLog.Logger, s *Storage) *ClusterRepo { + return &ClusterRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.cluster"))} +} + +func (d *ClusterRepo) GetClusterNodes(ctx context.Context) ([]*biz.ClusterNodeInfo, error) { + var items []*model.ClusterNodeInfo + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find models + db := tx.WithContext(ctx) + + if err := db.Find(&items).Error; err != nil { + return fmt.Errorf("failed to list cluster nodes: %v", err) + } + + return nil + }); err != nil { + return nil, err + } + + ret := make([]*biz.ClusterNodeInfo, 0, len(items)) + // convert model to biz + for _, item := range items { + ds, err := convertModelClusterNodeInfo(item) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert cluster_node_info: %w", err)) + } + ret = append(ret, ds) + } + + return ret, nil +} + +func (d *ClusterRepo) RegisterClusterNode(ctx context.Context, params *biz.ClusterNodeInfo) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(convertBizCLusterNodeInfo(params)).Error; err != nil { + return fmt.Errorf("failed to save cluster_node_info: %v", err) + } + + return nil + }) +} + +func (d *ClusterRepo) GetClusterLeader(ctx context.Context) (*biz.ClusterLeader, error) { + var item *model.ClusterLeader + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find models + if err := tx.WithContext(ctx).Find(&item).Error; err != nil { + return fmt.Errorf("failed to get cluster leader: %v", err) + } + + return nil + }); err != nil { + return nil, err + } + + return convertModelClusterLeader(item) +} + +const leaderTableAnchor = 1 + +func (d *ClusterRepo) MaintainClusterLeader(ctx context.Context, serverId string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + var maintainClusterLeaderSql = ` +INSERT ignore INTO cluster_leaders (anchor, server_id, last_seen_time) VALUES (?, ?, now()) +ON DUPLICATE KEY UPDATE +server_id = IF(last_seen_time < now() - interval 30 second, VALUES(server_id), server_id), +last_seen_time = IF(server_id = VALUES(server_id), VALUES(last_seen_time), last_seen_time) +` + return tx.WithContext(ctx).Exec(maintainClusterLeaderSql, leaderTableAnchor, serverId).Error + }) +} diff --git a/internal/dms/storage/company_notice.go b/internal/dms/storage/company_notice.go new file mode 100644 index 000000000..84f4343d4 --- /dev/null +++ b/internal/dms/storage/company_notice.go @@ -0,0 +1,57 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.CompanyNoticeRepo = (*CompanyNoticeRepo)(nil) + +type CompanyNoticeRepo struct { + *Storage + log *utilLog.Helper +} + +func NewCompanyNoticeRepo(log utilLog.Logger, s *Storage) *CompanyNoticeRepo { + return &CompanyNoticeRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.company_notice"))} +} +func (d *CompanyNoticeRepo) UpdateCompanyNotice(ctx context.Context, cn *biz.CompanyNotice) error { + model, err := convertBizCompanyNotice(cn) + if err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert biz company notice: %w", err)) + } + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(model).Where("uid = ?", model.UID).Omit("created_at").Save(model).Error; err != nil { + return fmt.Errorf("failed to save company notice configuration: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *CompanyNoticeRepo) GetCompanyNotice(ctx context.Context) (*biz.CompanyNotice, error) { + var companyNotice *model.CompanyNotice + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Last(&companyNotice).Error; err != nil { + return fmt.Errorf("failed to get company notice: %v", err) + } + return nil + }); err != nil { + return nil, err + } + ret, err := convertModelCompanyNotice(companyNotice) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model company notice: %w", err)) + } + return ret, nil +} diff --git a/internal/dms/storage/convert.go b/internal/dms/storage/convert.go index 68738cf6b..fac480bb6 100644 --- a/internal/dms/storage/convert.go +++ b/internal/dms/storage/convert.go @@ -1,17 +1,20 @@ package storage import ( + "database/sql" "fmt" "net/url" "strings" "time" + v1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/dms/biz" - pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" "github.com/actiontech/dms/internal/dms/storage/model" + "github.com/labstack/echo/v4/middleware" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" pkgAes "github.com/actiontech/dms/pkg/dms-common/pkg/aes" - "github.com/labstack/echo/v4" ) @@ -23,7 +26,7 @@ func convertBase(o model.Model) biz.Base { } func convertBizDBService(ds *biz.DBService) (*model.DBService, error) { - encrypted, err := pkgAes.AesEncrypt(ds.AdminPassword) + encrypted, err := pkgAes.AesEncrypt(ds.Password) if err != nil { return nil, fmt.Errorf("failed to encrypt password: %w", err) } @@ -33,24 +36,40 @@ func convertBizDBService(ds *biz.DBService) (*model.DBService, error) { }, Name: ds.Name, Desc: ds.Desc, - DBType: ds.DBType.String(), + DBType: ds.DBType, Host: ds.Host, Port: ds.Port, - User: ds.AdminUser, + User: ds.User, Password: encrypted, - Business: ds.Business, AdditionalParams: ds.AdditionalParams, - Source: string(pkgConst.DBServiceSourceNameDMS), + Source: ds.Source, MaintenancePeriod: ds.MaintenancePeriod, - NamespaceUID: ds.NamespaceUID, + ProjectUID: ds.ProjectUID, + EnableBackup: ds.EnableBackup, + BackupMaxRows: ds.BackupMaxRows, + } + if ds.EnvironmentTag != nil { + dbService.EnvironmentTagUID = ds.EnvironmentTag.UID + } + if ds.LastConnectionStatus != nil { + dbService.LastConnectionStatus = (*string)(ds.LastConnectionStatus) + } + if ds.LastConnectionTime != nil { + dbService.LastConnectionTime = ds.LastConnectionTime + } + if ds.LastConnectionErrorMsg != nil { + dbService.LastConnectionErrorMsg = ds.LastConnectionErrorMsg } { // add sqle config if ds.SQLEConfig != nil { dbService.ExtraParameters = model.ExtraParameters{ SqleConfig: &model.SQLEConfig{ - RuleTemplateName: ds.SQLEConfig.RuleTemplateName, - RuleTemplateID: ds.SQLEConfig.RuleTemplateID, + AuditEnabled: ds.SQLEConfig.AuditEnabled, + RuleTemplateName: ds.SQLEConfig.RuleTemplateName, + RuleTemplateID: ds.SQLEConfig.RuleTemplateID, + DataExportRuleTemplateName: ds.SQLEConfig.DataExportRuleTemplateName, + DataExportRuleTemplateID: ds.SQLEConfig.DataExportRuleTemplateID, }, } sqleQueryConfig := ds.SQLEConfig.SQLQueryConfig @@ -58,8 +77,12 @@ func convertBizDBService(ds *biz.DBService) (*model.DBService, error) { dbService.ExtraParameters.SqleConfig.SqlQueryConfig = &model.SqlQueryConfig{ AllowQueryWhenLessThanAuditLevel: sqleQueryConfig.AllowQueryWhenLessThanAuditLevel, AuditEnabled: sqleQueryConfig.AuditEnabled, + WorkflowExecEnabled: sqleQueryConfig.WorkflowExecEnabled, MaxPreQueryRows: sqleQueryConfig.MaxPreQueryRows, QueryTimeoutSecond: sqleQueryConfig.QueryTimeoutSecond, + RuleTemplateName: sqleQueryConfig.RuleTemplateName, + RuleTemplateID: sqleQueryConfig.RuleTemplateID, + MaintenancePeriods: sqleQueryConfig.MaintenancePeriods, } } } @@ -68,44 +91,69 @@ func convertBizDBService(ds *biz.DBService) (*model.DBService, error) { } func convertModelDBService(ds *model.DBService) (*biz.DBService, error) { + if ds == nil { + return nil, nil + } decrypted, err := pkgAes.AesDecrypt(ds.Password) if err != nil { return nil, fmt.Errorf("failed to decrypt password: %v", err) } - dbType, err := pkgConst.ParseDBType(ds.DBType) - if err != nil { - return nil, fmt.Errorf("failed to parse db type: %v", err) - } + dbService := &biz.DBService{ - Base: convertBase(ds.Model), - UID: ds.UID, - Name: ds.Name, - Desc: ds.Desc, - DBType: dbType, - Host: ds.Host, - Port: ds.Port, - AdminUser: ds.User, - AdminPassword: decrypted, - EncryptedAdminPassword: ds.Password, - MaintenancePeriod: ds.MaintenancePeriod, - Business: ds.Business, - AdditionalParams: ds.AdditionalParams, - Source: ds.Source, - NamespaceUID: ds.NamespaceUID, + Base: convertBase(ds.Model), + UID: ds.UID, + Name: ds.Name, + Desc: ds.Desc, + DBType: ds.DBType, + Host: ds.Host, + Port: ds.Port, + User: ds.User, + Password: decrypted, + MaintenancePeriod: ds.MaintenancePeriod, + AdditionalParams: ds.AdditionalParams, + Source: ds.Source, + ProjectUID: ds.ProjectUID, + EnableBackup: ds.EnableBackup, + BackupMaxRows: ds.BackupMaxRows, } + + if ds.LastConnectionStatus != nil { + dbService.LastConnectionStatus = (*biz.LastConnectionStatus)(ds.LastConnectionStatus) + } + if ds.LastConnectionTime != nil { + dbService.LastConnectionTime = ds.LastConnectionTime + } + if ds.LastConnectionErrorMsg != nil { + dbService.LastConnectionErrorMsg = ds.LastConnectionErrorMsg + } + + if ds.EnvironmentTag != nil { + dbService.EnvironmentTag = &dmsCommonV1.EnvironmentTag{ + UID: ds.EnvironmentTagUID, + Name: ds.EnvironmentTag.EnvironmentName, + } + } + { modelSqleConfig := ds.ExtraParameters.SqleConfig if modelSqleConfig != nil { dbService.SQLEConfig = &biz.SQLEConfig{} + dbService.SQLEConfig.AuditEnabled = modelSqleConfig.AuditEnabled dbService.SQLEConfig.RuleTemplateName = modelSqleConfig.RuleTemplateName dbService.SQLEConfig.RuleTemplateID = modelSqleConfig.RuleTemplateID + dbService.SQLEConfig.DataExportRuleTemplateName = modelSqleConfig.DataExportRuleTemplateName + dbService.SQLEConfig.DataExportRuleTemplateID = modelSqleConfig.DataExportRuleTemplateID sqleQueryConfig := modelSqleConfig.SqlQueryConfig if sqleQueryConfig != nil { sqc := &biz.SQLQueryConfig{ AllowQueryWhenLessThanAuditLevel: sqleQueryConfig.AllowQueryWhenLessThanAuditLevel, AuditEnabled: sqleQueryConfig.AuditEnabled, + WorkflowExecEnabled: sqleQueryConfig.WorkflowExecEnabled, MaxPreQueryRows: sqleQueryConfig.MaxPreQueryRows, QueryTimeoutSecond: sqleQueryConfig.QueryTimeoutSecond, + RuleTemplateName: sqleQueryConfig.RuleTemplateName, + RuleTemplateID: sqleQueryConfig.RuleTemplateID, + MaintenancePeriods: sqleQueryConfig.MaintenancePeriods, } dbService.SQLEConfig.SQLQueryConfig = sqc } @@ -129,14 +177,18 @@ func convertBizUser(u *biz.User) (*model.User, error) { Model: model.Model{ UID: u.UID, }, + TwoFactorEnabled: u.TwoFactorEnabled, Name: u.Name, ThirdPartyUserID: u.ThirdPartyUserID, + ThirdPartyUserInfo: u.ThirdPartyUserInfo, Password: encrypted, Email: u.Email, Phone: u.Phone, WeChatID: u.WxID, + Language: u.Language, UserAuthenticationType: u.UserAuthenticationType.String(), Stat: u.Stat.Uint(), + System: string(u.System), LastLoginAt: lastLoginAt, }, nil } @@ -152,12 +204,36 @@ func convertBizCloudbeaverUser(u *biz.CloudbeaverUser) *model.CloudbeaverUserCac func convertBizCloudbeaverConnection(u *biz.CloudbeaverConnection) *model.CloudbeaverConnectionCache { return &model.CloudbeaverConnectionCache{ DMSDBServiceID: u.DMSDBServiceID, + DMSUserID: u.DMSUserId, DMSDBServiceFingerprint: u.DMSDBServiceFingerprint, + Purpose: u.Purpose, CloudbeaverConnectionID: u.CloudbeaverConnectionID, } } +func convertBizBasicConfig(u *biz.BasicConfigParams) *model.BasicConfig { + m := &model.BasicConfig{ + Model: model.Model{UID: u.UID, CreatedAt: u.CreatedAt}, + Title: u.Title, + Logo: u.Logo, + } + + return m +} + +func convertModelBasicConfig(m *model.BasicConfig) *biz.BasicConfigParams { + return &biz.BasicConfigParams{ + Base: convertBase(m.Model), + UID: m.UID, + Title: m.Title, + Logo: m.Logo, + } +} + func convertModelUser(u *model.User) (*biz.User, error) { + if u == nil { + return nil, nil + } decrypted, err := pkgAes.AesDecrypt(u.Password) if err != nil { return nil, fmt.Errorf("failed to decrypt password: %v", err) @@ -176,16 +252,28 @@ func convertModelUser(u *model.User) (*biz.User, error) { lastLoginAt = *u.LastLoginAt } + projects := make([]string, 0) + for _, member := range u.Members { + if member != nil && member.Project != nil { + projects = append(projects, member.Project.Name) + } + } + return &biz.User{ Base: convertBase(u.Model), UID: u.UID, ThirdPartyUserID: u.ThirdPartyUserID, + ThirdPartyUserInfo: u.ThirdPartyUserInfo, Name: u.Name, Email: u.Email, Phone: u.Phone, WxID: u.WeChatID, + Language: u.Language, + Projects: projects, UserAuthenticationType: typ, Stat: stat, + TwoFactorEnabled: u.TwoFactorEnabled, + System: biz.UserSystem(u.System), LastLoginAt: lastLoginAt, Password: decrypted, Deleted: u.DeletedAt.Valid, @@ -205,7 +293,9 @@ func convertModelCloudbeaverConnection(items []*model.CloudbeaverConnectionCache for _, item := range items { res = append(res, &biz.CloudbeaverConnection{ DMSDBServiceID: item.DMSDBServiceID, + DMSUserId: item.DMSUserID, DMSDBServiceFingerprint: item.DMSDBServiceFingerprint, + Purpose: item.Purpose, CloudbeaverConnectionID: item.CloudbeaverConnectionID, }) } @@ -239,6 +329,49 @@ func convertModelUserGroup(u *model.UserGroup) (*biz.UserGroup, error) { }, nil } +func convertModelMemberGroup(mg *model.MemberGroup) (*biz.MemberGroup, error) { + roles := make([]biz.MemberRoleWithOpRange, 0, len(mg.RoleWithOpRanges)) + for _, p := range mg.RoleWithOpRanges { + typ, err := biz.ParseOpRangeType(p.OpRangeType) + if err != nil { + return nil, fmt.Errorf("failed to parse op range type: %v", err) + } + + roles = append(roles, biz.MemberRoleWithOpRange{ + RoleUID: p.RoleUID, + OpRangeType: typ, + RangeUIDs: convertModelRangeUIDs(p.RangeUIDs), + }) + } + + users := make([]biz.UIdWithName, 0, len(mg.Users)) + for _, user := range mg.Users { + users = append(users, biz.UIdWithName{ + Uid: user.UID, + Name: user.Name, + }) + } + + opPermissions := make([]biz.OpPermission, 0) + for _, permission := range mg.OpPermissions { + bizPermission, err := convertModelOpPermission(&permission) + if err != nil { + return nil, err + } + opPermissions = append(opPermissions, *bizPermission) + } + + return &biz.MemberGroup{ + Base: convertBase(mg.Model), + UID: mg.UID, + ProjectUID: mg.ProjectUID, + Name: mg.Name, + Users: users, + RoleWithOpRanges: roles, + OpPermissions: opPermissions, + }, nil +} + func convertBizRole(u *biz.Role) (*model.Role, error) { return &model.Role{ @@ -256,12 +389,22 @@ func convertModelRole(u *model.Role) (*biz.Role, error) { if err != nil { return nil, fmt.Errorf("failed to parse user stat: %v", err) } + opPermissions := make([]*biz.OpPermission, 0, len(u.OpPermissions)) + for _, permission := range u.OpPermissions { + bizPermission, err := convertModelOpPermission(permission) + if err != nil { + return nil, fmt.Errorf("failed to convert model op permission: %v", err) + } + opPermissions = append(opPermissions, bizPermission) + } + return &biz.Role{ - Base: convertBase(u.Model), - UID: u.UID, - Name: u.Name, - Desc: u.Desc, - Stat: stat, + Base: convertBase(u.Model), + UID: u.UID, + Name: u.Name, + Desc: u.Desc, + Stat: stat, + OpPermissions: opPermissions, }, nil } @@ -274,6 +417,8 @@ func convertBizOpPermission(u *biz.OpPermission) (*model.OpPermission, error) { Name: u.Name, Desc: u.Desc, RangeType: u.RangeType.String(), + Module: string(u.Module), + Service: string(u.Service), }, nil } @@ -284,6 +429,8 @@ func convertModelOpPermission(u *model.OpPermission) (*biz.OpPermission, error) Name: u.Name, Desc: u.Desc, RangeType: biz.OpRangeType(u.RangeType), + Module: biz.Module(u.Module), + Service: v1.Service(u.Service), }, nil } @@ -293,21 +440,23 @@ func convertBizDMSConfig(u *biz.DMSConfig) (*model.DMSConfig, error) { Model: model.Model{ UID: u.UID, }, - NeedInitOpPermissions: u.NeedInitOpPermissions, - NeedInitUsers: u.NeedInitUsers, - NeedInitRoles: u.NeedInitRoles, - NeedInitNamespaces: u.NeedInitNamespaces, + NeedInitOpPermissions: u.NeedInitOpPermissions, + NeedInitUsers: u.NeedInitUsers, + NeedInitRoles: u.NeedInitRoles, + NeedInitProjects: u.NeedInitProjects, + EnableSQLResultSetsDataMasking: u.EnableSQLResultSetsDataMasking, }, nil } func convertModelDMSConfig(u *model.DMSConfig) (*biz.DMSConfig, error) { return &biz.DMSConfig{ - Base: convertBase(u.Model), - UID: u.UID, - NeedInitOpPermissions: u.NeedInitOpPermissions, - NeedInitUsers: u.NeedInitUsers, - NeedInitRoles: u.NeedInitRoles, - NeedInitNamespaces: u.NeedInitNamespaces, + Base: convertBase(u.Model), + UID: u.UID, + NeedInitOpPermissions: u.NeedInitOpPermissions, + NeedInitUsers: u.NeedInitUsers, + NeedInitRoles: u.NeedInitRoles, + NeedInitProjects: u.NeedInitProjects, + EnableSQLResultSetsDataMasking: u.EnableSQLResultSetsDataMasking, }, nil } @@ -327,11 +476,44 @@ func convertBizMember(m *biz.Member) (*model.Member, error) { UID: m.UID, }, UserUID: m.UserUID, - NamespaceUID: m.NamespaceUID, + ProjectUID: m.ProjectUID, RoleWithOpRanges: roles, }, nil } +func convertBizMemberGroup(m *biz.MemberGroup) *model.MemberGroup { + roles := make([]model.MemberGroupRoleOpRange, 0, len(m.RoleWithOpRanges)) + for _, p := range m.RoleWithOpRanges { + roles = append(roles, model.MemberGroupRoleOpRange{ + MemberGroupUID: m.UID, + RoleUID: p.RoleUID, + OpRangeType: p.OpRangeType.String(), + RangeUIDs: convertBizRangeUIDs(p.RangeUIDs), + }) + } + + var users []*model.User + for _, uid := range m.UserUids { + users = append(users, &model.User{Model: model.Model{UID: uid}}) + } + var opPermissions []model.OpPermission + for _, permissionUid := range m.ProjectManagePermissions { + opPermissions = append(opPermissions, model.OpPermission{Model: model.Model{UID: permissionUid}}) + } + + return &model.MemberGroup{ + Model: model.Model{ + UID: m.UID, + CreatedAt: m.CreatedAt, + }, + Name: m.Name, + ProjectUID: m.ProjectUID, + RoleWithOpRanges: roles, + Users: users, + OpPermissions: opPermissions, + } +} + func convertModelMember(m *model.Member) (*biz.Member, error) { roles := make([]biz.MemberRoleWithOpRange, 0, len(m.RoleWithOpRanges)) for _, p := range m.RoleWithOpRanges { @@ -345,12 +527,30 @@ func convertModelMember(m *model.Member) (*biz.Member, error) { RangeUIDs: convertModelRangeUIDs(p.RangeUIDs), }) } + projects := make([]string, 0) + if m.User != nil && len(m.User.Members) > 0 { + for _, member := range m.User.Members { + if member.Project != nil { + projects = append(projects, member.Project.Name) + } + } + } + opPermissions := make([]biz.OpPermission, 0) + for _, permission := range m.OpPermissions { + bizPermission, err := convertModelOpPermission(permission) + if err != nil { + return nil, err + } + opPermissions = append(opPermissions, *bizPermission) + } return &biz.Member{ Base: convertBase(m.Model), UID: m.UID, - NamespaceUID: m.NamespaceUID, + ProjectUID: m.ProjectUID, + Projects: projects, UserUID: m.UserUID, RoleWithOpRanges: roles, + OpPermissions: opPermissions, }, nil } @@ -362,38 +562,53 @@ func convertModelRangeUIDs(uids string) []string { return strings.Split(uids, ",") } -func convertBizNamespace(m *biz.Namespace) (*model.Namespace, error) { - return &model.Namespace{ +func convertBizProject(m *biz.Project) *model.Project { + return &model.Project{ Model: model.Model{ UID: m.UID, }, - Name: m.Name, - Desc: m.Desc, - Status: string(m.Status), - CreateUserUID: m.CreateUserUID, - }, nil + Name: m.Name, + Desc: m.Desc, + BusinessTagUID: m.BusinessTag.UID, + Status: string(m.Status), + CreateUserUID: m.CreateUserUID, + Priority: dmsCommonV1.ToPriorityNum(m.Priority), + } } -func convertModelNamespace(m *model.Namespace) (*biz.Namespace, error) { - return &biz.Namespace{ +func convertModelProject(m *model.Project) (*biz.Project, error) { + return &biz.Project{ Base: convertBase(m.Model), UID: m.UID, Name: m.Name, Desc: m.Desc, - Status: convertModelNamespaceStatus(m.Status), + BusinessTag: biz.BusinessTag{UID: m.BusinessTagUID}, + Status: convertModelProjectStatus(m.Status), CreateUserUID: m.CreateUserUID, CreateTime: m.CreatedAt, + Priority: dmsCommonV1.ToPriority(m.Priority), }, nil } -func convertModelNamespaceStatus(status string) biz.NamespaceStatus { +func convertModelProjectStatus(status string) biz.ProjectStatus { switch status { - case string(biz.NamespaceStatusActive): - return biz.NamespaceStatusActive - case string(biz.NamespaceStatusArchived): - return biz.NamespaceStatusArchived + case string(biz.ProjectStatusActive): + return biz.ProjectStatusActive + case string(biz.ProjectStatusArchived): + return biz.ProjectStatusArchived + default: + return biz.ProjectStatusUnknown + } +} + +func convertModelProxyScenario(scenario string) biz.ProxyScenario { + switch scenario { + case "internal_service": + return biz.ProxyScenarioInternalService + case "thrid_party_integrate": + return biz.ProxyScenarioThirdPartyIntegrate default: - return biz.NamespaceStatusUnknown + return biz.ProxyScenarioUnknown } } @@ -401,7 +616,9 @@ func convertBizProxyTarget(t *biz.ProxyTarget) (*model.ProxyTarget, error) { return &model.ProxyTarget{ Name: t.Name, Url: t.URL.String(), + Version: t.Version, ProxyUrlPrefixs: strings.Join(t.GetProxyUrlPrefixs(), ";"), + Scenario: string(t.Scenario), }, nil } @@ -411,9 +628,13 @@ func convertModelProxyTarget(t *model.ProxyTarget) (*biz.ProxyTarget, error) { return nil, fmt.Errorf("invalid url: %s", t.Url) } p := &biz.ProxyTarget{ - Name: t.Name, - URL: url, - Meta: echo.Map{}, + ProxyTarget: middleware.ProxyTarget{ + Name: t.Name, + URL: url, + Meta: echo.Map{}, + }, + Version: t.Version, + Scenario: convertModelProxyScenario(t.Scenario), } p.SetProxyUrlPrefix(strings.Split(t.ProxyUrlPrefixs, ";")) return p, nil @@ -422,48 +643,109 @@ func convertModelProxyTarget(t *model.ProxyTarget) (*biz.ProxyTarget, error) { func convertBizPlugin(t *biz.Plugin) (*model.Plugin, error) { return &model.Plugin{ Name: t.Name, - AddDBServicePreCheckUrl: t.AddDBServicePreCheckUrl, - DelDBServicePreCheckUrl: t.DelDBServicePreCheckUrl, - DelUserPreCheckUrl: t.DelUserPreCheckUrl, - DelUserGroupPreCheckUrl: t.DelUserGroupPreCheckUrl, OperateDataResourceHandleUrl: t.OperateDataResourceHandleUrl, + GetDatabaseDriverOptionsUrl: t.GetDatabaseDriverOptionsUrl, + GetDatabaseDriverLogosUrl: t.GetDatabaseDriverLogosUrl, }, nil } func convertModelPlugin(t *model.Plugin) (*biz.Plugin, error) { p := &biz.Plugin{ Name: t.Name, - AddDBServicePreCheckUrl: t.AddDBServicePreCheckUrl, - DelDBServicePreCheckUrl: t.DelDBServicePreCheckUrl, - DelUserPreCheckUrl: t.DelUserPreCheckUrl, - DelUserGroupPreCheckUrl: t.DelUserGroupPreCheckUrl, OperateDataResourceHandleUrl: t.OperateDataResourceHandleUrl, + GetDatabaseDriverOptionsUrl: t.GetDatabaseDriverOptionsUrl, + GetDatabaseDriverLogosUrl: t.GetDatabaseDriverLogosUrl, } return p, nil } +func convertBizOAuth2Session(s *biz.OAuth2Session) (*model.OAuth2Session, error) { + return &model.OAuth2Session{ + Model: model.Model{ + UID: s.UID, + CreatedAt: s.CreatedAt, + UpdatedAt: s.UpdatedAt, + }, + UserUID: s.UserUID, + Sub: s.Sub, + Sid: s.Sid, + IdToken: s.IdToken, + RefreshToken: s.RefreshToken, + LastLogoutEvent: sql.NullString{String: s.LastLogoutEvent, Valid: true}, + DeleteAfter: s.DeleteAfter, + }, nil +} + +func convertModelOAuth2Session(m *model.OAuth2Session) (*biz.OAuth2Session, error) { + return &biz.OAuth2Session{ + Base: convertBase(m.Model), + UID: m.UID, + UserUID: m.UserUID, + Sub: m.Sub, + Sid: m.Sid, + IdToken: m.IdToken, + RefreshToken: m.RefreshToken, + LastLogoutEvent: m.LastLogoutEvent.String, + DeleteAfter: m.DeleteAfter, + }, nil +} + +func convertBizLoginConfiguration(b *biz.LoginConfiguration) (*model.LoginConfiguration, error) { + return &model.LoginConfiguration{ + Model: model.Model{ + UID: b.UID, + }, + LoginButtonText: b.LoginButtonText, + DisableUserPwdLogin: b.DisableUserPwdLogin, + }, nil +} + +func convertModelLoginConfiguration(m *model.LoginConfiguration) (*biz.LoginConfiguration, error) { + return &biz.LoginConfiguration{ + Base: convertBase(m.Model), + UID: m.UID, + LoginButtonText: m.LoginButtonText, + DisableUserPwdLogin: m.DisableUserPwdLogin, + }, nil +} + func convertBizOauth2Configuration(b *biz.Oauth2Configuration) (*model.Oauth2Configuration, error) { data, err := pkgAes.AesEncrypt(b.ClientKey) if err != nil { return nil, err } + pwd, err := pkgAes.AesEncrypt(b.AutoCreateUserPWD) + if err != nil { + return nil, err + } b.ClientSecret = data + b.AutoCreateUserSecret = pwd return &model.Oauth2Configuration{ Model: model.Model{ UID: b.UID, }, - EnableOauth2: b.EnableOauth2, - ClientID: b.ClientID, - ClientKey: b.ClientKey, - ClientSecret: b.ClientSecret, - ClientHost: b.ClientHost, - ServerAuthUrl: b.ServerAuthUrl, - ServerTokenUrl: b.ServerTokenUrl, - ServerUserIdUrl: b.ServerUserIdUrl, - Scopes: strings.Join(b.Scopes, ","), - AccessTokenTag: b.AccessTokenTag, - UserIdTag: b.UserIdTag, - LoginTip: b.LoginTip, + EnableOauth2: b.EnableOauth2, + SkipCheckState: b.SkipCheckState, + EnableManuallyBind: b.EnableManuallyBind, + AutoBindSameNameUser: b.AutoBindSameNameUser, + AutoCreateUser: b.AutoCreateUser, + AutoCreateUserPWD: b.AutoCreateUserPWD, + AutoCreateUserSecret: b.AutoCreateUserSecret, + ClientID: b.ClientID, + ClientKey: b.ClientKey, + ClientSecret: b.ClientSecret, + ClientHost: b.ClientHost, + ServerAuthUrl: b.ServerAuthUrl, + ServerTokenUrl: b.ServerTokenUrl, + ServerUserIdUrl: b.ServerUserIdUrl, + ServerLogoutUrl: b.ServerLogoutUrl, + Scopes: strings.Join(b.Scopes, ","), + AccessTokenTag: b.AccessTokenTag, + UserIdTag: b.UserIdTag, + LoginTip: b.LoginTip, + UserWeChatTag: b.UserWeChatTag, + UserEmailTag: b.UserEmailTag, + LoginPermExpr: b.LoginPermExpr, }, nil } @@ -476,21 +758,39 @@ func convertModelOauth2Configuration(m *model.Oauth2Configuration) (*biz.Oauth2C m.ClientKey = data } } + if m.AutoCreateUserPWD == "" { + data, err := pkgAes.AesDecrypt(m.AutoCreateUserSecret) + if err != nil { + return nil, err + } else { + m.AutoCreateUserPWD = data + } + } p := &biz.Oauth2Configuration{ - Base: convertBase(m.Model), - UID: m.UID, - EnableOauth2: m.EnableOauth2, - ClientID: m.ClientID, - ClientKey: m.ClientKey, - ClientSecret: m.ClientSecret, - ClientHost: m.ClientHost, - ServerAuthUrl: m.ServerAuthUrl, - ServerTokenUrl: m.ServerTokenUrl, - ServerUserIdUrl: m.ServerUserIdUrl, - Scopes: strings.Split(m.Scopes, ","), - AccessTokenTag: m.AccessTokenTag, - UserIdTag: m.UserIdTag, - LoginTip: m.LoginTip, + Base: convertBase(m.Model), + UID: m.UID, + EnableOauth2: m.EnableOauth2, + SkipCheckState: m.SkipCheckState, + EnableManuallyBind: m.EnableManuallyBind, + AutoBindSameNameUser: m.AutoBindSameNameUser, + AutoCreateUser: m.AutoCreateUser, + AutoCreateUserPWD: m.AutoCreateUserPWD, + AutoCreateUserSecret: m.AutoCreateUserSecret, + ClientID: m.ClientID, + ClientKey: m.ClientKey, + ClientSecret: m.ClientSecret, + ClientHost: m.ClientHost, + ServerAuthUrl: m.ServerAuthUrl, + ServerTokenUrl: m.ServerTokenUrl, + ServerUserIdUrl: m.ServerUserIdUrl, + ServerLogoutUrl: m.ServerLogoutUrl, + Scopes: strings.Split(m.Scopes, ","), + AccessTokenTag: m.AccessTokenTag, + UserIdTag: m.UserIdTag, + LoginTip: m.LoginTip, + UserWeChatTag: m.UserWeChatTag, + UserEmailTag: m.UserEmailTag, + LoginPermExpr: m.LoginPermExpr, } return p, nil } @@ -682,3 +982,401 @@ func convertModelIMConfigType(_type string) biz.ImType { return biz.ImTypeUnknow } } + +func convertBizCompanyNotice(b *biz.CompanyNotice) (*model.CompanyNotice, error) { + return &model.CompanyNotice{ + Model: model.Model{ + UID: b.UID, + }, + CreateUserUID: b.CreateUserUID, + NoticeStr: b.NoticeStr, + ReadUserIds: b.ReadUserIds, + StartTime: b.StartTime, + EndTime: b.EndTime, + }, nil +} + +func convertModelCompanyNotice(m *model.CompanyNotice) (*biz.CompanyNotice, error) { + p := &biz.CompanyNotice{ + Base: convertBase(m.Model), + UID: m.UID, + CreateUserUID: m.CreateUserUID, + NoticeStr: m.NoticeStr, + ReadUserIds: m.ReadUserIds, + StartTime: m.StartTime, + EndTime: m.EndTime, + } + + return p, nil +} + +func convertModelClusterLeader(m *model.ClusterLeader) (*biz.ClusterLeader, error) { + return &biz.ClusterLeader{ + Anchor: m.Anchor, + ServerId: m.ServerId, + LastSeenTime: m.LastSeenTime, + }, nil +} + +func convertBizCLusterNodeInfo(b *biz.ClusterNodeInfo) *model.ClusterNodeInfo { + return &model.ClusterNodeInfo{ + ServerId: b.ServerId, + HardwareSign: b.HardwareSign, + } +} + +func convertModelClusterNodeInfo(m *model.ClusterNodeInfo) (*biz.ClusterNodeInfo, error) { + return &biz.ClusterNodeInfo{ + ServerId: m.ServerId, + HardwareSign: m.HardwareSign, + }, nil +} + +func convertBizWorkflow(b *biz.Workflow) *model.Workflow { + workflow := &model.Workflow{ + Model: model.Model{ + UID: b.UID, + }, + Name: b.Name, + ProjectUID: b.ProjectUID, + WorkflowType: b.WorkflowType, + Desc: b.Desc, + CreateTime: &b.CreateTime, + CreateUserUID: b.CreateUserUID, + WorkflowRecordUid: b.WorkflowRecordUid, + } + if b.WorkflowRecord != nil { + workflow.WorkflowRecord = convertBizWorkflowRecord(b.WorkflowRecord) + } + return workflow +} + +func convertModelWorkflow(m *model.Workflow) (w *biz.Workflow, err error) { + w = &biz.Workflow{ + Base: convertBase(m.Model), + + UID: m.UID, + Name: m.Name, + ProjectUID: m.ProjectUID, + WorkflowType: m.WorkflowType, + Desc: m.Desc, + CreateTime: *m.CreateTime, + CreateUserUID: m.CreateUserUID, + WorkflowRecordUid: m.WorkflowRecordUid, + TaskIds: m.GetTaskIds(), + } + if m.WorkflowRecord != nil { + w.WorkflowRecord, err = convertModelWorkflowRecord(m.WorkflowRecord) + if err != nil { + return w, err + } + w.Status = m.WorkflowRecord.Status + for _, taskId := range m.WorkflowRecord.TaskIds { + w.WorkflowRecord.Tasks = append(w.WorkflowRecord.Tasks, biz.Task{UID: taskId}) + } + } + + return w, nil +} + +func convertBizWorkflowRecord(b *biz.WorkflowRecord) *model.WorkflowRecord { + var taskIds model.Strings + for _, task := range b.Tasks { + taskIds = append(taskIds, task.UID) + } + workflowRecord := &model.WorkflowRecord{ + Model: model.Model{ + UID: b.UID, + }, + CurrentWorkflowStepId: b.CurrentWorkflowStepId, + Status: b.Status.String(), + TaskIds: taskIds, + } + if b.WorkflowSteps != nil { + for _, step := range b.WorkflowSteps { + workflowRecord.Steps = append(workflowRecord.Steps, convertBizWorkflowStep(step)) + } + } + return workflowRecord +} + +func convertModelWorkflowRecord(m *model.WorkflowRecord) (wr *biz.WorkflowRecord, err error) { + wr = &biz.WorkflowRecord{ + UID: m.UID, + Status: biz.DataExportWorkflowStatus(m.Status), + Tasks: make([]biz.Task, 0), + CurrentWorkflowStepId: m.CurrentWorkflowStepId, + CurrentStep: convertModelWorkflowStep(m, m.CurrentWorkflowStepId), + } + + if len(m.Steps) != 0 { + wr.CurrentStep = convertModelWorkflowStep(m, m.CurrentWorkflowStepId) + } + if m.Steps != nil { + wr.WorkflowSteps = make([]*biz.WorkflowStep, 0) + for _, step := range m.Steps { + wr.WorkflowSteps = append(wr.WorkflowSteps, &biz.WorkflowStep{ + StepId: step.StepId, + WorkflowRecordUid: step.WorkflowRecordUid, + OperationUserUid: step.OperationUserUid, + OperateAt: step.OperateAt, + State: step.State, + Reason: step.Reason, + Assignees: step.Assignees, + }) + } + } + return wr, nil +} + +func convertBizWorkflowStep(b *biz.WorkflowStep) *model.WorkflowStep { + return &model.WorkflowStep{ + StepId: b.StepId, + WorkflowRecordUid: b.WorkflowRecordUid, + OperationUserUid: b.OperationUserUid, + OperateAt: b.OperateAt, + State: b.State, + Reason: b.Reason, + Assignees: b.Assignees, + } +} + +func convertModelWorkflowStep(workflowRecord *model.WorkflowRecord, currentWorkflowStepId uint64) *biz.WorkflowStep { + if len(workflowRecord.Steps) == 0 { + return nil + } + for _, step := range workflowRecord.Steps { + if step.StepId == currentWorkflowStepId { + return &biz.WorkflowStep{ + StepId: step.StepId, + WorkflowRecordUid: step.WorkflowRecordUid, + OperationUserUid: step.OperationUserUid, + OperateAt: step.OperateAt, + State: step.State, + Reason: step.Reason, + Assignees: step.Assignees, + } + } + } + return nil +} + +func convertBizDataExportTask(b *biz.DataExportTask) *model.DataExportTask { + dataExportTask := &model.DataExportTask{ + Model: model.Model{UID: b.UID}, + CreateUserUID: b.CreateUserUID, + DBServiceUid: b.DBServiceUid, + DatabaseName: b.DatabaseName, + WorkFlowRecordUid: b.WorkFlowRecordUid, + ExportType: b.ExportType, + ExportFileType: b.ExportFileType, + ExportFileName: b.ExportFileName, + ExportStatus: b.ExportStatus.String(), + ExportStartTime: b.ExportStartTime, + ExportEndTime: b.ExportEndTime, + AuditPassRate: b.AuditPassRate, + AuditScore: b.AuditScore, + AuditLevel: b.AuditLevel, + } + if b.DataExportTaskRecords != nil { + for _, record := range b.DataExportTaskRecords { + dataExportTask.DataExportTaskRecords = append(dataExportTask.DataExportTaskRecords, convertBizDataExportTaskRecords(record)) + } + + } + return dataExportTask +} + +func convertModelDataExportTask(m *model.DataExportTask) *biz.DataExportTask { + w := &biz.DataExportTask{ + Base: convertBase(m.Model), + UID: m.UID, + DBServiceUid: m.DBServiceUid, + CreateUserUID: m.CreateUserUID, + DatabaseName: m.DatabaseName, + WorkFlowRecordUid: m.WorkFlowRecordUid, + ExportType: m.ExportType, + ExportFileType: m.ExportFileType, + ExportFileName: m.ExportFileName, + AuditPassRate: m.AuditPassRate, + AuditScore: m.AuditScore, + AuditLevel: m.AuditLevel, + ExportStatus: biz.DataExportTaskStatus(m.ExportStatus), + ExportStartTime: m.ExportStartTime, + ExportEndTime: m.ExportEndTime, + } + if m.DataExportTaskRecords != nil { + for _, r := range m.DataExportTaskRecords { + w.DataExportTaskRecords = append(w.DataExportTaskRecords, convertModelDataExportTaskRecords(r)) + } + + } + return w +} + +func convertBizDataExportTaskRecords(b *biz.DataExportTaskRecord) *model.DataExportTaskRecord { + m := &model.DataExportTaskRecord{ + Number: b.Number, + DataExportTaskId: b.DataExportTaskId, + ExportSQL: b.ExportSQL, + ExportSQLType: b.ExportSQLType, + ExportResult: b.ExportResult, + AuditLevel: b.AuditLevel, + AuditResults: b.AuditSQLResults, + } + return m +} + +func convertModelDataExportTaskRecords(m *model.DataExportTaskRecord) *biz.DataExportTaskRecord { + b := &biz.DataExportTaskRecord{ + Number: m.Number, + DataExportTaskId: m.DataExportTaskId, + ExportSQL: m.ExportSQL, + ExportSQLType: m.ExportSQLType, + AuditLevel: m.AuditLevel, + ExportResult: m.ExportResult, + AuditSQLResults: m.AuditResults, + } + return b +} + +func convertBizCbOperationLog(src *biz.CbOperationLog) *model.CbOperationLog { + return &model.CbOperationLog{ + Model: model.Model{ + UID: src.UID, + }, + ProjectID: src.ProjectID, + OpPersonUID: src.OpPersonUID, + OpTime: src.OpTime, + DBServiceUID: src.DBServiceUID, + OpType: string(src.OpType), + I18nOpDetail: src.I18nOpDetail, + OpSessionID: src.OpSessionID, + OpHost: src.OpHost, + AuditResult: src.AuditResults, + IsAuditPassed: src.IsAuditPass, + ExecResult: src.ExecResult, + ExecTotalSec: src.ExecTotalSec, + ResultSetRowCount: src.ResultSetRowCount, + WorkflowID: src.WorkflowID, + } +} + +func convertModelCbOperationLog(model *model.CbOperationLog) (*biz.CbOperationLog, error) { + user, err := convertModelUser(model.User) + if err != nil { + return nil, err + } + + dbService, err := convertModelDBService(model.DbService) + if err != nil { + return nil, err + } + + project, err := convertModelProject(model.Project) + if err != nil { + return nil, err + } + + return &biz.CbOperationLog{ + UID: model.UID, + ProjectID: model.ProjectID, + OpPersonUID: model.OpPersonUID, + OpTime: model.OpTime, + DBServiceUID: model.DBServiceUID, + OpType: biz.CbOperationLogType(model.OpType), + I18nOpDetail: model.I18nOpDetail, + OpSessionID: model.OpSessionID, + OpHost: model.OpHost, + AuditResults: model.AuditResult, + IsAuditPass: model.IsAuditPassed, + ExecResult: model.ExecResult, + ExecTotalSec: model.ExecTotalSec, + ResultSetRowCount: model.ResultSetRowCount, + WorkflowID: model.WorkflowID, + User: user, + DbService: dbService, + Project: project, + }, nil +} + +func toModelDBServiceSyncTask(u *biz.DBServiceSyncTask) *model.DBServiceSyncTask { + ret := &model.DBServiceSyncTask{ + Model: model.Model{UID: u.UID}, + Name: u.Name, + Source: u.Source, + URL: u.URL, + DbType: u.DbType, + CronExpress: u.CronExpress, + LastSyncErr: u.LastSyncErr, + LastSyncSuccessTime: u.LastSyncSuccessTime, + } + if u.LastSyncSuccessTime != nil { + ret.LastSyncSuccessTime = u.LastSyncSuccessTime + } + if u.SQLEConfig != nil { + ret.ExtraParameters.SqleConfig = &model.SQLEConfig{ + AuditEnabled: u.SQLEConfig.AuditEnabled, + RuleTemplateName: u.SQLEConfig.RuleTemplateName, + RuleTemplateID: u.SQLEConfig.RuleTemplateID, + DataExportRuleTemplateName: u.SQLEConfig.DataExportRuleTemplateName, + DataExportRuleTemplateID: u.SQLEConfig.DataExportRuleTemplateID, + } + if u.SQLEConfig.SQLQueryConfig != nil { + ret.ExtraParameters.SqleConfig.SqlQueryConfig = &model.SqlQueryConfig{ + MaxPreQueryRows: u.SQLEConfig.SQLQueryConfig.QueryTimeoutSecond, + QueryTimeoutSecond: u.SQLEConfig.SQLQueryConfig.QueryTimeoutSecond, + AuditEnabled: u.SQLEConfig.SQLQueryConfig.AuditEnabled, + WorkflowExecEnabled: u.SQLEConfig.SQLQueryConfig.WorkflowExecEnabled, + AllowQueryWhenLessThanAuditLevel: u.SQLEConfig.SQLQueryConfig.AllowQueryWhenLessThanAuditLevel, + RuleTemplateName: u.SQLEConfig.SQLQueryConfig.RuleTemplateName, + RuleTemplateID: u.SQLEConfig.SQLQueryConfig.RuleTemplateID, + MaintenancePeriods: u.SQLEConfig.SQLQueryConfig.MaintenancePeriods, + } + } + } + if u.AdditionalParam != nil { + ret.ExtraParameters.AdditionalParam = u.AdditionalParam + } + return ret +} + +func toBizDBServiceSyncTask(m *model.DBServiceSyncTask) *biz.DBServiceSyncTask { + ret := &biz.DBServiceSyncTask{ + UID: m.UID, + Name: m.Name, + Source: m.Source, + URL: m.URL, + DbType: m.DbType, + CronExpress: m.CronExpress, + LastSyncErr: m.LastSyncErr, + } + if m.LastSyncSuccessTime != nil { + ret.LastSyncSuccessTime = m.LastSyncSuccessTime + } + if m.ExtraParameters.SqleConfig != nil { + ret.SQLEConfig = &biz.SQLEConfig{ + AuditEnabled: m.ExtraParameters.SqleConfig.AuditEnabled, + RuleTemplateName: m.ExtraParameters.SqleConfig.RuleTemplateName, + RuleTemplateID: m.ExtraParameters.SqleConfig.RuleTemplateID, + DataExportRuleTemplateName: m.ExtraParameters.SqleConfig.DataExportRuleTemplateName, + DataExportRuleTemplateID: m.ExtraParameters.SqleConfig.DataExportRuleTemplateID, + } + if m.ExtraParameters.SqleConfig.SqlQueryConfig != nil { + ret.SQLEConfig.SQLQueryConfig = &biz.SQLQueryConfig{ + MaxPreQueryRows: m.ExtraParameters.SqleConfig.SqlQueryConfig.QueryTimeoutSecond, + QueryTimeoutSecond: m.ExtraParameters.SqleConfig.SqlQueryConfig.QueryTimeoutSecond, + AuditEnabled: m.ExtraParameters.SqleConfig.SqlQueryConfig.AuditEnabled, + WorkflowExecEnabled: m.ExtraParameters.SqleConfig.SqlQueryConfig.WorkflowExecEnabled, + AllowQueryWhenLessThanAuditLevel: m.ExtraParameters.SqleConfig.SqlQueryConfig.AllowQueryWhenLessThanAuditLevel, + RuleTemplateName: m.ExtraParameters.SqleConfig.SqlQueryConfig.RuleTemplateName, + RuleTemplateID: m.ExtraParameters.SqleConfig.SqlQueryConfig.RuleTemplateID, + MaintenancePeriods: m.ExtraParameters.SqleConfig.SqlQueryConfig.MaintenancePeriods, + } + } + } + if m.ExtraParameters.AdditionalParam != nil { + ret.AdditionalParam = m.ExtraParameters.AdditionalParam + } + return ret +} diff --git a/internal/dms/storage/data_export_task.go b/internal/dms/storage/data_export_task.go new file mode 100644 index 000000000..f116fd5e3 --- /dev/null +++ b/internal/dms/storage/data_export_task.go @@ -0,0 +1,189 @@ +package storage + +import ( + "context" + "fmt" + "time" + + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.DataExportTaskRepo = (*DataExportTaskRepo)(nil) + +type DataExportTaskRepo struct { + *Storage + log *utilLog.Helper +} + +func NewDataExportTaskRepo(log utilLog.Logger, s *Storage) *DataExportTaskRepo { + return &DataExportTaskRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.dataExportTask"))} +} + +func (d *DataExportTaskRepo) SaveDataExportTask(ctx context.Context, dataExportDataExportTasks []*biz.DataExportTask) error { + models := make([]*model.DataExportTask, 0) + for _, dataExportDataExportTask := range dataExportDataExportTasks { + models = append(models, convertBizDataExportTask(dataExportDataExportTask)) + } + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(models).Error; err != nil { + return fmt.Errorf("failed to save data export task: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *DataExportTaskRepo) GetDataExportTaskByIds(ctx context.Context, ids []string) (dataExportDataExportTasks []*biz.DataExportTask, err error) { + tasks := make([]*model.DataExportTask, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Preload("DataExportTaskRecords").Find(&tasks, "uid in (?)", ids).Error; err != nil { + return fmt.Errorf("failed to get data export tasks: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + ret := make([]*biz.DataExportTask, 0) + for _, v := range tasks { + ret = append(ret, convertModelDataExportTask(v)) + } + + return ret, nil +} + +func (d *DataExportTaskRepo) ListDataExportTaskRecord(ctx context.Context, opt *biz.ListDataExportTaskRecordOption) (exportTaskRecords []*biz.DataExportTaskRecord, total int64, err error) { + var models []*model.DataExportTaskRecord + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + + // find models + { + db := tx.WithContext(ctx).Order(opt.OrderBy) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + if err := db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to list data export task records: %v", err) + } + } + + // find total + { + db := tx.WithContext(ctx).Model(&model.DataExportTaskRecord{}) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count data export task records: %v", err) + } + } + return nil + }); err != nil { + return nil, 0, err + } + + // convert model to biz + for _, model := range models { + exportTaskRecords = append(exportTaskRecords, convertModelDataExportTaskRecords(model)) + } + return exportTaskRecords, total, nil +} + +func (d *DataExportTaskRepo) BatchUpdateDataExportTaskStatusByIds(ctx context.Context, ids []string, status biz.DataExportTaskStatus) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.DataExportTask{}).Where("uid in (?)", ids).Update("export_status", status).Error; err != nil { + return fmt.Errorf("failed to update data export task status: %v", err) + } + + return nil + }) +} + +func (d *DataExportTaskRepo) ListDataExportTasks(ctx context.Context, opt *biz.ListDataExportTaskOption) (exportTasks []*biz.DataExportTask, total int64, err error) { + var models []*model.DataExportTask + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + + // find models + { + db := tx.WithContext(ctx).Order(opt.OrderBy) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + if err := db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to list data export task: %v", err) + } + } + + // find total + { + db := tx.WithContext(ctx).Model(&model.DataExportTask{}) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count data export task: %v", err) + } + } + return nil + }); err != nil { + return nil, 0, err + } + + // convert model to biz + for _, model := range models { + exportTasks = append(exportTasks, convertModelDataExportTask(model)) + } + return exportTasks, total, nil +} + +func (d *DataExportTaskRepo) DeleteUnusedDataExportTasks(ctx context.Context) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + err := tx.Exec(`DELETE det,detr + FROM data_export_tasks det + LEFT JOIN data_export_task_records detr ON det.uid = detr.data_export_task_id + WHERE det.uid NOT IN ( + SELECT uid FROM ( + SELECT det.uid + FROM data_export_tasks det + JOIN workflow_records wr ON JSON_SEARCH(wr.task_ids, "one", det.uid) IS NOT NULL + ) AS subquery + ) + AND det.created_at < ? + `, time.Now().Add(-time.Hour*24)).Error + if err != nil { + return err + } + + return nil + }) +} + +func (d *DataExportTaskRepo) BatchUpdateDataExportTaskByIds(ctx context.Context, ids []string, args map[string]interface{}) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.DataExportTask{}).Where("uid in (?)", ids).Updates(args).Error; err != nil { + return fmt.Errorf("failed to update data export task: %v", err) + } + return nil + }) +} + +func (d *DataExportTaskRepo) SaveDataExportTaskRecords(ctx context.Context, dataExportTaskRecords []*biz.DataExportTaskRecord) error { + models := make([]*model.DataExportTaskRecord, 0) + for _, dataExportTaskRecord := range dataExportTaskRecords { + models = append(models, convertBizDataExportTaskRecords(dataExportTaskRecord)) + } + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(models).Error; err != nil { + return fmt.Errorf("failed to save data export task records: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} diff --git a/internal/dms/storage/db_service.go b/internal/dms/storage/db_service.go index 22dccea13..d0f092c19 100644 --- a/internal/dms/storage/db_service.go +++ b/internal/dms/storage/db_service.go @@ -3,8 +3,10 @@ package storage import ( "context" "fmt" + "strings" "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" "github.com/actiontech/dms/internal/dms/storage/model" @@ -23,14 +25,22 @@ func NewDBServiceRepo(log utilLog.Logger, s *Storage) *DBServiceRepo { return &DBServiceRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.db_service"))} } -func (d *DBServiceRepo) SaveDBService(ctx context.Context, ds *biz.DBService) error { - model, err := convertBizDBService(ds) - if err != nil { - return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert biz db service: %w", err)) +func (d *DBServiceRepo) SaveDBServices(ctx context.Context, ds []*biz.DBService) error { + var err error + models := make([]*model.DBService, len(ds)) + for k, v := range ds { + if v == nil { + return fmt.Errorf("invalid DBService: %v", ds) + } + models[k], err = convertBizDBService(v) + if err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert biz db service: %w", err)) + } } + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Create(model).Error; err != nil { - return fmt.Errorf("failed to save db service: %v", err) + if err := tx.WithContext(ctx).Create(models).Error; err != nil { + return fmt.Errorf("failed to save db services: %v", err) } return nil }); err != nil { @@ -41,16 +51,26 @@ func (d *DBServiceRepo) SaveDBService(ctx context.Context, ds *biz.DBService) er } func (d *DBServiceRepo) ListDBServices(ctx context.Context, opt *biz.ListDBServicesOption) (services []*biz.DBService, total int64, err error) { + if opt == nil { + opt = &biz.ListDBServicesOption{ + PageNumber: 1, + LimitPerPage: 20, + } + } + if opt.LimitPerPage == 0 { + opt.LimitPerPage = 20 + } var models []*model.DBService if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { // find models { - db := tx.WithContext(ctx).Order(opt.OrderBy) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) + db := tx.WithContext(ctx) + if opt.OrderBy != "" { + db = db.Order(string(opt.OrderBy)) } - db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))).Find(&models) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))).Preload("EnvironmentTag").Find(&models) if err := db.Error; err != nil { return fmt.Errorf("failed to list db service: %v", err) } @@ -59,9 +79,7 @@ func (d *DBServiceRepo) ListDBServices(ctx context.Context, opt *biz.ListDBServi // find total { db := tx.WithContext(ctx).Model(&model.DBService{}) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) if err := db.Count(&total).Error; err != nil { return fmt.Errorf("failed to count db service: %v", err) } @@ -86,7 +104,7 @@ func (d *DBServiceRepo) GetDBServicesByIds(ctx context.Context, dbServiceIds []s var items []*model.DBService if err = transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { // find models - db := tx.WithContext(ctx).Find(&items, dbServiceIds) + db := tx.WithContext(ctx).Preload("EnvironmentTag").Find(&items, dbServiceIds) if err = db.Error; err != nil { return fmt.Errorf("failed to list db service: %v", err) @@ -114,14 +132,86 @@ func (d *DBServiceRepo) DelDBService(ctx context.Context, dbServiceUid string) e if err := tx.WithContext(ctx).Where("uid = ?", dbServiceUid).Delete(&model.DBService{}).Error; err != nil { return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to delete db service: %v", err)) } + + var memberRoleItems []*model.MemberRoleOpRange + if err := tx.WithContext(ctx).Where("op_range_type = ? and find_in_set(?, range_uids)", "db_service", dbServiceUid).Find(&memberRoleItems).Error; err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to find member_role_op_range err: %v", err)) + } + + for _, item := range memberRoleItems { + var dbServiceIds []string + for _, uid := range strings.Split(item.RangeUIDs, ",") { + if uid != dbServiceUid { + dbServiceIds = append(dbServiceIds, uid) + } + } + + item.RangeUIDs = strings.Join(dbServiceIds, ",") + + if err := tx.WithContext(ctx).Model(&model.MemberRoleOpRange{}).Where("member_uid = ? and role_uid = ? and op_range_type = ?", item.MemberUID, item.RoleUID, item.OpRangeType).Update("range_uids", item.RangeUIDs).Error; err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to update member_role_op_range err: %v", err)) + } + } + + var memberGroupRoleItems []*model.MemberGroupRoleOpRange + if err := tx.WithContext(ctx).Where("op_range_type = ? and find_in_set(?, range_uids)", "db_service", dbServiceUid).Find(&memberGroupRoleItems).Error; err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to find member_group_role_op_range err: %v", err)) + } + + for _, item := range memberGroupRoleItems { + var dbServiceIds []string + for _, uid := range strings.Split(item.RangeUIDs, ",") { + if uid != dbServiceUid { + dbServiceIds = append(dbServiceIds, uid) + } + } + + item.RangeUIDs = strings.Join(dbServiceIds, ",") + + if err := tx.WithContext(ctx).Model(&model.MemberGroupRoleOpRange{}).Where("member_group_uid = ? and role_uid = ? and op_range_type = ?", item.MemberGroupUID, item.RoleUID, item.OpRangeType).Update("range_uids", item.RangeUIDs).Error; err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to update member_group_role_op_range err: %v", err)) + } + } + return nil }) } +func (d *DBServiceRepo) GetDBServices(ctx context.Context, conditions []pkgConst.FilterCondition) (services []*biz.DBService, err error) { + var models []*model.DBService + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find models + { + db := tx.WithContext(ctx) + for _, f := range conditions { + db = gormWhere(db, f) + } + db = db.Preload("EnvironmentTag").Find(&models) + if err := db.Error; err != nil { + return fmt.Errorf("failed to list db service: %v", err) + } + } + + return nil + }); err != nil { + return nil, err + } + + // convert model to biz + for _, model := range models { + ds, err := convertModelDBService(model) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model db services: %w", err)) + } + services = append(services, ds) + } + return services, nil +} + func (d *DBServiceRepo) GetDBService(ctx context.Context, dbServiceUid string) (*biz.DBService, error) { var dbService *model.DBService if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.First(&dbService, "uid = ?", dbServiceUid).Error; err != nil { + if err := tx.Preload("EnvironmentTag").First(&dbService, "uid = ?", dbServiceUid).Error; err != nil { return fmt.Errorf("failed to get db service: %v", err) } return nil @@ -167,3 +257,55 @@ func (d *DBServiceRepo) UpdateDBService(ctx context.Context, dbService *biz.DBSe }) } + +func (d *DBServiceRepo) CountDBService(ctx context.Context) ([]biz.DBTypeCount, error) { + type Result struct { + DBType string `json:"db_type"` + Count int64 `json:"count"` + } + var results []Result + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.DBService{}).Select("db_type, count(*) as count").Group("db_type").Find(&results).Error; err != nil { + return fmt.Errorf("failed to count dbService: %v", err) + } + return nil + }); err != nil { + return nil, err + } + dbTypeCounts := make([]biz.DBTypeCount, 0, len(results)) + for _, result := range results { + dbTypeCounts = append(dbTypeCounts, biz.DBTypeCount{ + DBType: result.DBType, + Count: result.Count, + }) + } + return dbTypeCounts, nil +} + +func (d *DBServiceRepo) GetBusinessByProjectUID(ctx context.Context, projectUid string) ([]string, error) { + businessList := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` +SELECT DISTINCT business +FROM db_services +WHERE project_uid = ?; + `, projectUid).Find(&businessList).Error; err != nil { + return fmt.Errorf("failed to get business: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + return businessList, nil +} + +func (d *DBServiceRepo) GetFieldDistinctValue(ctx context.Context, field biz.DBServiceField, results interface{}) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.DBService{}).Select(string(field)).Group(string(field)).Find(results).Error; err != nil { + return fmt.Errorf("DBServiceRepo failed to GroupByField: %v", err) + } + return nil + }) +} diff --git a/internal/dms/storage/db_service_sync_task.go b/internal/dms/storage/db_service_sync_task.go new file mode 100644 index 000000000..40ef23213 --- /dev/null +++ b/internal/dms/storage/db_service_sync_task.go @@ -0,0 +1,129 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + "github.com/actiontech/dms/internal/pkg/locale" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgParams "github.com/actiontech/dms/pkg/params" + "gorm.io/gorm" +) + +var _ biz.DBServiceSyncTaskRepo = (*DBServiceSyncTaskRepo)(nil) + +type DBServiceSyncTaskRepo struct { + *Storage + log *utilLog.Helper +} + +func NewDBServiceSyncTaskRepo(log utilLog.Logger, s *Storage) *DBServiceSyncTaskRepo { + return &DBServiceSyncTaskRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.db_service_sync_task"))} +} + +func (d *DBServiceSyncTaskRepo) SaveDBServiceSyncTask(ctx context.Context, syncTask *biz.DBServiceSyncTask) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + modelDBServiceSyncTask := toModelDBServiceSyncTask(syncTask) + if err := tx.WithContext(ctx).Create(modelDBServiceSyncTask).Error; err != nil { + return fmt.Errorf("failed to save db_service_sync_task: %v", err) + } + return nil + }) +} + +func (d *DBServiceSyncTaskRepo) GetDBServiceSyncTaskById(ctx context.Context, id string) (*biz.DBServiceSyncTask, error) { + var dbServiceSyncTask *model.DBServiceSyncTask + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.First(&dbServiceSyncTask, "uid = ?", id).Error; err != nil { + return fmt.Errorf("failed to get db_service_sync_task: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return toBizDBServiceSyncTask(dbServiceSyncTask), nil +} + +func (d *DBServiceSyncTaskRepo) UpdateDBServiceSyncTask(ctx context.Context, syncTask *biz.DBServiceSyncTask) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Omit("created_at").Save(toModelDBServiceSyncTask(syncTask)).Error; err != nil { + return fmt.Errorf("failed to update db_service_sync_task: %v", err) + } + return nil + }) +} + +func (d *DBServiceSyncTaskRepo) ListDBServiceSyncTasks(ctx context.Context) ([]*biz.DBServiceSyncTask, error) { + var items []*model.DBServiceSyncTask + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find models + if err := tx.WithContext(ctx).Find(&items).Error; err != nil { + return fmt.Errorf("failed to list db_service_sync_task: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + ret := make([]*biz.DBServiceSyncTask, 0, len(items)) + // convert model to biz + for _, item := range items { + ret = append(ret, toBizDBServiceSyncTask(item)) + } + return ret, nil +} + +func (d *DBServiceSyncTaskRepo) ListDBServiceSyncTaskTips(ctx context.Context) ([]biz.ListDBServiceSyncTaskTips, error) { + return []biz.ListDBServiceSyncTaskTips{ + { + Type: pkgConst.DBServiceSourceNameDMP, + Desc: "Actiontech DMP", + DBTypes: []pkgConst.DBType{pkgConst.DBTypeMySQL}, + Params: pkgParams.Params{ + { + Key: "version", + Desc: locale.Bundle.LocalizeMsgByCtx(ctx, locale.DBServiceSyncVersion), + Type: pkgParams.ParamTypeString, + }, + }, + }, + { + Type: pkgConst.DBServiceSourceNameExpandService, + Desc: locale.Bundle.LocalizeMsgByCtx(ctx, locale.DBServiceSyncExpand), + DBTypes: []pkgConst.DBType{ + pkgConst.DBTypeMySQL, + pkgConst.DBTypePostgreSQL, + pkgConst.DBTypeTiDB, + pkgConst.DBTypeSQLServer, + pkgConst.DBTypeOracle, + pkgConst.DBTypeDB2, + pkgConst.DBTypeOceanBaseMySQL, + pkgConst.DBTypeTDSQLForInnoDB, + pkgConst.DBTypeGoldenDB, + }, + }, + }, nil +} + +func (d *DBServiceSyncTaskRepo) DeleteDBServiceSyncTask(ctx context.Context, dbServiceSyncTaskUid string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("uid = ?", dbServiceSyncTaskUid).Delete(&model.DBServiceSyncTask{}).Error; err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to delete db_service_sync_task: %v", err)) + } + return nil + }) +} + +func (d *DBServiceSyncTaskRepo) UpdateDBServiceSyncTaskByFields(ctx context.Context, dbServiceSyncTaskUid string, fields map[string]interface{}) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.DBServiceSyncTask{}).Where("uid = ?", dbServiceSyncTaskUid).Updates(fields).Error; err != nil { + return fmt.Errorf("failed to update db_service_sync_task: %v", err) + } + + return nil + }) +} diff --git a/internal/dms/storage/environment_tag.go b/internal/dms/storage/environment_tag.go new file mode 100644 index 000000000..bd1d7f3bb --- /dev/null +++ b/internal/dms/storage/environment_tag.go @@ -0,0 +1,122 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.EnvironmentTagRepo = (*EnvironmentTagRepo)(nil) + +type EnvironmentTagRepo struct { + *Storage + log *utilLog.Helper +} + +func NewEnvironmentTagRepo(log utilLog.Logger, s *Storage) *EnvironmentTagRepo { + return &EnvironmentTagRepo{ + Storage: s, + log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.environment_tag")), + } +} + +func (repo *EnvironmentTagRepo) toModel(environmentTag *biz.EnvironmentTag) *model.EnvironmentTag { + return &model.EnvironmentTag{ + EnvironmentName: environmentTag.Name, + Model: model.Model{UID: environmentTag.UID}, + ProjectUID: environmentTag.ProjectUID, + } +} + +func (repo *EnvironmentTagRepo) toBiz(environmentTag *model.EnvironmentTag) *biz.EnvironmentTag { + return &biz.EnvironmentTag{ + Name: environmentTag.EnvironmentName, + UID: environmentTag.UID, + ProjectUID: environmentTag.ProjectUID, + } +} + +func (repo *EnvironmentTagRepo) CreateEnvironmentTag(ctx context.Context, environmentTag *biz.EnvironmentTag) error { + return transaction(repo.log, ctx, repo.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Create(repo.toModel(environmentTag)).Error; err != nil { + return pkgErr.WrapStorageErr(repo.log, fmt.Errorf("failed to create environment tag: %v", err)) + } + return nil + }) +} + +func (repo *EnvironmentTagRepo) UpdateEnvironmentTag(ctx context.Context, environmentTagUID, environmentTagName string) error { + return transaction(repo.log, ctx, repo.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.EnvironmentTag{}).Where("uid = ?", environmentTagUID).Update("environment_name", environmentTagName).Error; err != nil { + return pkgErr.WrapStorageErr(repo.log, fmt.Errorf("failed to update environment tag: %v", err)) + } + return nil + }) +} + +func (repo *EnvironmentTagRepo) DeleteEnvironmentTag(ctx context.Context, environmentTagUID string) error { + return transaction(repo.log, ctx, repo.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("uid = ?", environmentTagUID).Delete(&model.EnvironmentTag{}).Error; err != nil { + return pkgErr.WrapStorageErr(repo.log, fmt.Errorf("failed to delete environment tag: %v", err)) + } + return nil + }) +} + +func (repo *EnvironmentTagRepo) GetEnvironmentTagByName(ctx context.Context, projetUid, name string) (bool, *biz.EnvironmentTag, error) { + var environmentTag model.EnvironmentTag + if err := repo.db.WithContext(ctx).Where("environment_name = ? AND project_uid = ?", name, projetUid).First(&environmentTag).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return false, nil, nil + } + return false, nil, fmt.Errorf("failed to get environment tag by name: %w", err) + } + return true, repo.toBiz(&environmentTag), nil +} + +func (repo *EnvironmentTagRepo) GetEnvironmentTagByUID(ctx context.Context, uid string) (*biz.EnvironmentTag, error) { + var environmentTag model.EnvironmentTag + if err := repo.db.WithContext(ctx).Where("uid = ?", uid).First(&environmentTag).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return nil, pkgErr.ErrStorageNoData + } + return nil, fmt.Errorf("failed to get environment tag by uid: %w", err) + } + return repo.toBiz(&environmentTag), nil +} +func (repo *EnvironmentTagRepo) ListEnvironmentTags(ctx context.Context, options *biz.ListEnvironmentTagsOption) ([]*biz.EnvironmentTag, int64, error) { + var environmentTags []*model.EnvironmentTag + db := repo.db.WithContext(ctx) + + // 构建查询条件 + query := db.Model(&model.EnvironmentTag{}) + if options.Limit >= 0 { + query = query.Limit(options.Limit) + } + if options.Offset >= 0 { + query = query.Offset(options.Offset) + } + + // 获取分页结果 + if err := query.Where("project_uid = ?", options.ProjectUID).Find(&environmentTags).Error; err != nil { + return nil, 0, fmt.Errorf("failed to list environment tags: %w", err) + } + + // 获取总数 + var count int64 + if err := repo.db.WithContext(ctx).Model(&model.EnvironmentTag{}).Count(&count).Error; err != nil { + return nil, 0, fmt.Errorf("failed to count environment tags: %w", err) + } + + bizEnvironmentTags := make([]*biz.EnvironmentTag, 0, len(environmentTags)) + for _, EnvironmentTag := range environmentTags { + bizEnvironmentTags = append(bizEnvironmentTags, repo.toBiz(EnvironmentTag)) + } + + return bizEnvironmentTags, count, nil +} diff --git a/internal/dms/storage/gateway.go b/internal/dms/storage/gateway.go new file mode 100644 index 000000000..d12ba4072 --- /dev/null +++ b/internal/dms/storage/gateway.go @@ -0,0 +1,201 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.GatewayRepo = (*GatewayRepo)(nil) + +type GatewayRepo struct { + *Storage + log *utilLog.Helper +} + +func NewGatewayRepo(log utilLog.Logger, s *Storage) *GatewayRepo { + return &GatewayRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.gateway"))} +} + +// AddGateway 添加一个新网关 +func (r *GatewayRepo) AddGateway(ctx context.Context, u *biz.Gateway) error { + gateway := &model.Gateway{ + Model: model.Model{ + UID: u.ID, + }, + Name: u.Name, + Description: u.Desc, + Address: u.URL, + } + + if err := transaction(r.log, ctx, r.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Create(gateway).Error; err != nil { + return fmt.Errorf("failed to add gateway: %v", err) + } + return nil + }); err != nil { + return pkgErr.WrapStorageErr(r.log, err) + } + + return nil +} + +// DeleteGateway 删除网关 +func (r *GatewayRepo) DeleteGateway(ctx context.Context, id string) error { + if err := transaction(r.log, ctx, r.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("uid = ?", id).Delete(&model.Gateway{}).Error; err != nil { + return fmt.Errorf("failed to delete gateway: %v", err) + } + return nil + }); err != nil { + return pkgErr.WrapStorageErr(r.log, err) + } + + return nil +} + +// UpdateGateway 更新网关 +func (r *GatewayRepo) UpdateGateway(ctx context.Context, u *biz.Gateway) error { + gateway := &model.Gateway{ + Model: model.Model{ + UID: u.ID, + }, + Name: u.Name, + Description: u.Desc, + Address: u.URL, + } + + if err := transaction(r.log, ctx, r.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.Gateway{}).Where("uid = ?", u.ID).Updates(gateway).Error; err != nil { + return fmt.Errorf("failed to update gateway: %v", err) + } + return nil + }); err != nil { + return pkgErr.WrapStorageErr(r.log, err) + } + + return nil +} + +// GetGateway 根据ID获取网关 +func (r *GatewayRepo) GetGateway(ctx context.Context, id string) (*biz.Gateway, error) { + var gateway model.Gateway + + if err := transaction(r.log, ctx, r.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("uid = ?", id).First(&gateway).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return fmt.Errorf("gateway %s not found", id) + } + return fmt.Errorf("failed to get gateway: %v", err) + } + return nil + }); err != nil { + return nil, pkgErr.WrapStorageErr(r.log, err) + } + + return &biz.Gateway{ + ID: gateway.UID, + Name: gateway.Name, + Desc: gateway.Description, + URL: gateway.Address, + }, nil +} + +// ListGateways 列出所有网关 +func (r *GatewayRepo) ListGateways(ctx context.Context, opt *biz.ListGatewaysOption) ([]*biz.Gateway, int64, error) { + var gateways []*model.Gateway + var total int64 + + if err := transaction(r.log, ctx, r.db, func(tx *gorm.DB) error { + // 查询网关列表 + { + db := tx.WithContext(ctx).Order(string(opt.OrderBy)) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))).Find(&gateways) + if err := db.Error; err != nil { + return fmt.Errorf("failed to list gateways: %v", err) + } + } + + // 查询总数 + { + db := tx.WithContext(ctx).Model(&model.Gateway{}) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count gateways: %v", err) + } + } + return nil + }); err != nil { + return nil, 0, pkgErr.WrapStorageErr(r.log, err) + } + + // 转换为业务模型 + result := make([]*biz.Gateway, len(gateways)) + for i, g := range gateways { + result[i] = &biz.Gateway{ + ID: g.UID, + Name: g.Name, + Desc: g.Description, + URL: g.Address, + } + } + + return result, total, nil +} + +// GetGatewayTips 获取网关提示信息 +func (r *GatewayRepo) GetGatewayTips(ctx context.Context) ([]*biz.Gateway, error) { + var gateways []*model.Gateway + + if err := transaction(r.log, ctx, r.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Find(&gateways).Error; err != nil { + return fmt.Errorf("failed to get gateway tips: %v", err) + } + return nil + }); err != nil { + return nil, pkgErr.WrapStorageErr(r.log, err) + } + + // 转换为业务模型 + result := make([]*biz.Gateway, len(gateways)) + for i, g := range gateways { + result[i] = &biz.Gateway{ + ID: g.UID, + Name: g.Name, + Desc: g.Description, + URL: g.Address, + } + } + + return result, nil +} + +func (d *GatewayRepo) SyncGateways(ctx context.Context, s []*biz.Gateway) error { + gateways := make([]*model.Gateway, len(s)) + for i, v := range s { + gateways[i] = &model.Gateway{ + Model: model.Model{ + UID: v.ID, + }, + Name: v.Name, + Description: v.Desc, + Address: v.URL, + } + } + + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // 第一步:删除所有现有的 gateways(整表清空) + if err := tx.WithContext(ctx).Where("1 = 1").Delete(&model.Gateway{}).Error; err != nil { + return err + } + // 第二步:插入新的 gateways + return tx.WithContext(ctx).Save(gateways).Error + }) +} diff --git a/internal/dms/storage/license_qa.go b/internal/dms/storage/license_qa.go new file mode 100644 index 000000000..c5fbe30ad --- /dev/null +++ b/internal/dms/storage/license_qa.go @@ -0,0 +1,42 @@ +//go:build !release +// +build !release + +package storage + +import ( + "context" + + "github.com/actiontech/dms/internal/dms/biz" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +var _ biz.LicenseRepo = (*LicenseRepo)(nil) + +type LicenseRepo struct { + *Storage + log *utilLog.Helper +} + +func NewLicenseRepo(log utilLog.Logger, s *Storage) *LicenseRepo { + return &LicenseRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.license"))} +} + +func (d *LicenseRepo) SaveLicense(ctx context.Context, license interface{}) error { + return nil +} + +func (d *LicenseRepo) GetLastLicense(ctx context.Context) (interface{}, bool, error) { + return nil, false, nil +} + +func (d *LicenseRepo) GetLicenseById(ctx context.Context, id string) (interface{}, bool, error) { + return nil, true, nil +} + +func (d *LicenseRepo) UpdateLicense(ctx context.Context, l interface{}) error { + return nil +} + +func (d *LicenseRepo) DelLicense(ctx context.Context) error { + return nil +} diff --git a/internal/dms/storage/login_configuration.go b/internal/dms/storage/login_configuration.go new file mode 100644 index 000000000..f60633882 --- /dev/null +++ b/internal/dms/storage/login_configuration.go @@ -0,0 +1,58 @@ +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.LoginConfigurationRepo = (*LoginConfigurationRepo)(nil) + +type LoginConfigurationRepo struct { + *Storage + log *utilLog.Helper +} + +func NewLoginConfigurationRepo(log utilLog.Logger, s *Storage) *LoginConfigurationRepo { + return &LoginConfigurationRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.Login_configuration"))} +} + +func (d *LoginConfigurationRepo) UpdateLoginConfiguration(ctx context.Context, loginConfiguration *biz.LoginConfiguration) error { + modelLoginConfiguration, err := convertBizLoginConfiguration(loginConfiguration) + if err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert biz Login configuration: %w", err)) + } + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(modelLoginConfiguration).Where("uid = ?", modelLoginConfiguration.UID).Omit("created_at").Save(modelLoginConfiguration).Error; err != nil { + return fmt.Errorf("failed to save Login configuration: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *LoginConfigurationRepo) GetLastLoginConfiguration(ctx context.Context) (*biz.LoginConfiguration, error) { + var LoginConfiguration *model.LoginConfiguration + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Last(&LoginConfiguration).Error; err != nil { + return fmt.Errorf("failed to get Login configuration: %v", err) + } + return nil + }); err != nil { + return nil, err + } + ret, err := convertModelLoginConfiguration(LoginConfiguration) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model Login configuration: %w", err)) + } + return ret, nil +} diff --git a/internal/dms/storage/member.go b/internal/dms/storage/member.go index f407a58a6..4448d5b53 100644 --- a/internal/dms/storage/member.go +++ b/internal/dms/storage/member.go @@ -2,6 +2,7 @@ package storage import ( "context" + "errors" "fmt" "github.com/actiontech/dms/internal/dms/biz" @@ -47,11 +48,9 @@ func (d *MemberRepo) ListMembers(ctx context.Context, opt *biz.ListMembersOption if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { // find models { - db := tx.WithContext(ctx).Preload("RoleWithOpRanges").Order(opt.OrderBy) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } - db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + db := tx.WithContext(ctx).Preload("RoleWithOpRanges").Preload("OpPermissions").Order(opt.OrderBy) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Preload("User.Members.Project").Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) if err := db.Find(&models).Error; err != nil { return fmt.Errorf("failed to list members: %v", err) } @@ -60,9 +59,7 @@ func (d *MemberRepo) ListMembers(ctx context.Context, opt *biz.ListMembersOption // find total { db := tx.WithContext(ctx).Model(&model.Member{}) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) if err := db.Count(&total).Error; err != nil { return fmt.Errorf("failed to count members: %v", err) } @@ -165,3 +162,47 @@ func (d *MemberRepo) DelRoleFromAllMembers(ctx context.Context, roleUid string) return nil }) } + +func (d *MemberRepo) ReplaceOpPermissionsInMember(ctx context.Context, memberUid string, opPermissionUids []string) error { + if len(opPermissionUids) == 0 { + // delete all op permissions when op permission uids is empty + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + member := &model.Member{Model: model.Model{UID: memberUid}} + if err := tx.WithContext(ctx).Where("uid = ?", memberUid).First(member).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return fmt.Errorf("member not found: %v", err) + } + return fmt.Errorf("failed to query member existence: %v", err) + } + + err := tx.WithContext(ctx).Model(member).Association("OpPermissions").Clear() + if err != nil { + return fmt.Errorf("failed to delete op permissions") + } + return nil + }) + } + var ops []*model.OpPermission + for _, u := range opPermissionUids { + ops = append(ops, &model.OpPermission{ + Model: model.Model{ + UID: u, + }, + }) + } + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + member := &model.Member{Model: model.Model{UID: memberUid}} + if err := tx.WithContext(ctx).Where("uid = ?", memberUid).First(member).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return fmt.Errorf("member not found: %v", err) + } + return fmt.Errorf("failed to query member existence: %v", err) + } + + err := tx.WithContext(ctx).Model(member).Association("OpPermissions").Replace(ops) + if err != nil { + return fmt.Errorf("failed to replace op permissions") + } + return nil + }) +} diff --git a/internal/dms/storage/member_group.go b/internal/dms/storage/member_group.go new file mode 100644 index 000000000..71728d121 --- /dev/null +++ b/internal/dms/storage/member_group.go @@ -0,0 +1,208 @@ +package storage + +import ( + "context" + "errors" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.MemberGroupRepo = (*MemberGroupRepo)(nil) + +type MemberGroupRepo struct { + *Storage + log *utilLog.Helper +} + +func NewMemberGroupRepo(log utilLog.Logger, s *Storage) *MemberGroupRepo { + return &MemberGroupRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.member_group"))} +} + +func (d *MemberGroupRepo) ListMemberGroups(ctx context.Context, opt *biz.ListMemberGroupsOption) (memberGroups []*biz.MemberGroup, total int64, err error) { + var models []*model.MemberGroup + + if err = transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find models + { + db := tx.WithContext(ctx).Preload("RoleWithOpRanges").Preload("Users").Preload("OpPermissions").Order(opt.OrderBy) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + if err = db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to list member groups: %v", err) + } + } + + // find total + { + db := tx.WithContext(ctx).Model(&model.MemberGroup{}) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err = db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count member groups: %v", err) + } + } + + return nil + }); err != nil { + return nil, 0, err + } + + // convert model to biz + for _, memberGroup := range models { + ds, err := convertModelMemberGroup(memberGroup) + if err != nil { + return nil, 0, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model user groups: %v", err)) + } + memberGroups = append(memberGroups, ds) + } + + return +} + +func (d *MemberGroupRepo) GetMemberGroup(ctx context.Context, memberGroupId string) (*biz.MemberGroup, error) { + var memberGroup model.MemberGroup + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Preload("RoleWithOpRanges").Preload("Users").Where("uid = ?", memberGroupId).First(&memberGroup).Error; err != nil { + return fmt.Errorf("failed to get member group: %v", err) + } + + return nil + }); err != nil { + return nil, err + } + + ret, err := convertModelMemberGroup(&memberGroup) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model member group: %v", err)) + } + + return ret, nil +} + +func (d *MemberGroupRepo) CreateMemberGroup(ctx context.Context, u *biz.MemberGroup) error { + memberGroup := convertBizMemberGroup(u) + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Create(memberGroup).Error; err != nil { + return fmt.Errorf("failed to create member group err: %v", err) + } + + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *MemberGroupRepo) UpdateMemberGroup(ctx context.Context, m *biz.MemberGroup) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + memberGroup := convertBizMemberGroup(m) + if err := tx.WithContext(ctx).Model(memberGroup).Association("Users").Clear(); err != nil { + return fmt.Errorf("clean member group relationship with user failed: %v", err) + } + + if err := tx.WithContext(ctx).Model(memberGroup).Association("RoleWithOpRanges").Clear(); err != nil { + return fmt.Errorf("failed to delete member group: %v", err) + } + + memberGroup = convertBizMemberGroup(m) + if err := tx.WithContext(ctx).Save(memberGroup).Error; err != nil { + return fmt.Errorf("failed to update member group err: %v", err) + } + + return nil + }) +} + +func (d *MemberGroupRepo) DeleteMemberGroup(ctx context.Context, memberGroupUid string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + memberGroup := model.MemberGroup{Model: model.Model{UID: memberGroupUid}} + + if err := tx.WithContext(ctx).Model(&memberGroup).Association("Users").Clear(); err != nil { + return fmt.Errorf("clean member group relationship with user failed: %v", err) + } + + if err := tx.WithContext(ctx).Select("RoleWithOpRanges").Delete(&memberGroup).Error; err != nil { + return fmt.Errorf("failed to delete member group: %v", err) + } + + return nil + }) +} + +func (d *MemberGroupRepo) GetMemberGroupsByUserIDAndProjectID(ctx context.Context, userID, projectID string) ([]*biz.MemberGroup, error) { + var memberGroups []*model.MemberGroup + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // 查询关联的用户组 + if err := tx.WithContext(ctx).Preload("RoleWithOpRanges").Preload("Users").Preload("OpPermissions"). + Joins("JOIN member_group_users ON member_groups.uid = member_group_users.member_group_uid"). + Where("member_group_users.user_uid = ? AND member_groups.project_uid = ?", userID, projectID). + Find(&memberGroups).Error; err != nil { + return fmt.Errorf("failed to get member groups by user id and project id: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + bizGroups := make([]*biz.MemberGroup, 0, len(memberGroups)) + for _, modelGroup := range memberGroups { + bizGroup, err := convertModelMemberGroup(modelGroup) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model member group: %v", err)) + } + bizGroups = append(bizGroups, bizGroup) + } + + return bizGroups, nil +} + +func (d *MemberGroupRepo) ReplaceOpPermissionsInMemberGroup(ctx context.Context, memberGroupUid string, opPermissionUids []string) error { + if len(opPermissionUids) == 0 { + // delete all op permissions when op permission uids is empty + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + memberGroup := &model.MemberGroup{Model: model.Model{UID: memberGroupUid}} + if err := tx.WithContext(ctx).Where("uid = ?", memberGroupUid).First(memberGroup).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return fmt.Errorf("member group not found: %v", err) + } + return fmt.Errorf("failed to query member group existence: %v", err) + } + + err := tx.WithContext(ctx).Model(memberGroup).Association("OpPermissions").Clear() + if err != nil { + return fmt.Errorf("failed to delete op permissions: %v", err) + } + return nil + }) + } + var ops []*model.OpPermission + for _, u := range opPermissionUids { + ops = append(ops, &model.OpPermission{ + Model: model.Model{ + UID: u, + }, + }) + } + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + memberGroup := &model.MemberGroup{Model: model.Model{UID: memberGroupUid}} + if err := tx.WithContext(ctx).Where("uid = ?", memberGroupUid).First(memberGroup).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return fmt.Errorf("member not found: %v", err) + } + return fmt.Errorf("failed to query member existence: %v", err) + } + + err := tx.WithContext(ctx).Model(memberGroup).Association("OpPermissions").Replace(ops) + if err != nil { + return fmt.Errorf("failed to replace op permissions") + } + return nil + }) +} \ No newline at end of file diff --git a/internal/dms/storage/model/model.go b/internal/dms/storage/model/model.go index 14a227dc4..d1d9dded1 100644 --- a/internal/dms/storage/model/model.go +++ b/internal/dms/storage/model/model.go @@ -1,65 +1,105 @@ package model import ( + "database/sql" "database/sql/driver" "encoding/json" + "fmt" + "strings" "time" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" "github.com/actiontech/dms/pkg/params" "github.com/actiontech/dms/pkg/periods" + "golang.org/x/text/language" "gorm.io/gorm" ) -func GetAllModels() []interface{} { - return []interface{}{ - DBService{}, - User{}, - UserGroup{}, - Role{}, - OpPermission{}, - DMSConfig{}, - Member{}, - MemberRoleOpRange{}, - Namespace{}, - ProxyTarget{}, - Plugin{}, - Oauth2Configuration{}, - LDAPConfiguration{}, - SMTPConfiguration{}, - WebHookConfiguration{}, - WeChatConfiguration{}, - IMConfiguration{}, - CloudbeaverUserCache{}, - CloudbeaverConnectionCache{}, - } +var AutoMigrateList = []interface{}{ + DBService{}, + User{}, + UserGroup{}, + Role{}, + OpPermission{}, + DMSConfig{}, + Member{}, + MemberRoleOpRange{}, + MemberGroup{}, + MemberGroupRoleOpRange{}, + BusinessTag{}, + Project{}, + ProxyTarget{}, + Plugin{}, + OAuth2Session{}, + LoginConfiguration{}, + Oauth2Configuration{}, + LDAPConfiguration{}, + SMTPConfiguration{}, + WebHookConfiguration{}, + WeChatConfiguration{}, + IMConfiguration{}, + SmsConfiguration{}, + CloudbeaverUserCache{}, + CloudbeaverConnectionCache{}, + SqlWorkbenchUserCache{}, + SqlWorkbenchDatasourceCache{}, + DBServiceSyncTask{}, + BasicConfig{}, + CompanyNotice{}, + ClusterLeader{}, + ClusterNodeInfo{}, + Workflow{}, + WorkflowRecord{}, + WorkflowStep{}, + DataExportTask{}, + DataExportTaskRecord{}, + UserAccessToken{}, + CbOperationLog{}, + EnvironmentTag{}, + Gateway{}, + SystemVariable{}, + OperationRecord{}, } type Model struct { - UID string `json:"uid" gorm:"primaryKey" example:"1"` - CreatedAt time.Time `json:"created_at" example:"2018-10-21T16:40:23+08:00"` + UID string `json:"uid" gorm:"primaryKey;size:32" example:"1"` + CreatedAt time.Time `json:"created_at" gorm:"column:created_at" example:"2018-10-21T16:40:23+08:00"` UpdatedAt time.Time `json:"updated_at" example:"2018-10-21T16:40:23+08:00"` } type DBService struct { Model - Name string `json:"name" gorm:"size:200;not null;uniqueIndex" example:""` - DBType string `json:"db_type" gorm:"column:db_type; not null" example:"mysql"` - Host string `json:"host" gorm:"column:db_host; not null" example:"10.10.10.10"` - Port string `json:"port" gorm:"column:db_port; not null" example:"3306"` - User string `json:"user" gorm:"column:db_user; not null" example:"root"` - Password string `json:"password" gorm:"column:db_password; not null"` - Desc string `json:"desc" gorm:"column:desc" example:"this is a instance"` - Business string `json:"business" gorm:"column:business; not null" example:"this is a business"` - AdditionalParams params.Params `json:"additional_params" gorm:"type:text"` - Source string `json:"source" gorm:"not null"` - NamespaceUID string `json:"namespace_uid" gorm:"column:namespace_uid"` - MaintenancePeriod periods.Periods `json:"maintenance_period" gorm:"type:text"` - ExtraParameters ExtraParameters `json:"extra_parameters" gorm:"TYPE:json"` + Name string `json:"name" gorm:"size:200;not null;index:project_uid_name,unique" example:""` + DBType string `json:"db_type" gorm:"size:255;column:db_type; not null" example:"mysql"` + Host string `json:"host" gorm:"column:db_host;size:255; not null" example:"10.10.10.10"` + Port string `json:"port" gorm:"column:db_port;size:255; not null" example:"3306"` + User string `json:"user" gorm:"column:db_user;size:255; not null" example:"root"` + Password string `json:"password" gorm:"column:db_password; size:255; not null"` + Desc string `json:"desc" gorm:"column:desc" example:"this is a instance"` + EnvironmentTagUID string `json:"environment_tag_id" gorm:"column:environment_tag_uid; not null"` + AdditionalParams params.Params `json:"additional_params" gorm:"type:text"` + Source string `json:"source" gorm:"size:255;not null"` + ProjectUID string `json:"project_uid" gorm:"size:32;column:project_uid;index:project_uid_name,unique"` + MaintenancePeriod periods.Periods `json:"maintenance_period" gorm:"type:text"` + ExtraParameters ExtraParameters `json:"extra_parameters" gorm:"TYPE:json"` + LastConnectionStatus *string `json:"last_connection_status"` + LastConnectionTime *time.Time `json:"last_connection_time"` + LastConnectionErrorMsg *string `json:"last_connection_error_msg"` + EnableBackup bool `json:"enable_backup" gorm:"column:enable_backup;type:bool"` + BackupMaxRows uint64 `json:"backup_max_rows" gorm:"column:backup_max_rows;not null;default:1000"` + EnvironmentTag *EnvironmentTag +} + +type EnvironmentTag struct { + Model + ProjectUID string `json:"project_uid" gorm:"size:32;column:project_uid;index:project_uid_name"` + EnvironmentName string `json:"environment_name" gorm:"not null;index:project_uid_name"` } type ExtraParameters struct { - SqleConfig *SQLEConfig `json:"sqle_config"` + SqleConfig *SQLEConfig `json:"sqle_config"` + AdditionalParam params.Params `json:"additional_param"` } func (e ExtraParameters) Value() (driver.Value, error) { @@ -73,30 +113,42 @@ func (e *ExtraParameters) Scan(input interface{}) error { } type SQLEConfig struct { - RuleTemplateID string `json:"rule_template_id"` - RuleTemplateName string `json:"rule_template_name"` - SqlQueryConfig *SqlQueryConfig `json:"sql_query_config"` + AuditEnabled bool `json:"audit_enabled"` + RuleTemplateID string `json:"rule_template_id"` + RuleTemplateName string `json:"rule_template_name"` + DataExportRuleTemplateName string `json:"data_export_rule_template_name"` + DataExportRuleTemplateID string `json:"data_export_rule_template_id"` + SqlQueryConfig *SqlQueryConfig `json:"sql_query_config"` } type SqlQueryConfig struct { - MaxPreQueryRows int `json:"max_pre_query_rows"` - QueryTimeoutSecond int `json:"query_timeout_second"` - AuditEnabled bool `json:"audit_enabled"` - AllowQueryWhenLessThanAuditLevel string `json:"allow_query_when_less_than_audit_level"` + MaxPreQueryRows int `json:"max_pre_query_rows"` + QueryTimeoutSecond int `json:"query_timeout_second"` + AuditEnabled bool `json:"audit_enabled"` + WorkflowExecEnabled bool `json:"workflow_exec_enabled"` + AllowQueryWhenLessThanAuditLevel string `json:"allow_query_when_less_than_audit_level"` + RuleTemplateID string `json:"rule_template_id"` + RuleTemplateName string `json:"rule_template_name"` + MaintenancePeriods periods.Periods `json:"maintenance_periods"` } type User struct { Model Name string `json:"name" gorm:"size:200;column:name"` - ThirdPartyUserID string `json:"third_party_user_id" gorm:"third_party_user_id;column:third_party_user_id"` - Email string `json:"email" gorm:"column:email"` - Phone string `json:"phone" gorm:"column:phone"` - WeChatID string `json:"wechat_id" gorm:"column:wechat_id"` - Password string `json:"password" gorm:"column:password"` - UserAuthenticationType string `json:"user_authentication_type" gorm:"not null;column:user_authentication_type"` + ThirdPartyUserID string `json:"third_party_user_id" gorm:"size:255;column:third_party_user_id"` // used to retrieve sqle user based on third-party user ID + ThirdPartyUserInfo string `json:"third_party_user_info" gorm:"type:text;column:third_party_user_info"` // used to save original third-party user information + Email string `json:"email" gorm:"size:255;column:email"` + Phone string `json:"phone" gorm:"size:255;column:phone"` + WeChatID string `json:"wechat_id" gorm:"size:255;column:wechat_id"` + Language string `json:"language" gorm:"size:255;column:language"` + Password string `json:"password" gorm:"size:255;column:password"` + UserAuthenticationType string `json:"user_authentication_type" gorm:"size:255;not null;column:user_authentication_type"` Stat uint `json:"stat" gorm:"not null"` + TwoFactorEnabled bool `json:"two_factor_enabled" gorm:"default:false; not null"` + System string `json:"system" gorm:"size:50;column:system"` LastLoginAt *time.Time `json:"last_login_at" gorm:"column:last_login_at"` DeletedAt gorm.DeletedAt `json:"delete_at" gorm:"column:delete_at" sql:"index"` + Members []*Member `gorm:"foreignKey:UserUID"` UserGroups []*UserGroup `gorm:"many2many:user_group_users"` OpPermissions []*OpPermission `gorm:"many2many:user_op_permissions"` } @@ -105,7 +157,7 @@ type UserGroup struct { Model Name string `json:"name" gorm:"size:200;uniqueIndex"` Desc string `json:"desc" gorm:"column:description"` - Stat uint `json:"stat" gorm:"not null"` + Stat uint `json:"stat" gorm:"size:32;not null"` Users []*User `gorm:"many2many:user_group_users"` } @@ -114,7 +166,7 @@ type Role struct { Model Name string `json:"name" gorm:"size:200;uniqueIndex"` Desc string `json:"desc" gorm:"column:description"` - Stat uint `json:"stat" gorm:"not null"` + Stat uint `json:"stat" gorm:"size:32;not null"` OpPermissions []*OpPermission `gorm:"many2many:role_op_permissions"` } @@ -122,70 +174,152 @@ type Role struct { type OpPermission struct { Model Name string `json:"name" gorm:"size:200;uniqueIndex"` + Module string `json:"module" gorm:"size:255;column:module"` Desc string `json:"desc" gorm:"column:description"` - RangeType string `json:"range_type" gorm:"column:range_type"` + RangeType string `json:"range_type" gorm:"size:255;column:range_type"` + Service string `json:"service" gorm:"size:255;column:service"` +} + +type UserAccessToken struct { + Model + Token string `json:"token" gorm:"size:255"` + ExpiredTime time.Time `json:"expired_time" example:"2018-10-21T16:40:23+08:00"` + UserID uint `json:"user_id" gorm:"size:32;index:user_id,unique"` + + User *User `json:"user" gorm:"foreignkey:user_id"` } type DMSConfig struct { Model - NeedInitOpPermissions bool `json:"need_init_op_permissions" gorm:"column:need_init_op_permissions"` - NeedInitUsers bool `json:"need_init_users" gorm:"column:need_init_users"` - NeedInitRoles bool `json:"need_init_roles" gorm:"column:need_init_roles"` - NeedInitNamespaces bool `json:"need_init_namespaces" gorm:"column:need_init_namespaces"` + NeedInitOpPermissions bool `json:"need_init_op_permissions" gorm:"column:need_init_op_permissions"` + NeedInitUsers bool `json:"need_init_users" gorm:"column:need_init_users"` + NeedInitRoles bool `json:"need_init_roles" gorm:"column:need_init_roles"` + NeedInitProjects bool `json:"need_init_projects" gorm:"column:need_init_projects"` + EnableSQLResultSetsDataMasking bool `json:"enable_sql_result_sets_data_masking" gorm:"column:enable_sql_result_sets_data_masking"` } type Member struct { Model - UserUID string `json:"user_uid" gorm:"column:user_uid"` - NamespaceUID string `json:"namespace_uid" gorm:"column:namespace_uid"` + UserUID string `json:"user_uid" gorm:"size:32;column:user_uid;index:project_user_id,unique"` + ProjectUID string `json:"project_uid" gorm:"size:32;column:project_uid;index:project_user_id,unique"` + Project *Project `json:"project" gorm:"foreignKey:ProjectUID"` + User *User `json:"user" gorm:"foreignkey:UserUID"` RoleWithOpRanges []MemberRoleOpRange `json:"role_with_op_ranges" gorm:"foreignKey:MemberUID;references:UID"` + OpPermissions []*OpPermission `json:"op_permissions" gorm:"many2many:member_op_permissions"` } type MemberRoleOpRange struct { - MemberUID string `json:"member_uid" gorm:"size:200;column:member_uid"` - RoleUID string `json:"role_uid" gorm:"column:role_uid"` - OpRangeType string `json:"op_range_type" gorm:"column:op_range_type"` + MemberUID string `json:"member_uid" gorm:"size:32;column:member_uid"` + RoleUID string `json:"role_uid" gorm:"size:32;column:role_uid"` + OpRangeType string `json:"op_range_type" gorm:"size:255;column:op_range_type"` RangeUIDs string `json:"range_uids" gorm:"type:text;column:range_uids"` } -type Namespace struct { +func (mg *MemberRoleOpRange) AfterSave(tx *gorm.DB) error { + return tx.Delete(&MemberRoleOpRange{}, "member_uid IS NULL").Error +} + +type MemberGroup struct { + Model + Name string `json:"name" gorm:"size:200;index:project_uid_name,unique"` + ProjectUID string `json:"project_uid" gorm:"size:32;column:project_uid;index:project_uid_name,unique"` + Users []*User `gorm:"many2many:member_group_users"` + RoleWithOpRanges []MemberGroupRoleOpRange `json:"role_with_op_ranges" gorm:"foreignKey:MemberGroupUID;references:UID"` + OpPermissions []OpPermission `json:"op_permissions" gorm:"many2many:member_group_op_permissions"` +} + +type MemberGroupRoleOpRange struct { + MemberGroupUID string `json:"member_group_uid" gorm:"size:32;column:member_group_uid"` + RoleUID string `json:"role_uid" gorm:"size:32;column:role_uid"` + OpRangeType string `json:"op_range_type" gorm:"size:255;column:op_range_type"` + RangeUIDs string `json:"range_uids" gorm:"type:text;column:range_uids"` +} + +func (mg *MemberGroupRoleOpRange) AfterSave(tx *gorm.DB) error { + return tx.Delete(&MemberGroupRoleOpRange{}, "member_group_uid IS NULL").Error +} + +type Project struct { Model - Name string `json:"name" gorm:"column:name"` - Desc string `json:"desc" gorm:"column:desc"` - CreateUserUID string `json:"create_user_uid" gorm:"column:create_user_uid"` - Status string `gorm:"default:'active'"` + Name string `json:"name" gorm:"size:200;column:name;index:name,unique"` + Desc string `json:"desc" gorm:"column:desc"` + BusinessTagUID string `json:"business_tag_uid" gorm:"size:32;column:business_tag_uid"` + CreateUserUID string `json:"create_user_uid" gorm:"size:32;column:create_user_uid"` + Status string `gorm:"size:64;default:'active'"` + Priority uint8 `json:"priority" gorm:"type:tinyint unsigned;not null;default:20;comment:'优先级:10=低, 20=中, 30=高'"` } +const ( + ProxyScenarioInternalService string = "internal_service" + ProxyScenarioThirdPartyIntegrate string = "thrid_party_integrate" +) + type ProxyTarget struct { Name string `json:"name" gorm:"primaryKey;size:200;not null;column:name"` - Url string `json:"url" gorm:"column:url"` - ProxyUrlPrefixs string `json:"proxy_url_prefixs" gorm:"column:proxy_url_prefixs"` + Url string `json:"url" gorm:"size:255;column:url"` + Version string `json:"version" gorm:"size:64;column:version"` + ProxyUrlPrefixs string `json:"proxy_url_prefixs" gorm:"size:255;column:proxy_url_prefixs"` + Scenario string `json:"scenario" gorm:"size:64;column:scenario;default:'internal_service'"` } type Plugin struct { Name string `json:"name" gorm:"primaryKey;size:200;not null;column:name"` - AddDBServicePreCheckUrl string `json:"add_db_service_pre_check_url" gorm:"column:add_db_service_pre_check_url"` - DelDBServicePreCheckUrl string `json:"del_db_service_pre_check_url" gorm:"column:del_db_service_pre_check_url"` - DelUserPreCheckUrl string `json:"del_user_pre_check_url" gorm:"column:del_user_pre_check_url"` - DelUserGroupPreCheckUrl string `json:"del_user_group_pre_check_url" gorm:"column:del_user_group_pre_check_url"` - OperateDataResourceHandleUrl string `json:"operate_data_resource_handle_url" gorm:"column:operate_data_resource_handle_url"` + AddDBServicePreCheckUrl string `json:"add_db_service_pre_check_url" gorm:"size:255;column:add_db_service_pre_check_url"` + DelDBServicePreCheckUrl string `json:"del_db_service_pre_check_url" gorm:"size:255;column:del_db_service_pre_check_url"` + DelUserPreCheckUrl string `json:"del_user_pre_check_url" gorm:"size:255;column:del_user_pre_check_url"` + DelUserGroupPreCheckUrl string `json:"del_user_group_pre_check_url" gorm:"size:255;column:del_user_group_pre_check_url"` + OperateDataResourceHandleUrl string `json:"operate_data_resource_handle_url" gorm:"size:255;column:operate_data_resource_handle_url"` + GetDatabaseDriverOptionsUrl string `json:"get_database_driver_options_url" gorm:"size:255;column:get_database_driver_options_url"` + GetDatabaseDriverLogosUrl string `json:"get_database_driver_logos_url" gorm:"size:255;column:get_database_driver_logos_url"` +} + +type OAuth2Session struct { + Model + UserUID string `json:"user_uid" gorm:"size:32;column:user_uid"` + Sub string `json:"sub" gorm:"size:255;column:sub;index:idx_sub_sid,unique"` + Sid string `json:"sid" gorm:"size:255;column:sid;index:idx_sub_sid,unique"` + IdToken string `json:"id_token" gorm:"type:text;column:id_token"` + RefreshToken string `json:"refresh_token" gorm:"type:text;column:refresh_token"` + LastLogoutEvent sql.NullString `json:"last_logout_event" gorm:"size:255;column:last_logout_event;"` + DeleteAfter time.Time `json:"delete_after" gorm:"column:delete_after;not null;index:idx_delete_after"` // 记录保留时间,在此时间之后将删除该记录 +} + +func (OAuth2Session) TableName() string { + return "oauth2_sessions" +} + +// LoginConfiguration store local login configuration. +type LoginConfiguration struct { + Model + LoginButtonText string `json:"login_button_text" gorm:"column:login_button_text;size:255;default:'登录';not null"` + DisableUserPwdLogin bool `json:"disable_user_pwd_login" gorm:"column:disable_user_pwd_login;default:false;not null"` } // Oauth2Configuration store oauth2 server configuration. type Oauth2Configuration struct { Model - EnableOauth2 bool `json:"enable_oauth2" gorm:"column:enable_oauth2"` - ClientID string `json:"client_id" gorm:"column:client_id"` - ClientKey string `json:"-" gorm:"-"` - ClientSecret string `json:"client_secret" gorm:"client_secret"` - ClientHost string `json:"client_host" gorm:"column:client_host"` - ServerAuthUrl string `json:"server_auth_url" gorm:"column:server_auth_url"` - ServerTokenUrl string `json:"server_token_url" gorm:"column:server_token_url"` - ServerUserIdUrl string `json:"server_user_id_url" gorm:"column:server_user_id_url"` - Scopes string `json:"scopes" gorm:"column:scopes"` - AccessTokenTag string `json:"access_token_tag" gorm:"column:access_token_tag"` - UserIdTag string `json:"user_id_tag" gorm:"column:user_id_tag"` - LoginTip string `json:"login_tip" gorm:"column:login_tip; default:'使用第三方账户登录'"` + EnableOauth2 bool `json:"enable_oauth2" gorm:"column:enable_oauth2"` + SkipCheckState bool `json:"skip_check_state" gorm:"column:skip_check_state"` + EnableManuallyBind bool `json:"enable_manually_bind" gorm:"column:enable_manually_bind;default:true"` + AutoBindSameNameUser bool `json:"auto_bind_same_name_user" gorm:"column:auto_bind_same_name_user"` + AutoCreateUser bool `json:"auto_create_user" gorm:"auto_create_user"` + AutoCreateUserPWD string `json:"-" gorm:"-"` + AutoCreateUserSecret string `json:"auto_create_user_pwd" gorm:"size:255;column:auto_create_user_pwd"` + ClientID string `json:"client_id" gorm:"size:255;column:client_id"` + ClientKey string `json:"-" gorm:"-"` + ClientSecret string `json:"client_secret" gorm:"size:255;client_secret"` + ClientHost string `json:"client_host" gorm:"size:255;column:client_host"` + ServerAuthUrl string `json:"server_auth_url" gorm:"size:255;column:server_auth_url"` + ServerTokenUrl string `json:"server_token_url" gorm:"size:255;column:server_token_url"` + ServerUserIdUrl string `json:"server_user_id_url" gorm:"size:255;column:server_user_id_url"` + ServerLogoutUrl string `json:"server_logout_url" gorm:"size:255;column:server_logout_url"` + Scopes string `json:"scopes" gorm:"size:255;column:scopes"` + AccessTokenTag string `json:"access_token_tag" gorm:"size:255;column:access_token_tag"` + UserIdTag string `json:"user_id_tag" gorm:"size:255;column:user_id_tag"` + UserWeChatTag string `json:"user_wechat_tag" gorm:"size:255;column:user_wechat_tag"` + UserEmailTag string `json:"user_email_tag" gorm:"size:255;column:user_email_tag"` + LoginPermExpr string `json:"login_perm_expr" gorm:"size:255;column:login_perm_expr"` + LoginTip string `json:"login_tip" gorm:"size:255;column:login_tip; default:'使用第三方账户登录'"` } // LDAPConfiguration store ldap server configuration. @@ -196,29 +330,29 @@ type LDAPConfiguration struct { // whether the ssl is enabled EnableSSL bool `json:"enable_ssl" gorm:"not null"` // ldap server's ip - Host string `json:"host" gorm:"not null"` + Host string `json:"host" gorm:"size:255;not null"` // ldap server's port - Port string `json:"port" gorm:"not null"` + Port string `json:"port" gorm:"size:255;not null"` // the DN of the ldap administrative user for verification - ConnectDn string `json:"connect_dn" gorm:"not null"` + ConnectDn string `json:"connect_dn" gorm:"size:255;not null"` // the secret password of the ldap administrative user for verification - ConnectSecretPassword string `json:"connect_secret_password" gorm:"not null"` + ConnectSecretPassword string `json:"connect_secret_password" gorm:"size:255;not null"` // base dn used for ldap verification - BaseDn string `json:"base_dn" gorm:"not null"` + BaseDn string `json:"base_dn" gorm:"size:255;not null"` // the key corresponding to the user name in ldap - UserNameRdnKey string `json:"ldap_user_name_rdn_key" gorm:"not null"` + UserNameRdnKey string `json:"ldap_user_name_rdn_key" gorm:"size:255;not null"` // the key corresponding to the user email in ldap - UserEmailRdnKey string `json:"ldap_user_email_rdn_key" gorm:"not null"` + UserEmailRdnKey string `json:"ldap_user_email_rdn_key" gorm:"size:255;not null"` } // SMTPConfiguration store SMTP server configuration. type SMTPConfiguration struct { Model EnableSMTPNotify bool `json:"enable_smtp_notify" gorm:"default:true"` - Host string `json:"smtp_host" gorm:"column:smtp_host; not null"` - Port string `json:"smtp_port" gorm:"column:smtp_port; not null"` - Username string `json:"smtp_username" gorm:"column:smtp_username; not null"` - SecretPassword string `json:"secret_smtp_password" gorm:"column:secret_smtp_password; not null"` + Host string `json:"smtp_host" gorm:"size:255;column:smtp_host; not null"` + Port string `json:"smtp_port" gorm:"size:255;column:smtp_port; not null"` + Username string `json:"smtp_username" gorm:"size:255;column:smtp_username; not null"` + SecretPassword string `json:"secret_smtp_password" gorm:"size:255;column:secret_smtp_password; not null"` IsSkipVerify bool `json:"is_skip_verify" gorm:"default:false; not null"` } @@ -226,11 +360,11 @@ type SMTPConfiguration struct { type WeChatConfiguration struct { Model EnableWeChatNotify bool `json:"enable_wechat_notify" gorm:"not null"` - CorpID string `json:"corp_id" gorm:"not null"` - EncryptedCorpSecret string `json:"encrypted_corp_secret" gorm:"not null"` + CorpID string `json:"corp_id" gorm:"size:255;not null"` + EncryptedCorpSecret string `json:"encrypted_corp_secret" gorm:"size:255;not null"` AgentID int `json:"agent_id" gorm:"not null"` SafeEnabled bool `json:"safe_enabled" gorm:"not null"` - ProxyIP string `json:"proxy_ip"` + ProxyIP string `json:"proxy_ip" gorm:"size:255"` } type WebHookConfiguration struct { @@ -238,8 +372,18 @@ type WebHookConfiguration struct { Enable bool `json:"enable" gorm:"default:true;not null"` MaxRetryTimes int `json:"max_retry_times" gorm:"not null"` RetryIntervalSeconds int `json:"retry_interval_seconds" gorm:"not null"` - EncryptedToken string `json:"encrypted_token" gorm:"not null"` - URL string `json:"url" gorm:"not null"` + EncryptedToken string `json:"encrypted_token" gorm:"size:255;not null"` + URL string `json:"url" gorm:"size:255;not null"` +} + +type JSON json.RawMessage + +type SmsConfiguration struct { + Model + Enable bool `json:"enable" gorm:"default:true;not null"` + Type string `json:"type" gorm:"size:255;not null"` + Url string `json:"url" gorm:"size:255;not null"` + Configuration JSON `json:"configuration" gorm:"type:json"` } const ( @@ -250,22 +394,341 @@ const ( // Instant messaging config type IMConfiguration struct { Model - AppKey string `json:"app_key" gorm:"column:app_key"` - AppSecret string `json:"app_secret" gorm:"column:app_secret"` + AppKey string `json:"app_key" gorm:"size:255;column:app_key"` + AppSecret string `json:"app_secret" gorm:"size:255;column:app_secret"` IsEnable bool `json:"is_enable" gorm:"column:is_enable"` - ProcessCode string `json:"process_code" gorm:"column:process_code"` + ProcessCode string `json:"process_code" gorm:"size:255;column:process_code"` // 类型唯一 - Type string `json:"type" gorm:"unique"` + Type string `json:"type" gorm:"index:unique,size:255"` +} + +type SqlWorkbenchUserCache struct { + DMSUserID string `json:"dms_user_id" gorm:"column:dms_user_id;primaryKey"` + SqlWorkbenchUserId int64 `json:"sql_workbench_user_id" gorm:"column:sql_workbench_user_id"` + SqlWorkbenchUsername string `json:"sql_workbench_username" gorm:"size:255;column:sql_workbench_username"` +} + +type SqlWorkbenchDatasourceCache struct { + DMSDBServiceID string `json:"dms_db_service_id" gorm:"column:dms_db_service_id;primaryKey"` + DMSUserID string `json:"dms_user_id" gorm:"column:dms_user_id;primaryKey"` + DMSDBServiceFingerprint string `json:"dms_db_service_fingerprint" gorm:"size:255;column:dms_db_service_fingerprint"` + SqlWorkbenchDatasourceID int64 `json:"sql_workbench_datasource_id" gorm:"column:sql_workbench_datasource_id"` + Purpose string `json:"purpose" gorm:"size:255;column:purpose;primaryKey"` } type CloudbeaverUserCache struct { DMSUserID string `json:"dms_user_id" gorm:"column:dms_user_id;primaryKey"` - DMSFingerprint string `json:"dms_fingerprint" gorm:"column:dms_fingerprint"` - CloudbeaverUserID string `json:"cloudbeaver_user_id" gorm:"column:cloudbeaver_user_id"` + DMSFingerprint string `json:"dms_fingerprint" gorm:"size:255;column:dms_fingerprint"` + CloudbeaverUserID string `json:"cloudbeaver_user_id" gorm:"size:255;column:cloudbeaver_user_id"` } type CloudbeaverConnectionCache struct { DMSDBServiceID string `json:"dms_db_service_id" gorm:"column:dms_db_service_id;primaryKey"` - DMSDBServiceFingerprint string `json:"dms_db_service_fingerprint" gorm:"column:dms_db_service_fingerprint"` - CloudbeaverConnectionID string `json:"cloudbeaver_connection_id" gorm:"column:cloudbeaver_connection_id"` + DMSUserID string `json:"dms_user_id" gorm:"column:dms_user_id;primaryKey"` + DMSDBServiceFingerprint string `json:"dms_db_service_fingerprint" gorm:"size:255;column:dms_db_service_fingerprint"` + CloudbeaverConnectionID string `json:"cloudbeaver_connection_id" gorm:"size:255;column:cloudbeaver_connection_id"` + Purpose string `json:"purpose" gorm:"size:255;column:purpose;primaryKey"` +} + +type BasicConfig struct { + Model + Logo []byte `json:"logo" gorm:"type:mediumblob"` + Title string `json:"title" gorm:"size:100;not null;uniqueIndex" example:""` +} + +type CompanyNotice struct { + Model + CreateUserUID string `json:"create_user_uid" gorm:"column:create_user_uid;size:32;comment:'创建人uid'"` + NoticeStr string `gorm:"type:mediumtext;comment:'企业公告'" json:"notice_str"` + ReadUserIds ReadUsers `gorm:"type:longtext" json:"read_user_ids"` + StartTime *time.Time `json:"start_time" gorm:"column:start_time;comment:'公告开始时间'"` + EndTime *time.Time `json:"end_time" gorm:"column:end_time;comment:'公告结束时间'"` +} + +type ReadUsers []string + +func (t *ReadUsers) Scan(value interface{}) error { + bytesValue, _ := value.([]byte) + return json.Unmarshal(bytesValue, t) +} + +func (t ReadUsers) Value() (driver.Value, error) { + return json.Marshal(t) +} + +type ClusterLeader struct { + Anchor int `gorm:"primary_key"` // 常量值,保证该表仅有一行不重复记录。无其他意义。 + ServerId string `gorm:"not null"` + LastSeenTime time.Time `gorm:"not null"` +} + +type ClusterNodeInfo struct { + ServerId string `json:"server_id" gorm:"primary_key"` + HardwareSign string `json:"hardware_sign" gorm:"type:varchar(3000)"` + CreatedAt time.Time `json:"created_at" gorm:"<-:create" example:"2018-10-21T16:40:23+08:00"` + UpdatedAt time.Time `json:"updated_at" example:"2018-10-21T16:40:23+08:00"` } +type Workflow struct { + Model + Name string `json:"name" gorm:"size:255;not null;index:project_uid_name,unique" example:""` + ProjectUID string `json:"project_uid" gorm:"size:32;column:project_uid;index:project_uid_name,unique"` + WorkflowType string `json:"workflow_type" gorm:"size:64;column:workflow_type; not null" example:"export"` + Desc string `json:"desc" gorm:"column:desc" example:"this is a data transform export workflow"` + CreateTime *time.Time `json:"create_time" gorm:"column:create_time"` + CreateUserUID string `json:"create_user_uid" gorm:"size:32;column:create_user_uid"` + WorkflowRecordUid string `json:"workflow_record_uid" gorm:"size:32;column:workflow_record_uid"` + + WorkflowRecord *WorkflowRecord `gorm:"foreignkey:WorkflowUid"` +} + +func (w *Workflow) GetTaskIds() Strings { + return w.WorkflowRecord.TaskIds +} + +func (w *Workflow) FinalStep() *WorkflowStep { + return w.WorkflowRecord.Steps[len(w.WorkflowRecord.Steps)-1] +} + +type WorkflowRecord struct { + Model + WorkflowUid string `json:"workflow_uid" gorm:"size:32" ` + CurrentWorkflowStepId uint64 `json:"current_workflow_step_id"` + Status string `gorm:"default:\"wait_for_export\""` + TaskIds Strings `json:"task_ids" gorm:"type:json"` + + Steps []*WorkflowStep `gorm:"foreignkey:WorkflowRecordUid"` +} + +type Strings []string + +func (t *Strings) Scan(value interface{}) error { + bytesValue, _ := value.([]byte) + return json.Unmarshal(bytesValue, t) +} + +func (t Strings) Value() (driver.Value, error) { + return json.Marshal(t) +} + +type Bus []Business + +type Business struct { + Uid string + Name string +} + +func (b *Bus) Scan(value interface{}) error { + bytesValue, _ := value.([]byte) + return json.Unmarshal(bytesValue, b) +} + +func (b Bus) Value() (driver.Value, error) { + return json.Marshal(b) +} + +type WorkflowStep struct { + StepId uint64 `json:"step_id" gorm:"index:step_record_id,unique"` + WorkflowRecordUid string `gorm:"index; not null;index:step_record_id,unique"` + OperationUserUid string `json:"operation_user_uid" gorm:"size:32"` + OperateAt *time.Time `json:"operate_at"` + State string `gorm:"size:32"` + Reason string `json:"reason" gorm:"size:255"` + Assignees Strings `json:"assignees" gorm:"type:json"` +} + +type DataExportTask struct { + Model + DBServiceUid string `json:"db_service_uid" gorm:"size:32"` + DatabaseName string `json:"database_name" gorm:"size:32"` + WorkFlowRecordUid string `json:"workflow_record_uid" gorm:"size:255"` + ExportType string `json:"export_type" gorm:"size:32"` + ExportFileType string `json:"export_file_type" gorm:"size:32"` + ExportFileName string `json:"export_file_name" gorm:"column:export_file_name;size:255"` + ExportStatus string `json:"export_status" gorm:"column:export_status;size:32"` + ExportStartTime *time.Time `json:"export_start_time" gorm:"column:export_start_time"` + ExportEndTime *time.Time `json:"export_end_time" gorm:"column:export_end_time"` + CreateUserUID string `json:"create_user_uid" gorm:"size:32;column:create_user_uid"` + // Audit Result + AuditPassRate float64 `json:"audit_pass_rate"` + AuditScore int32 `json:"audit_score"` + AuditLevel string `json:"audit_level" gorm:"size:32"` + + DataExportTaskRecords []*DataExportTaskRecord `gorm:"foreignkey:DataExportTaskId"` +} + +type DataExportTaskRecord struct { + Number uint `json:"number" gorm:"index:task_id_number,unique"` + DataExportTaskId string `json:"data_export_task_id" gorm:"size:32;column:data_export_task_id;index:task_id_number,unique"` + ExportSQL string `json:"export_sql"` + ExportSQLType string `json:"export_sql_type" gorm:"column:export_sql_type;size:10"` + ExportResult string `json:"export_result"` + ExportStatus string `json:"export_status" gorm:"size:32"` + + AuditLevel string `json:"audit_level"` + AuditResults AuditResults `json:"audit_results" gorm:"type:json"` +} + +type AuditResult struct { + Level string `json:"level"` + RuleName string `json:"rule_name"` + ExecutionFailed bool `json:"execution_failed"` + I18nAuditResultInfo I18nAuditResultInfo `json:"i18n_audit_result_info"` + Message string `json:"message"` +} + +type RuleLevel string + +const ( + RuleLevelNull RuleLevel = "" // used to indicate no rank + RuleLevelNormal RuleLevel = "normal" + RuleLevelNotice RuleLevel = "notice" + RuleLevelWarn RuleLevel = "warn" + RuleLevelError RuleLevel = "error" +) + +var ruleLevelMap = map[RuleLevel]int{ + RuleLevelNull: -1, + RuleLevelNormal: 0, + RuleLevelNotice: 1, + RuleLevelWarn: 2, + RuleLevelError: 3, +} + +func (r RuleLevel) LessOrEqual(l RuleLevel) bool { + return ruleLevelMap[r] <= ruleLevelMap[l] +} + +func (ar *AuditResult) GetAuditMsgByLangTag(lang language.Tag) string { + return ar.I18nAuditResultInfo.GetAuditResultInfoByLangTag(lang).Message +} + +func (ar *AuditResult) GetAuditErrorMsgByLangTag(lang language.Tag) string { + return ar.I18nAuditResultInfo.GetAuditResultInfoByLangTag(lang).ErrorInfo +} + +type AuditResultInfo struct { + Message string + ErrorInfo string +} + +type I18nAuditResultInfo map[language.Tag]AuditResultInfo + +func (i *I18nAuditResultInfo) GetAuditResultInfoByLangTag(lang language.Tag) *AuditResultInfo { + if i == nil { + return &AuditResultInfo{} + } + + if info, ok := (*i)[lang]; ok { + return &info + } + + info := (*i)[i18nPkg.DefaultLang] + return &info +} + +type AuditResults []AuditResult + +func (a AuditResults) Value() (driver.Value, error) { + b, err := json.Marshal(a) + return string(b), err +} + +func (a *AuditResults) Scan(input interface{}) error { + if input == nil { + return nil + } + if data, ok := input.([]byte); !ok { + return fmt.Errorf("AuditResults Scan input is not bytes") + } else { + return json.Unmarshal(data, a) + } +} + +func (a *AuditResults) String() string { + msgs := make([]string, len(*a)) + for i := range *a { + res := (*a)[i] + msg := fmt.Sprintf("[%s]%s", res.Level, res.GetAuditMsgByLangTag(i18nPkg.DefaultLang)) // todo i18n other lang? + msgs[i] = msg + } + return strings.Join(msgs, "\n") +} + +func (a *AuditResults) Append(nar *AuditResult) { + for i := range *a { + ar := (*a)[i] + if ar.Level == nar.Level && ar.RuleName == nar.RuleName && ar.GetAuditMsgByLangTag(i18nPkg.DefaultLang) == nar.GetAuditMsgByLangTag(i18nPkg.DefaultLang) { + return + } + } + *a = append(*a, AuditResult{Level: nar.Level, RuleName: nar.RuleName, I18nAuditResultInfo: nar.I18nAuditResultInfo}) +} + +type CbOperationLog struct { + Model + OpPersonUID string `json:"op_person_uid" gorm:"size:32"` + OpTime *time.Time `json:"op_time"` + DBServiceUID string `json:"db_service_uid" gorm:"size:32"` + OpType string `json:"op_type" gorm:"size:255"` + I18nOpDetail i18nPkg.I18nStr `json:"i18n_op_detail" gorm:"column:i18n_op_detail; type:json"` + OpSessionID *string `json:"op_session_id" gorm:"size:255"` + ProjectID string `json:"project_id" gorm:"size:32"` + OpHost string `json:"op_host" gorm:"size:255"` + AuditResult AuditResults `json:"audit_result" gorm:"type:json"` + IsAuditPassed *bool `json:"is_audit_passed"` + ExecResult string `json:"exec_result" gorm:"type:text"` + ExecTotalSec int64 `json:"exec_total_sec"` + ResultSetRowCount int64 `json:"result_set_row_count"` + WorkflowID *string `json:"workflow_id" gorm:"size:255"` + + User *User `json:"user" gorm:"foreignKey:OpPersonUID"` + DbService *DBService `json:"db_service" gorm:"foreignKey:DBServiceUID"` + Project *Project `json:"project" gorm:"foreignKey:ProjectID"` +} + +type DBServiceSyncTask struct { + Model + Name string `json:"name" gorm:"size:200;not null;unique" example:""` + Source string `json:"source" gorm:"size:255;not null"` + URL string `json:"url" gorm:"size:255;not null"` + DbType string `json:"db_type" gorm:"size:255;not null"` + CronExpress string `json:"cron_express" gorm:"size:255;column:cron_express; not null"` + LastSyncErr string `json:"last_sync_err" gorm:"column:last_sync_err"` + LastSyncSuccessTime *time.Time `json:"last_sync_success_time" gorm:"column:last_sync_success_time"` + ExtraParameters ExtraParameters `json:"extra_parameters" gorm:"TYPE:json"` +} + +type BusinessTag struct { + Model + Name string `gorm:"type:varchar(100);unique;column:name"` +} + +type Gateway struct { + Model + Name string `gorm:"type:varchar(100);unique;column:name"` + Description string `gorm:"type:varchar(255);column:description"` + Address string `gorm:"type:varchar(255);column:address"` +} + +type SystemVariable struct { + Key string `gorm:"primary_key"` + Value string `gorm:"not null;type:text"` +} + +type OperationRecord struct { + ID uint `json:"id" gorm:"primary_key" example:"1"` + CreatedAt time.Time `json:"created_at" gorm:"default:current_timestamp(3)" example:"2018-10-21T16:40:23+08:00"` + OperationTime time.Time `gorm:"column:operation_time;type:datetime;" json:"operation_time"` + OperationUserName string `gorm:"column:operation_user_name;type:varchar(255);not null" json:"operation_user_name"` + OperationReqIP string `gorm:"column:operation_req_ip;type:varchar(255)" json:"operation_req_ip"` + OperationUserAgent string `gorm:"column:operation_user_agent;type:varchar(512)" json:"operation_user_agent"` + OperationTypeName string `gorm:"column:operation_type_name;type:varchar(255)" json:"operation_type_name"` + OperationAction string `gorm:"column:operation_action;type:varchar(255)" json:"operation_action"` + OperationProjectName string `gorm:"column:operation_project_name;type:varchar(255)" json:"operation_project_name"` + OperationStatus string `gorm:"column:operation_status;type:varchar(255)" json:"operation_status"` + OperationI18nContent i18nPkg.I18nStr `gorm:"column:operation_i18n_content;type:json" json:"operation_i18n_content"` +} + +func (OperationRecord) TableName() string { + return "operation_records" +} \ No newline at end of file diff --git a/internal/dms/storage/namespace.go b/internal/dms/storage/namespace.go deleted file mode 100644 index b27137dfa..000000000 --- a/internal/dms/storage/namespace.go +++ /dev/null @@ -1,175 +0,0 @@ -package storage - -import ( - "context" - "errors" - "fmt" - - "github.com/actiontech/dms/internal/dms/biz" - pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" - pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" - "github.com/actiontech/dms/internal/dms/storage/model" - - utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" - "gorm.io/gorm" -) - -var _ biz.NamespaceRepo = (*NamespaceRepo)(nil) - -type NamespaceRepo struct { - *Storage - log *utilLog.Helper -} - -func NewNamespaceRepo(log utilLog.Logger, s *Storage) *NamespaceRepo { - return &NamespaceRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.namespace"))} -} - -func (d *NamespaceRepo) SaveNamespace(ctx context.Context, u *biz.Namespace) error { - model, err := convertBizNamespace(u) - if err != nil { - return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert biz namespace: %v", err)) - } - - if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Create(model).Error; err != nil { - return fmt.Errorf("failed to save namespace: %v", err) - } - return nil - }); err != nil { - return err - } - - return nil -} - -func (d *NamespaceRepo) ListNamespaces(ctx context.Context, opt *biz.ListNamespacesOption, currentUserUid string) (namespaces []*biz.Namespace, total int64, err error) { - var models []*model.Namespace - - if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - // user can only view his belonging namespace,sys user can view all namespace - if currentUserUid != pkgConst.UIDOfUserSys { - tx = tx.Joins("JOIN (select namespace_uid,user_uid FROM members) as t_members ON t_members.namespace_uid = namespaces.uid AND t_members.user_uid = ? ", currentUserUid) - } - - // find models - { - db := tx.WithContext(ctx).Order(opt.OrderBy) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } - db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) - if err := db.Find(&models).Error; err != nil { - return fmt.Errorf("failed to list namespaces: %v", err) - } - } - - // find total - { - db := tx.WithContext(ctx).Model(&model.Namespace{}) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } - if err := db.Count(&total).Error; err != nil { - return fmt.Errorf("failed to count namespaces: %v", err) - } - } - return nil - }); err != nil { - return nil, 0, err - } - - // convert model to biz - for _, model := range models { - ds, err := convertModelNamespace(model) - if err != nil { - return nil, 0, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model namespaces: %v", err)) - } - // ds.CreateUserName = model.UserName - namespaces = append(namespaces, ds) - } - return namespaces, total, nil -} - -func (d *NamespaceRepo) GetNamespace(ctx context.Context, namespaceUid string) (*biz.Namespace, error) { - var namespace *model.Namespace - if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.First(&namespace, "uid = ?", namespaceUid).Error; err != nil { - return fmt.Errorf("failed to get namespace: %v", err) - } - return nil - }); err != nil { - return nil, err - } - - ret, err := convertModelNamespace(namespace) - if err != nil { - return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model namespace: %v", err)) - } - return ret, nil -} - -func (d *NamespaceRepo) GetNamespaceByName(ctx context.Context, namespaceName string) (*biz.Namespace, error) { - var namespace *model.Namespace - if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.First(&namespace, "name = ?", namespaceName).Error; err != nil { - return fmt.Errorf("failed to get namespace by name: %v", err) - } - return nil - }); err != nil { - return nil, err - } - - ret, err := convertModelNamespace(namespace) - if err != nil { - return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model namespace: %v", err)) - } - return ret, nil -} - -func (d *NamespaceRepo) UpdateNamespace(ctx context.Context, u *biz.Namespace) error { - _, err := d.GetNamespace(ctx, u.UID) - if err != nil { - if errors.Is(err, pkgErr.ErrStorageNoData) { - return pkgErr.WrapStorageErr(d.log, fmt.Errorf("namespace not exist")) - } - return err - } - - namespace, err := convertBizNamespace(u) - if err != nil { - return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert biz namespace: %v", err)) - } - - return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Model(&model.Namespace{}).Where("uid = ?", u.UID).Omit("created_at").Save(namespace).Error; err != nil { - return fmt.Errorf("failed to update namespace: %v", err) - } - return nil - }) - -} - -func (d *NamespaceRepo) DelNamespace(ctx context.Context, namespaceUid string) error { - return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Where("uid = ?", namespaceUid).Delete(&model.Namespace{}).Error; err != nil { - return fmt.Errorf("failed to delete namespace: %v", err) - } - return nil - }) -} - -func (d *NamespaceRepo) IsNamespaceActive(ctx context.Context, namespaceUid string) error { - namespace, err := d.GetNamespace(ctx, namespaceUid) - if err != nil { - if errors.Is(err, pkgErr.ErrStorageNoData) { - return pkgErr.WrapStorageErr(d.log, fmt.Errorf("namespace not exist")) - } - return err - } - - if namespace.Status != biz.NamespaceStatusActive { - return fmt.Errorf("namespace status is : %v", namespace.Status) - } - return nil -} diff --git a/internal/dms/storage/oauth2_session.go b/internal/dms/storage/oauth2_session.go new file mode 100644 index 000000000..2d9bd38a2 --- /dev/null +++ b/internal/dms/storage/oauth2_session.go @@ -0,0 +1,102 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + + "gorm.io/gorm" +) + +var _ biz.OAuth2SessionRepo = (*OAuth2SessionRepo)(nil) + +type OAuth2SessionRepo struct { + *Storage + log *utilLog.Helper +} + +func NewOAuth2SessionRepo(log utilLog.Logger, s *Storage) *OAuth2SessionRepo { + return &OAuth2SessionRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.OAuth2Session"))} +} + +func (d *OAuth2SessionRepo) SaveSession(ctx context.Context, s *biz.OAuth2Session) error { + session, err := convertBizOAuth2Session(s) + if err != nil { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert biz oauth2 session: %v", err)) + } + + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + return tx.WithContext(ctx).Save(session).Error + }) +} + +func (d *OAuth2SessionRepo) GetSessions(ctx context.Context, conditions []pkgConst.FilterCondition) (sessions []*biz.OAuth2Session, err error) { + var results []*model.OAuth2Session + err = transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + db := tx.WithContext(ctx) + for _, f := range conditions { + db = gormWhere(db, f) + } + return db.Find(&results).Error + }) + if err != nil { + return nil, err + } + + // convert model to biz + for _, res := range results { + ds, err := convertModelOAuth2Session(res) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model oauth2 session: %w", err)) + } + sessions = append(sessions, ds) + } + return sessions, nil +} + +func (d *OAuth2SessionRepo) GetSessionBySubSid(ctx context.Context, sub, sid string) (session *biz.OAuth2Session, exist bool, err error) { + record := &model.OAuth2Session{} + err = d.db.WithContext(ctx).Where("sub = ? and sid = ?", sub, sid).First(record).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, false, nil + } + return nil, false, err + } + + // convert model to biz + bizSession, err := convertModelOAuth2Session(record) + if err != nil { + return nil, true, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model oauth2 session: %w", err)) + } + + return bizSession, true, nil +} + +func (d *OAuth2SessionRepo) UpdateUserUidBySub(ctx context.Context, userUid string, sub string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + return tx.WithContext(ctx).Model(&model.OAuth2Session{}).Where("sub = ?", sub).Update("user_uid", userUid).Error + }) +} + +func (d *OAuth2SessionRepo) UpdateLogoutEvent(ctx context.Context, sub, sid, logoutIat string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + return tx.WithContext(ctx).Model(&model.OAuth2Session{}). + Where("sub = ?", sub). + Where("sid = ?", sid). + Update("last_logout_event", logoutIat).Error + }) +} + +func (d *OAuth2SessionRepo) DeleteExpiredSessions(ctx context.Context) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + return tx.WithContext(ctx).Unscoped().Delete(&model.OAuth2Session{}, "delete_after < ?", time.Now()).Error + }) +} diff --git a/internal/dms/storage/op_permission.go b/internal/dms/storage/op_permission.go index b8c1fad66..3cab212e8 100644 --- a/internal/dms/storage/op_permission.go +++ b/internal/dms/storage/op_permission.go @@ -89,9 +89,7 @@ func (d *OpPermissionRepo) ListOpPermissions(ctx context.Context, opt *biz.ListO // find models { db := tx.WithContext(ctx).Order(opt.OrderBy) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) if err := db.Find(&models).Error; err != nil { return fmt.Errorf("failed to list opPermissions: %v", err) @@ -101,9 +99,7 @@ func (d *OpPermissionRepo) ListOpPermissions(ctx context.Context, opt *biz.ListO // find total { db := tx.WithContext(ctx).Model(&model.OpPermission{}) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) if err := db.Count(&total).Error; err != nil { return fmt.Errorf("failed to count opPermissions: %v", err) } diff --git a/internal/dms/storage/op_permission_verify.go b/internal/dms/storage/op_permission_verify.go index 158ae36c6..1016c97e7 100644 --- a/internal/dms/storage/op_permission_verify.go +++ b/internal/dms/storage/op_permission_verify.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" "github.com/actiontech/dms/internal/dms/storage/model" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" @@ -22,21 +23,56 @@ func NewOpPermissionVerifyRepo(log utilLog.Logger, s *Storage) *OpPermissionVeri return &OpPermissionVerifyRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.op_permission_verify"))} } -func (o *OpPermissionVerifyRepo) IsUserHasOpPermissionInNamespace(ctx context.Context, userUid, namespaceUid, opPermissionUid string) (has bool, err error) { +func (o *OpPermissionVerifyRepo) IsUserHasOpPermissionInProject(ctx context.Context, userUid, projectUid, opPermissionUid string) (has bool, err error) { var count int64 + var memberGroupCount int64 + var projectPermissionMemberCount int64 + var projectPermissionMemberGroupCount int64 if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Raw(`SELECT count(*) FROM members AS m - JOIN member_role_op_ranges AS r ON m.uid=r.member_uid AND m.user_uid=? AND m.namespace_uid=? - JOIN role_op_permissions AS p ON r.role_uid = p.role_uid AND p.op_permission_uid = ?`, userUid, namespaceUid, opPermissionUid).Count(&count).Error; err != nil { - return fmt.Errorf("failed to check user has op permission in namespace: %v", err) + if err := tx.WithContext(ctx).Raw(` + SELECT + count(*) + FROM members AS m + JOIN member_role_op_ranges AS r ON m.uid=r.member_uid AND m.user_uid=? AND m.project_uid=? + JOIN role_op_permissions AS p ON r.role_uid = p.role_uid AND p.op_permission_uid = ?`, userUid, projectUid, opPermissionUid).Count(&count).Error; err != nil { + return fmt.Errorf("failed to check user has op permission in project: %v", err) + } + + if err := tx.WithContext(ctx).Raw(` + SELECT + count(*) + FROM member_groups AS mg + JOIN member_group_users AS mgu ON mg.uid = mgu.member_group_uid and mgu.user_uid = ? AND mg.project_uid = ? + JOIN member_group_role_op_ranges AS mgrop ON mg.uid = mgrop.member_group_uid + JOIN role_op_permissions AS rop ON mgrop.role_uid = rop.role_uid AND rop.op_permission_uid = ?`, userUid, projectUid, opPermissionUid).Count(&memberGroupCount).Error; err != nil { + return fmt.Errorf("failed to check user has op permission in project: %v", err) + } + + if err := tx.WithContext(ctx).Raw(` + SELECT + count(*) + FROM members AS m + JOIN member_op_permissions AS p ON m.uid = p.member_uid AND p.op_permission_uid = ? + WHERE m.user_uid=? AND m.project_uid=?`,opPermissionUid,userUid,projectUid).Count(&projectPermissionMemberCount).Error; err != nil { + return fmt.Errorf("failed to check user has op permission in project: %v", err) + } + + if err := tx.WithContext(ctx).Raw(` + SELECT + count(*) + FROM member_groups AS mg + JOIN member_group_users AS mgu ON mg.uid = mgu.member_group_uid and mgu.user_uid = ? AND mg.project_uid = ? + JOIN member_group_op_permissions AS p ON mg.uid = p.member_group_uid AND p.op_permission_uid = ?`,userUid,projectUid,opPermissionUid).Count(&projectPermissionMemberGroupCount).Error; err != nil { + return fmt.Errorf("failed to check user has op permission in project: %v", err) } + return nil }); err != nil { return false, err } - return count > 0, nil + return count > 0 || memberGroupCount > 0 || projectPermissionMemberCount > 0 || projectPermissionMemberGroupCount > 0, nil } -func (o *OpPermissionVerifyRepo) GetUserNamespaceWithOpPermissions(ctx context.Context, userUid string) (namespaceWithPermission []biz.NamespaceOpPermissionWithOpRange, err error) { +func (o *OpPermissionVerifyRepo) GetUserProjectWithOpPermissions(ctx context.Context, userUid string) (projectWithPermission []biz.ProjectOpPermissionWithOpRange, err error) { var ret []struct { Uid string Name string @@ -45,29 +81,42 @@ func (o *OpPermissionVerifyRepo) GetUserNamespaceWithOpPermissions(ctx context.C RangeUids string } if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Raw(`SELECT n.uid,n.name,p.op_permission_uid, r.op_range_type, r.range_uids FROM namespaces AS n - JOIN members AS m ON n.uid = m.namespace_uid + if err := tx.WithContext(ctx).Raw(` + SELECT + n.uid, n.name, p.op_permission_uid, r.op_range_type, r.range_uids + FROM projects AS n + JOIN members AS m ON n.uid = m.project_uid JOIN users AS u ON m.user_uid = u.uid AND u.uid = ? - JOIN member_role_op_ranges AS r ON m.uid=r.member_uid - JOIN role_op_permissions AS p ON r.role_uid = p.role_uid + LEFT JOIN member_role_op_ranges AS r ON m.uid=r.member_uid + LEFT JOIN role_op_permissions AS p ON r.role_uid = p.role_uid WHERE n.status = 'active' - `, userUid).Find(&ret).Error; err != nil { - return fmt.Errorf("failed to find user op permission with namespace: %v", err) + UNION + SELECT + distinct n.uid, n.name, rop.op_permission_uid, mgrop.op_range_type, mgrop.range_uids + FROM projects AS n + JOIN member_groups AS mg ON n.uid = mg.project_uid + JOIN member_group_users AS mgu ON mg.uid = mgu.member_group_uid + JOIN users AS u ON mgu.user_uid = u.uid AND u.uid = ? + LEFT JOIN member_group_role_op_ranges AS mgrop ON mg.uid=mgrop.member_group_uid + LEFT JOIN role_op_permissions AS rop ON mgrop.role_uid = rop.role_uid + WHERE n.status = 'active' + `, userUid, userUid).Find(&ret).Error; err != nil { + return fmt.Errorf("failed to find user op permission with project: %v", err) } return nil }); err != nil { return nil, err } - namespaceWithPermission = make([]biz.NamespaceOpPermissionWithOpRange, 0, len(ret)) + projectWithPermission = make([]biz.ProjectOpPermissionWithOpRange, 0, len(ret)) for _, r := range ret { typ, err := biz.ParseOpRangeType(r.OpRangeType) if err != nil { return nil, fmt.Errorf("failed to parse op range type: %v", err) } - namespaceWithPermission = append(namespaceWithPermission, biz.NamespaceOpPermissionWithOpRange{ - NamespaceUid: r.Uid, - NamespaceName: r.Name, + projectWithPermission = append(projectWithPermission, biz.ProjectOpPermissionWithOpRange{ + ProjectUid: r.Uid, + ProjectName: r.Name, OpPermissionWithOpRange: biz.OpPermissionWithOpRange{ OpPermissionUID: r.OpPermissionUid, OpRangeType: typ, @@ -75,10 +124,10 @@ func (o *OpPermissionVerifyRepo) GetUserNamespaceWithOpPermissions(ctx context.C }, }) } - return namespaceWithPermission, nil + return projectWithPermission, nil } -func (o *OpPermissionVerifyRepo) GetUserOpPermissionInNamespace(ctx context.Context, userUid, namespaceUid string) (opPermissionWithOpRanges []biz.OpPermissionWithOpRange, err error) { +func (o *OpPermissionVerifyRepo) GetUserOpPermissionInProject(ctx context.Context, userUid, projectUid string) (opPermissionWithOpRanges []biz.OpPermissionWithOpRange, err error) { type result struct { OpPermissionUid string OpRangeType string @@ -86,10 +135,23 @@ func (o *OpPermissionVerifyRepo) GetUserOpPermissionInNamespace(ctx context.Cont } var results []result if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { - if err := tx.WithContext(ctx).Raw(`SELECT p.op_permission_uid, r.op_range_type, r.range_uids FROM members AS m - JOIN member_role_op_ranges AS r ON m.uid=r.member_uid AND m.user_uid=? AND m.namespace_uid=? - JOIN role_op_permissions AS p ON r.role_uid = p.role_uid`, userUid, namespaceUid).Scan(&results).Error; err != nil { - return fmt.Errorf("failed to get user op permission in namespace: %v", err) + if err := tx.WithContext(ctx).Raw(` + SELECT + p.op_permission_uid, mror.op_range_type, mror.range_uids + FROM members AS m + JOIN member_role_op_ranges AS mror ON m.uid=mror.member_uid AND m.user_uid=? AND m.project_uid=? + JOIN role_op_permissions AS p ON mror.role_uid = p.role_uid + JOIN roles AS r ON r.uid = p.role_uid AND r.stat = 0 + UNION + SELECT + DISTINCT rop.op_permission_uid, mgror.op_range_type, mgror.range_uids + FROM member_groups mg + JOIN member_group_users mgu ON mg.uid = mgu.member_group_uid + JOIN member_group_role_op_ranges mgror ON mgu.member_group_uid = mgror.member_group_uid + JOIN role_op_permissions rop ON mgror.role_uid = rop.role_uid + JOIN roles AS r ON r.uid = rop.role_uid AND r.stat = 0 + WHERE mg.project_uid = ? and mgu.user_uid = ?`, userUid, projectUid, projectUid, userUid).Scan(&results).Error; err != nil { + return fmt.Errorf("failed to get user op permission in project: %v", err) } return nil }); err != nil { @@ -113,6 +175,99 @@ func (o *OpPermissionVerifyRepo) GetUserOpPermissionInNamespace(ctx context.Cont return opPermissionWithOpRanges, nil } +func (o *OpPermissionVerifyRepo) GetOneOpPermissionInProject(ctx context.Context, userUid, projectUid, permissionId string) (opPermissionWithOpRanges []biz.OpPermissionWithOpRange, err error) { + type result struct { + OpPermissionUid string + OpRangeType string + RangeUids string + } + var results []result + if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT + p.op_permission_uid, mror.op_range_type, mror.range_uids + FROM members AS m + JOIN member_role_op_ranges AS mror ON m.uid=mror.member_uid AND m.user_uid=? AND m.project_uid=? + JOIN role_op_permissions AS p ON mror.role_uid = p.role_uid AND p.op_permission_uid=? + JOIN roles AS r ON r.uid = p.role_uid AND r.stat = 0 + UNION + SELECT + DISTINCT rop.op_permission_uid, mgror.op_range_type, mgror.range_uids + FROM member_groups mg + JOIN member_group_users mgu ON mg.uid = mgu.member_group_uid + JOIN member_group_role_op_ranges mgror ON mgu.member_group_uid = mgror.member_group_uid + JOIN role_op_permissions rop ON mgror.role_uid = rop.role_uid AND rop.op_permission_uid=? + JOIN roles AS r ON r.uid = rop.role_uid AND r.stat = 0 + WHERE mg.project_uid = ? and mgu.user_uid = ?`, userUid, projectUid, permissionId, permissionId, projectUid, userUid).Scan(&results).Error; err != nil { + return fmt.Errorf("failed to get user op permission in project: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + opPermissionWithOpRanges = make([]biz.OpPermissionWithOpRange, 0, len(results)) + for _, r := range results { + typ, err := biz.ParseOpRangeType(r.OpRangeType) + if err != nil { + return nil, fmt.Errorf("failed to parse op range type: %v", err) + } + + opPermissionWithOpRanges = append(opPermissionWithOpRanges, biz.OpPermissionWithOpRange{ + OpPermissionUID: r.OpPermissionUid, + OpRangeType: typ, + RangeUIDs: convertModelRangeUIDs(r.RangeUids), + }) + } + + return opPermissionWithOpRanges, nil +} + + +func (o *OpPermissionVerifyRepo) GetUserProjectOpPermissionInProject(ctx context.Context, userUid, projectUid string) (opPermissionWithOpRanges []biz.OpPermissionWithOpRange, err error) { + type result struct { + OpPermissionUid string + OpRangeType string + RangeDataSourceUids string + } + var results []result + if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT + mop.op_permission_uid, 'project' as op_range_type, m.project_uid as range_uids + FROM members AS m + JOIN member_op_permissions AS mop ON m.uid=mop.member_uid AND m.user_uid=? AND m.project_uid=? + UNION + SELECT + DISTINCT mgop.op_permission_uid, 'project' as op_range_type, mg.project_uid as range_uids + FROM member_groups mg + JOIN member_group_users mgu ON mg.uid = mgu.member_group_uid + JOIN member_group_op_permissions AS mgop ON mg.uid = mgop.member_group_uid + WHERE mg.project_uid = ? and mgu.user_uid = ?`, userUid, projectUid, projectUid, userUid).Scan(&results).Error; err != nil { + return fmt.Errorf("failed to get user op permission in project: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + opPermissionWithOpRanges = make([]biz.OpPermissionWithOpRange, 0, len(results)) + for _, r := range results { + typ, err := biz.ParseOpRangeType(r.OpRangeType) + if err != nil { + return nil, fmt.Errorf("failed to parse op range type: %v", err) + } + + opPermissionWithOpRanges = append(opPermissionWithOpRanges, biz.OpPermissionWithOpRange{ + OpPermissionUID: r.OpPermissionUid, + OpRangeType: typ, + RangeUIDs: convertModelRangeUIDs(r.RangeDataSourceUids), + }) + } + + return opPermissionWithOpRanges, nil +} + func (o *OpPermissionVerifyRepo) GetUserOpPermission(ctx context.Context, userUid string) (opPermissionWithOpRanges []biz.OpPermissionWithOpRange, err error) { type result struct { OpPermissionUid string @@ -126,7 +281,14 @@ func (o *OpPermissionVerifyRepo) GetUserOpPermission(ctx context.Context, userUi p.op_permission_uid, r.op_range_type, r.range_uids FROM members AS m JOIN member_role_op_ranges AS r ON m.uid=r.member_uid AND m.user_uid = ? - JOIN role_op_permissions AS p ON r.role_uid = p.role_uid`, userUid).Scan(&results).Error; err != nil { + JOIN role_op_permissions AS p ON r.role_uid = p.role_uid + UNION + select + distinct rop.op_permission_uid, mgror.op_range_type, mgror.range_uids + from member_group_users mgu + join member_group_role_op_ranges mgror on mgu.member_group_uid = mgror.member_group_uid + join role_op_permissions rop on mgror.role_uid = rop.role_uid + where mgu.user_uid = ?`, userUid, userUid).Scan(&results).Error; err != nil { return fmt.Errorf("failed to get user op permission: %v", err) } return nil @@ -151,6 +313,50 @@ func (o *OpPermissionVerifyRepo) GetUserOpPermission(ctx context.Context, userUi return opPermissionWithOpRanges, nil } +func (o *OpPermissionVerifyRepo) GetUserProjectOpPermission(ctx context.Context, userUid string) (opPermissionWithOpRanges []biz.OpPermissionWithOpRange, err error) { + type result struct { + OpPermissionUid string + OpRangeType string + RangeDataSourceUids string + } + var results []result + if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT + mop.op_permission_uid, 'project' as op_range_type, m.project_uid as range_uids + FROM members AS m + JOIN member_op_permissions AS mop ON m.uid=mop.member_uid AND m.user_uid=? + UNION + SELECT + DISTINCT mgop.op_permission_uid, 'project' as op_range_type, mg.project_uid as range_uids + FROM member_groups mg + JOIN member_group_users mgu ON mg.uid = mgu.member_group_uid + JOIN member_group_op_permissions AS mgop ON mg.uid = mgop.member_group_uid + WHERE mgu.user_uid = ?`, userUid, userUid).Scan(&results).Error; err != nil { + return fmt.Errorf("failed to get user op permission: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + opPermissionWithOpRanges = make([]biz.OpPermissionWithOpRange, 0, len(results)) + for _, r := range results { + typ, err := biz.ParseOpRangeType(r.OpRangeType) + if err != nil { + return nil, fmt.Errorf("failed to parse op range type: %v", err) + } + + opPermissionWithOpRanges = append(opPermissionWithOpRanges, biz.OpPermissionWithOpRange{ + OpPermissionUID: r.OpPermissionUid, + OpRangeType: typ, + RangeUIDs: convertModelRangeUIDs(r.RangeDataSourceUids), + }) + } + + return opPermissionWithOpRanges, nil +} + func (o *OpPermissionVerifyRepo) GetUserGlobalOpPermission(ctx context.Context, userUid string) (opPermissions []*biz.OpPermission, err error) { ops := []*model.OpPermission{} if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { @@ -175,9 +381,8 @@ func (o *OpPermissionVerifyRepo) GetUserGlobalOpPermission(ctx context.Context, return opPermissions, nil } -func (o *OpPermissionVerifyRepo) ListMembersOpPermissionInNamespace(ctx context.Context, namespaceUid string, opt *biz.ListMembersOpPermissionOption) (items []biz.ListMembersOpPermissionItem, total int64, err error) { +func (o *OpPermissionVerifyRepo) ListUsersOpPermissionInProject(ctx context.Context, projectUid string, opt *biz.ListMembersOpPermissionOption) (items []biz.ListMembersOpPermissionItem, total int64, err error) { type result struct { - MemberUid string UserUid string UserName string OpPermissionUid string @@ -185,25 +390,74 @@ func (o *OpPermissionVerifyRepo) ListMembersOpPermissionInNamespace(ctx context. RangeUids string } var results []result + var permissionResults []result if err := transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { - // opt中的分页属性作用于空间内的成员,即opt.LimitPerPage表示返回opt.LimitPerPage个成员的权限 + // opt中的分页属性作用于项目内的成员,即opt.LimitPerPage表示返回opt.LimitPerPage个成员的权限 // find result { - if err := tx.WithContext(ctx).Raw(`SELECT um.member_uid, um.user_uid, um.user_name, p.op_permission_uid, r.op_range_type, r.range_uids FROM - (SELECT m.user_uid AS user_uid, u.name AS user_name, m.uid AS member_uid FROM members AS m JOIN users AS u ON m.user_uid = u.uid AND m.namespace_uid=? ORDER BY m.user_uid LIMIT ? OFFSET ?) AS um - LEFT JOIN member_role_op_ranges AS r ON um.member_uid=r.member_uid - LEFT JOIN role_op_permissions AS p ON r.role_uid = p.role_uid`, - namespaceUid, opt.LimitPerPage, opt.LimitPerPage*(uint32(fixPageIndices(opt.PageNumber)))).Scan(&results).Error; err != nil { - return fmt.Errorf("failed to list member op permission in namespace: %v", err) + if err := tx.WithContext(ctx).Raw(` + SELECT * FROM ( + SELECT + m.user_uid, u.name AS user_name + FROM + members AS m JOIN users AS u ON m.user_uid = u.uid AND m.project_uid = ? + UNION + SELECT + DISTINCT u.uid AS user_uid, u.name AS user_name + FROM + member_groups AS mg + JOIN member_group_users mgu on mg.uid = mgu.member_group_uid AND mg.project_uid = ? + JOIN users AS u ON mgu.user_uid = u.uid + ) TEMP ORDER BY user_uid LIMIT ? OFFSET ?`, + projectUid, projectUid, opt.LimitPerPage, opt.LimitPerPage*(uint32(fixPageIndices(opt.PageNumber)))).Scan(&results).Error; err != nil { + return fmt.Errorf("failed to list user op permission in project: %v", err) } } // find total { - if err := tx.WithContext(ctx).Raw(`SELECT COUNT(*) FROM members AS m JOIN users AS u ON m.user_uid = u.uid AND m.namespace_uid=?`, - namespaceUid).Scan(&total).Error; err != nil { - return fmt.Errorf("failed to list total member op permission in namespace: %v", err) + if err := tx.WithContext(ctx).Raw(` + SELECT COUNT(*) FROM ( + SELECT + m.user_uid, u.name AS user_name + FROM members AS m + JOIN users AS u ON m.user_uid = u.uid AND m.project_uid=? + UNION + SELECT + DISTINCT u.uid AS user_uid, u.name AS user_name + FROM member_groups AS mg + JOIN member_group_users mgu on mg.uid = mgu.member_group_uid AND mg.project_uid = ? + JOIN users AS u ON mgu.user_uid = u.uid + ) TEMP`, + projectUid, projectUid).Scan(&total).Error; err != nil { + return fmt.Errorf("failed to list total user op permission in project: %v", err) + } + } + + if len(results) > 0 { + userIds := make([]string, 0) + for _, item := range results { + userIds = append(userIds, item.UserUid) + } + + { + if err = tx.WithContext(ctx).Raw(` + SELECT + m.user_uid, p.op_permission_uid, r.op_range_type, r.range_uids + FROM members AS m + JOIN member_role_op_ranges AS r ON m.uid=r.member_uid AND m.user_uid in (?) AND m.project_uid=? + JOIN role_op_permissions AS p ON r.role_uid = p.role_uid + UNION + SELECT + DISTINCT mgu.user_uid, rop.op_permission_uid, mgror.op_range_type, mgror.range_uids + FROM member_groups mg + JOIN member_group_users mgu ON mg.uid = mgu.member_group_uid + JOIN member_group_role_op_ranges mgror ON mgu.member_group_uid = mgror.member_group_uid + JOIN role_op_permissions rop ON mgror.role_uid = rop.role_uid + WHERE mg.project_uid = ? and mgu.user_uid in (?)`, userIds, projectUid, projectUid, userIds).Scan(&permissionResults).Error; err != nil { + return fmt.Errorf("failed to get user op permission in project: %v", err) + } } } @@ -213,38 +467,117 @@ func (o *OpPermissionVerifyRepo) ListMembersOpPermissionInNamespace(ctx context. } resultGroupByUser := make(map[string][]result) - for _, r := range results { + for _, r := range permissionResults { resultGroupByUser[r.UserUid] = append(resultGroupByUser[r.UserUid], r) } - for _, rs := range resultGroupByUser { - opPermissionWithOpRanges := make([]biz.OpPermissionWithOpRange, 0, len(rs)) + for _, rs := range results { + opPermissionWithOpRanges := make([]biz.OpPermissionWithOpRange, 0) - for _, r := range rs { - // 这里表示没有任何角色权限的成员 - if r.OpRangeType == "" { - continue - } - typ, err := biz.ParseOpRangeType(r.OpRangeType) - if err != nil { - return nil, 0, fmt.Errorf("failed to parse op range type: %v", err) - } + if permissionItems, ok := resultGroupByUser[rs.UserUid]; ok { + for _, r := range permissionItems { + // 这里表示没有任何角色权限的成员 + if r.OpRangeType == "" { + continue + } + typ, err := biz.ParseOpRangeType(r.OpRangeType) + if err != nil { + return nil, 0, fmt.Errorf("failed to parse op range type: %v", err) + } - opPermissionWithOpRanges = append(opPermissionWithOpRanges, biz.OpPermissionWithOpRange{ - OpPermissionUID: r.OpPermissionUid, - OpRangeType: typ, - RangeUIDs: convertModelRangeUIDs(r.RangeUids), - }) + opPermissionWithOpRanges = append(opPermissionWithOpRanges, biz.OpPermissionWithOpRange{ + OpPermissionUID: r.OpPermissionUid, + OpRangeType: typ, + RangeUIDs: convertModelRangeUIDs(r.RangeUids), + }) + } } items = append(items, biz.ListMembersOpPermissionItem{ - MemberUid: rs[0].MemberUid, - UserUid: rs[0].UserUid, - UserName: rs[0].UserName, + UserUid: rs.UserUid, + UserName: rs.UserName, OpPermissions: opPermissionWithOpRanges, }) - } return items, total, nil } + +func (o *OpPermissionVerifyRepo) ListUsersInProject(ctx context.Context, projectUid string) (items []biz.ListMembersOpPermissionItem, err error) { + type result struct { + UserUid string + UserName string + } + var results []result + if err = transaction(o.log, ctx, o.db, func(tx *gorm.DB) error { + // find result + { + if err = tx.WithContext(ctx).Raw(` + SELECT * FROM ( + SELECT + m.user_uid, u.name AS user_name + FROM + members AS m JOIN users AS u ON m.user_uid = u.uid AND m.project_uid = ? + UNION + SELECT + DISTINCT u.uid AS user_uid, u.name AS user_name + FROM + member_groups AS mg + JOIN member_group_users mgu on mg.uid = mgu.member_group_uid AND mg.project_uid = ? + JOIN users AS u ON mgu.user_uid = u.uid + ) TEMP`, + projectUid, projectUid).Scan(&results).Error; err != nil { + return fmt.Errorf("failed to list users in project: %v", err) + } + } + + return nil + }); err != nil { + return nil, err + } + + for _, rs := range results { + items = append(items, biz.ListMembersOpPermissionItem{ + UserUid: rs.UserUid, + UserName: rs.UserName, + }) + } + + return items, nil +} + +func (d *OpPermissionVerifyRepo) GetUserProject(ctx context.Context, userUid string) (projects []*biz.Project, err error) { + var models []*model.Project + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT + n.* + FROM + projects n + JOIN members m ON n.uid = m.project_uid + JOIN users u ON m.user_uid = u.uid AND u.uid = ? + UNION + SELECT + DISTINCT n.* + FROM + projects n + JOIN member_groups mg on n.uid = mg.project_uid + JOIN member_group_users mgu ON mgu.member_group_uid = mg.uid + JOIN users u ON mgu.user_uid = u.uid AND u.uid = ? + `, userUid, userUid).Scan(&models).Error; err != nil { + return fmt.Errorf("failed to list user project: %v", err) + } + return nil + }); err != nil { + return nil, err + } + // convert model to biz + for _, model := range models { + ds, err := convertModelProject(model) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model projects: %v", err)) + } + projects = append(projects, ds) + } + return projects, nil +} diff --git a/internal/dms/storage/operation_record.go b/internal/dms/storage/operation_record.go new file mode 100644 index 000000000..90a7ae964 --- /dev/null +++ b/internal/dms/storage/operation_record.go @@ -0,0 +1,180 @@ +package storage + +import ( + "context" + "fmt" + "time" + + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.OperationRecordRepo = (*operationRecordRepo)(nil) + +type operationRecordRepo struct { + *Storage + log *utilLog.Helper +} + +func NewOperationRecordRepo(log utilLog.Logger, s *Storage) biz.OperationRecordRepo { + return &operationRecordRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.operationRecord"))} +} + +func (d *operationRecordRepo) SaveOperationRecord(ctx context.Context, record *biz.OperationRecord) error { + model := convertBizOperationRecord(record) + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Create(model).Error; err != nil { + return fmt.Errorf("failed to save operation record: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func applyOperationRecordFilters(db *gorm.DB, opt *biz.ListOperationRecordOption) *gorm.DB { + if opt.FilterOperateTimeFrom != "" { + db = db.Where("operation_time > ?", opt.FilterOperateTimeFrom) + } + if opt.FilterOperateTimeTo != "" { + db = db.Where("operation_time < ?", opt.FilterOperateTimeTo) + } + // 项目过滤:如果指定了项目,已经通过权限校验,直接使用该过滤条件 + if opt.FilterOperateProjectName != nil { + db = db.Where("operation_project_name = ?", *opt.FilterOperateProjectName) + } else { + // 如果没指定项目,根据权限过滤 + if !opt.CanViewGlobal && len(opt.AccessibleProjectNames) > 0 { + // 项目管理员只能查看对应项目下的操作记录 + db = db.Where("operation_project_name IN ?", opt.AccessibleProjectNames) + } + // 如果 CanViewGlobal 为 true,不添加项目过滤(可以查看所有项目,包括空字符串) + } + if opt.FuzzySearchOperateUserName != "" { + db = db.Where("operation_user_name LIKE ?", "%"+opt.FuzzySearchOperateUserName+"%") + } + if opt.FilterOperateTypeName != "" { + db = db.Where("operation_type_name = ?", opt.FilterOperateTypeName) + } + if opt.FilterOperateAction != "" { + db = db.Where("operation_action = ?", opt.FilterOperateAction) + } + return db +} + +func (d *operationRecordRepo) ListOperationRecords(ctx context.Context, opt *biz.ListOperationRecordOption) ([]*biz.OperationRecord, uint64, error) { + var models []*model.OperationRecord + var total int64 + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find models + { + db := tx.WithContext(ctx).Model(&model.OperationRecord{}) + db = applyOperationRecordFilters(db, opt) + + // Order and pagination + db = db.Order("operation_time DESC") + offset := (opt.PageIndex - 1) * opt.PageSize + db = db.Limit(int(opt.PageSize)).Offset(int(offset)) + + if err := db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to list operation records: %v", err) + } + } + + // find total + { + db := tx.WithContext(ctx).Model(&model.OperationRecord{}) + db = applyOperationRecordFilters(db, opt) + + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count operation records: %v", err) + } + } + return nil + }); err != nil { + return nil, 0, err + } + + ret := make([]*biz.OperationRecord, 0) + for _, m := range models { + record := convertModelOperationRecord(m) + ret = append(ret, record) + } + + return ret, uint64(total), nil +} + +func (d *operationRecordRepo) ExportOperationRecords(ctx context.Context, opt *biz.ListOperationRecordOption) ([]*biz.OperationRecord, error) { + var models []*model.OperationRecord + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + db := tx.WithContext(ctx).Model(&model.OperationRecord{}) + db = applyOperationRecordFilters(db, opt) + + // Order by time DESC, no pagination for export + db = db.Order("operation_time DESC") + + if err := db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to export operation records: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + ret := make([]*biz.OperationRecord, 0) + for _, m := range models { + record := convertModelOperationRecord(m) + ret = append(ret, record) + } + + return ret, nil +} + +func (d *operationRecordRepo) CleanOperationRecordOpTimeBefore(ctx context.Context, t time.Time) (rowsAffected int64, err error) { + err = transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + result := tx.WithContext(ctx).Unscoped().Delete(&model.OperationRecord{}, "operation_time < ?", t) + if err := result.Error; err != nil { + return err + } + rowsAffected = result.RowsAffected + return nil + }) + return +} + +func convertBizOperationRecord(src *biz.OperationRecord) *model.OperationRecord { + return &model.OperationRecord{ + ID: src.ID, + OperationTime: src.OperationTime, + OperationUserName: src.OperationUserName, + OperationReqIP: src.OperationReqIP, + OperationUserAgent: src.OperationUserAgent, + OperationTypeName: src.OperationTypeName, + OperationAction: src.OperationAction, + OperationProjectName: src.OperationProjectName, + OperationStatus: src.OperationStatus, + OperationI18nContent: src.OperationI18nContent, + } +} + +func convertModelOperationRecord(model *model.OperationRecord) *biz.OperationRecord { + return &biz.OperationRecord{ + ID: model.ID, + OperationTime: model.OperationTime, + OperationUserName: model.OperationUserName, + OperationReqIP: model.OperationReqIP, + OperationUserAgent: model.OperationUserAgent, + OperationTypeName: model.OperationTypeName, + OperationAction: model.OperationAction, + OperationProjectName: model.OperationProjectName, + OperationStatus: model.OperationStatus, + OperationI18nContent: model.OperationI18nContent, + } +} diff --git a/internal/dms/storage/project.go b/internal/dms/storage/project.go new file mode 100644 index 000000000..29b38fe71 --- /dev/null +++ b/internal/dms/storage/project.go @@ -0,0 +1,206 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.ProjectRepo = (*ProjectRepo)(nil) + +type ProjectRepo struct { + *Storage + log *utilLog.Helper +} + +func NewProjectRepo(log utilLog.Logger, s *Storage) *ProjectRepo { + return &ProjectRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.project"))} +} + +func (d *ProjectRepo) SaveProject(ctx context.Context, u *biz.Project) error { + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Create(convertBizProject(u)).Error; err != nil { + return fmt.Errorf("failed to save project: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *ProjectRepo) BatchSaveProjects(ctx context.Context, projects []*biz.Project) error { + models := make([]*model.Project, 0) + for _, project := range projects { + models = append(models, convertBizProject(project)) + } + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).CreateInBatches(models, 50).Error; err != nil { + return fmt.Errorf("failed to batch save projects: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +// TODO currentUserUid 未生效 +func (d *ProjectRepo) ListProjects(ctx context.Context, opt *biz.ListProjectsOption, currentUserUid string) (projects []*biz.Project, total int64, err error) { + var models []*model.Project + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + + // find models + { + db := tx.WithContext(ctx).Order(opt.OrderBy) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + if err := db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to list projects: %v", err) + } + } + + // find total + { + db := tx.WithContext(ctx).Model(&model.Project{}) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count projects: %v", err) + } + } + return nil + }); err != nil { + return nil, 0, err + } + + // convert model to biz + for _, model := range models { + ds, err := convertModelProject(model) + if err != nil { + return nil, 0, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model projects: %v", err)) + } + // ds.CreateUserName = model.UserName + projects = append(projects, ds) + } + return projects, total, nil +} + +func (d *ProjectRepo) GetProject(ctx context.Context, projectUid string) (*biz.Project, error) { + var project *model.Project + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.First(&project, "uid = ?", projectUid).Error; err != nil { + return fmt.Errorf("failed to get project: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + ret, err := convertModelProject(project) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model project: %v", err)) + } + return ret, nil +} + +func (d *ProjectRepo) GetProjectByName(ctx context.Context, projectName string) (*biz.Project, error) { + var project *model.Project + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.First(&project, "name = ?", projectName).Error; err != nil { + return fmt.Errorf("failed to get project by name: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + ret, err := convertModelProject(project) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model project: %v", err)) + } + return ret, nil +} + +func (d *ProjectRepo) GetProjectByNames(ctx context.Context, projectNames []string) ([]*biz.Project, error) { + var projects []*model.Project + bizProjects := make([]*biz.Project, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Where("name IN (?)", projectNames).Find(&projects).Error; err != nil { + return fmt.Errorf("failed to get project by name: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + for _, project := range projects { + bizProject, err := convertModelProject(project) + if err != nil { + continue + } + bizProjects = append(bizProjects, bizProject) + } + return bizProjects, nil +} + +func (d *ProjectRepo) UpdateProject(ctx context.Context, u *biz.Project) error { + _, err := d.GetProject(ctx, u.UID) + if err != nil { + if errors.Is(err, pkgErr.ErrStorageNoData) { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("project not exist")) + } + return err + } + + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.Project{}).Where("uid = ?", u.UID).Omit("created_at").Save(convertBizProject(u)).Error; err != nil { + return fmt.Errorf("failed to update project: %v", err) + } + return nil + }) + +} + +func (d *ProjectRepo) DelProject(ctx context.Context, projectUid string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("uid = ?", projectUid).Delete(&model.Project{}).Error; err != nil { + return fmt.Errorf("failed to delete project: %v", err) + } + return nil + }) +} + +func (d *ProjectRepo) UpdateDBServiceBusiness(ctx context.Context, projectUid string, originBusiness string, descBusiness string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.DBService{}).Where("project_uid = ? and business = ?", projectUid, originBusiness). + Update("business", descBusiness).Error; err != nil { + return fmt.Errorf("failed to update dbService business: %v", err) + } + return nil + }) +} + +func (d *ProjectRepo) IsProjectActive(ctx context.Context, projectUid string) error { + project, err := d.GetProject(ctx, projectUid) + if err != nil { + if errors.Is(err, pkgErr.ErrStorageNoData) { + return pkgErr.WrapStorageErr(d.log, fmt.Errorf("project not exist")) + } + return err + } + + if project.Status != biz.ProjectStatusActive { + return fmt.Errorf("project status is : %v", project.Status) + } + return nil +} diff --git a/internal/dms/storage/proxy.go b/internal/dms/storage/proxy.go index 6accce40d..6b35f5056 100644 --- a/internal/dms/storage/proxy.go +++ b/internal/dms/storage/proxy.go @@ -79,6 +79,32 @@ func (d *ProxyTargetRepo) CheckProxyTargetExist(ctx context.Context, targetNames return true, nil } +func (d *ProxyTargetRepo) ListProxyTargetsByScenarios(ctx context.Context, scenarios []biz.ProxyScenario) (targets []*biz.ProxyTarget, err error) { + + var models []*model.ProxyTarget + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + + // find targets + if err := tx.WithContext(ctx).Where("scenario IN (?)", scenarios).Find(&models).Error; err != nil { + return fmt.Errorf("failed to list proxy targets: %v", err) + } + + return nil + }); err != nil { + return nil, err + } + + // convert model to biz + for _, model := range models { + t, err := convertModelProxyTarget(model) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model proxy targets: %v", err)) + } + targets = append(targets, t) + } + return targets, nil +} + func (d *ProxyTargetRepo) ListProxyTargets(ctx context.Context) (targets []*biz.ProxyTarget, err error) { var models []*model.ProxyTarget @@ -109,10 +135,9 @@ func (d *ProxyTargetRepo) GetProxyTargetByName(ctx context.Context, name string) var target model.ProxyTarget if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - - // find targets - if err := tx.WithContext(ctx).Where(&model.ProxyTarget{Name: name}).Find(&target).Error; err != nil { - return fmt.Errorf("failed to list proxy target: %v", err) + // get targets + if err := tx.First(&target, "name = ?", name).Error; err != nil { + return fmt.Errorf("failed to get proxy target: %v", err) } return nil diff --git a/internal/dms/storage/resource_overview.go b/internal/dms/storage/resource_overview.go new file mode 100644 index 000000000..a0411f400 --- /dev/null +++ b/internal/dms/storage/resource_overview.go @@ -0,0 +1,17 @@ +package storage + +import ( + "github.com/actiontech/dms/internal/dms/biz" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +var _ biz.ResourceOverviewRepo = (*ResourceOverviewRepo)(nil) + +type ResourceOverviewRepo struct { + *Storage + log *utilLog.Helper +} + +func NewResourceOverviewRepo(log utilLog.Logger, s *Storage) *ResourceOverviewRepo { + return &ResourceOverviewRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.resource_overview"))} +} diff --git a/internal/dms/storage/resource_overview_ce.go b/internal/dms/storage/resource_overview_ce.go new file mode 100644 index 000000000..a0672f992 --- /dev/null +++ b/internal/dms/storage/resource_overview_ce.go @@ -0,0 +1,14 @@ +//go:build !enterprise + +package storage + +import ( + "context" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" +) + +func (repo *ResourceOverviewRepo) GetResourceList(ctx context.Context, listOptions biz.ListResourceOverviewOption) ([]*biz.ResourceRow, int64, error) { + return nil, 0, fmt.Errorf("resource overview is enterprise version functions") +} diff --git a/internal/dms/storage/role.go b/internal/dms/storage/role.go index 7d8979ace..fad68e1ca 100644 --- a/internal/dms/storage/role.go +++ b/internal/dms/storage/role.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" "github.com/actiontech/dms/internal/dms/storage/model" @@ -59,6 +60,23 @@ func (d *RoleRepo) CheckRoleExist(ctx context.Context, roleUids []string) (exist return true, nil } +func (d *RoleRepo) CheckRoleExistByRoleName(ctx context.Context, name string) (exists bool, err error) { + var count int64 + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.Role{}).Where("name = ?", name).Count(&count).Error; err != nil { + return fmt.Errorf("failed to check role exist: %v", err) + } + return nil + }); err != nil { + return false, err + } + + if count > 0 { + return true, nil + } + return false, nil +} + func (d *RoleRepo) UpdateRole(ctx context.Context, u *biz.Role) error { exist, err := d.CheckRoleExist(ctx, []string{u.UID}) if err != nil { @@ -118,17 +136,49 @@ func (d *RoleRepo) ReplaceOpPermissionsInRole(ctx context.Context, roleUid strin } func (d *RoleRepo) ListRoles(ctx context.Context, opt *biz.ListRolesOption) (roles []*biz.Role, total int64, err error) { + // 取出权限条件的值 + opPermissionValue := "" + filterByOptionsWithoutOpPermission := pkgConst.FilterOptions{ + Logic: opt.FilterByOptions.Logic, + Groups: make([]pkgConst.FilterConditionGroup, 0, len(opt.FilterByOptions.Groups)), + } - var models []*model.Role + for _, group := range opt.FilterByOptions.Groups { + newGroup := pkgConst.FilterConditionGroup{ + Logic: group.Logic, + Conditions: make([]pkgConst.FilterCondition, 0, len(group.Conditions)), + Groups: group.Groups, + } + + for _, condition := range group.Conditions { + if condition.Field == string(biz.RoleFieldOpPermission) { + if opPermissionValue == "" { + opPermissionValue = condition.Value.(string) + } + continue + } + newGroup.Conditions = append(newGroup.Conditions, condition) + } + + if len(newGroup.Conditions) > 0 || len(newGroup.Groups) > 0 { + filterByOptionsWithoutOpPermission.Groups = append(filterByOptionsWithoutOpPermission.Groups, newGroup) + } + } + + var roleModels []*model.Role if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { // find models { - db := tx.WithContext(ctx).Order(opt.OrderBy) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) + db := tx.WithContext(ctx).Order(string(opt.OrderBy) + " DESC") + db = gormWheresWithOptions(ctx, db, filterByOptionsWithoutOpPermission) + if opPermissionValue != "" { + db = db.Joins("JOIN role_op_permissions on roles.uid = role_op_permissions.role_uid"). + Joins("JOIN op_permissions ON op_permissions.uid = role_op_permissions.op_permission_uid"). + Where("op_permissions.name like ?", "%"+opPermissionValue+"%"). + Group("roles.uid") } db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) - if err := db.Find(&models).Error; err != nil { + if err := db.Find(&roleModels).Error; err != nil { return fmt.Errorf("failed to list roles: %v", err) } } @@ -136,8 +186,12 @@ func (d *RoleRepo) ListRoles(ctx context.Context, opt *biz.ListRolesOption) (rol // find total { db := tx.WithContext(ctx).Model(&model.Role{}) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) + db = gormWheresWithOptions(ctx, db, filterByOptionsWithoutOpPermission) + if opPermissionValue != "" { + db = db.Joins("JOIN role_op_permissions on roles.uid = role_op_permissions.role_uid"). + Joins("JOIN op_permissions ON op_permissions.uid = role_op_permissions.op_permission_uid"). + Where("op_permissions.name like ?", "%"+opPermissionValue+"%"). + Group("roles.uid") } if err := db.Count(&total).Error; err != nil { return fmt.Errorf("failed to count roles: %v", err) @@ -149,8 +203,8 @@ func (d *RoleRepo) ListRoles(ctx context.Context, opt *biz.ListRolesOption) (rol } // convert model to biz - for _, model := range models { - ds, err := convertModelRole(model) + for _, role := range roleModels { + ds, err := convertModelRole(role) if err != nil { return nil, 0, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model roles: %v", err)) } @@ -168,10 +222,19 @@ func (d *RoleRepo) DelRole(ctx context.Context, roleUid string) error { }) } +func (d *RoleRepo) DelRoleFromAllMemberGroups(ctx context.Context, roleUid string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("role_uid = ?", roleUid).Delete(&model.MemberGroupRoleOpRange{}).Error; err != nil { + return fmt.Errorf("failed to delete role from all member groups: %v", err) + } + return nil + }) +} + func (d *RoleRepo) GetRole(ctx context.Context, roleUid string) (*biz.Role, error) { var role *model.Role if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { - if err := tx.First(&role, "uid = ?", roleUid).Error; err != nil { + if err := tx.Preload("OpPermissions").First(&role, "uid = ?", roleUid).Error; err != nil { return fmt.Errorf("failed to get role: %v", err) } return nil diff --git a/internal/dms/storage/sensitive_data_discovery_task_ce.go b/internal/dms/storage/sensitive_data_discovery_task_ce.go new file mode 100644 index 000000000..a23fda70b --- /dev/null +++ b/internal/dms/storage/sensitive_data_discovery_task_ce.go @@ -0,0 +1,23 @@ +//go:build !dms + +package storage + +import ( + "context" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +type SensitiveDataDiscoveryTaskRepo struct{} + +func NewSensitiveDataDiscoveryTaskRepo(_ utilLog.Logger, _ *Storage) *SensitiveDataDiscoveryTaskRepo { + return &SensitiveDataDiscoveryTaskRepo{} +} + +func (r *SensitiveDataDiscoveryTaskRepo) CheckMaskingTaskExist(_ context.Context, _ string) (bool, error) { + return false, nil +} + +func (r *SensitiveDataDiscoveryTaskRepo) ListMaskingTaskStatus(_ context.Context, _ []string) (map[string]bool, error) { + return map[string]bool{}, nil +} diff --git a/internal/dms/storage/sms_configuration.go b/internal/dms/storage/sms_configuration.go new file mode 100644 index 000000000..06a78703a --- /dev/null +++ b/internal/dms/storage/sms_configuration.go @@ -0,0 +1,47 @@ +package storage + +import ( + "context" + "fmt" + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.SmsConfigurationRepo = (*SmsConfigurationRepo)(nil) + +type SmsConfigurationRepo struct { + *Storage + log *utilLog.Helper +} + +func NewSmsConfigurationRepo(log utilLog.Logger, s *Storage) *SmsConfigurationRepo { + return &SmsConfigurationRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.sms_configuration"))} +} + +func (d *SmsConfigurationRepo) UpdateSmsConfiguration(ctx context.Context, smsConfiguration *model.SmsConfiguration) error { + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(smsConfiguration).Where("uid = ?", smsConfiguration.UID).Omit("created_at").Save(smsConfiguration).Error; err != nil { + return fmt.Errorf("failed to save sms configuration: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *SmsConfigurationRepo) GetLastSmsConfiguration(ctx context.Context) (*model.SmsConfiguration, error) { + var smsConfiguration *model.SmsConfiguration + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Last(&smsConfiguration).Error; err != nil { + return fmt.Errorf("failed to get sms configuration: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return smsConfiguration, nil +} \ No newline at end of file diff --git a/internal/dms/storage/sql_workbench.go b/internal/dms/storage/sql_workbench.go new file mode 100644 index 000000000..613163ac4 --- /dev/null +++ b/internal/dms/storage/sql_workbench.go @@ -0,0 +1,151 @@ +package storage + +import ( + "context" + "errors" + "fmt" + + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/storage/model" + "gorm.io/gorm" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +var _ biz.SqlWorkbenchUserRepo = (*SqlWorkbenchRepo)(nil) + +type SqlWorkbenchRepo struct { + *Storage + log *utilLog.Helper +} + +func NewSqlWorkbenchRepo(log utilLog.Logger, s *Storage) *SqlWorkbenchRepo { + return &SqlWorkbenchRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.sql_workbench"))} +} + +func (sr *SqlWorkbenchRepo) GetSqlWorkbenchUserByDMSUserID(ctx context.Context, dmsUserID string) (*biz.SqlWorkbenchUser, bool, error) { + var user model.SqlWorkbenchUserCache + err := sr.db.WithContext(ctx).Where("dms_user_id = ?", dmsUserID).First(&user).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, false, nil + } + return nil, false, err + } + + return convertModelSqlWorkbenchUser(&user), true, nil +} + +func (sr *SqlWorkbenchRepo) SaveSqlWorkbenchUserCache(ctx context.Context, user *biz.SqlWorkbenchUser) error { + return transaction(sr.log, ctx, sr.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(convertBizSqlWorkbenchUser(user)).Error; err != nil { + return fmt.Errorf("failed to save sql workbench user cache: %v", err) + } + return nil + }) +} + +func convertModelSqlWorkbenchUser(user *model.SqlWorkbenchUserCache) *biz.SqlWorkbenchUser { + return &biz.SqlWorkbenchUser{ + DMSUserID: user.DMSUserID, + SqlWorkbenchUserId: user.SqlWorkbenchUserId, + SqlWorkbenchUsername: user.SqlWorkbenchUsername, + } +} + +func convertBizSqlWorkbenchUser(user *biz.SqlWorkbenchUser) *model.SqlWorkbenchUserCache { + return &model.SqlWorkbenchUserCache{ + DMSUserID: user.DMSUserID, + SqlWorkbenchUserId: user.SqlWorkbenchUserId, + SqlWorkbenchUsername: user.SqlWorkbenchUsername, + } +} + +// SqlWorkbenchDatasourceRepo 实现 +var _ biz.SqlWorkbenchDatasourceRepo = (*SqlWorkbenchDatasourceRepo)(nil) + +type SqlWorkbenchDatasourceRepo struct { + *Storage + log *utilLog.Helper +} + +func NewSqlWorkbenchDatasourceRepo(log utilLog.Logger, s *Storage) *SqlWorkbenchDatasourceRepo { + return &SqlWorkbenchDatasourceRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.sql_workbench_datasource"))} +} + +func (sr *SqlWorkbenchDatasourceRepo) GetSqlWorkbenchDatasourceByDMSDBServiceID(ctx context.Context, dmsDBServiceID, dmsUserID, purpose string) (*biz.SqlWorkbenchDatasource, bool, error) { + var datasource model.SqlWorkbenchDatasourceCache + err := transaction(sr.log, ctx, sr.db, func(tx *gorm.DB) error { + if err := tx.First(&datasource, "dms_db_service_id = ? AND dms_user_id = ? AND purpose = ?", dmsDBServiceID, dmsUserID, purpose).Error; err != nil { + return fmt.Errorf("failed to get sql workbench datasource: %v", err) + } + return nil + }) + + if err != nil { + if err == gorm.ErrRecordNotFound { + return nil, false, nil + } + return nil, false, err + } + + return convertModelSqlWorkbenchDatasource(&datasource), true, nil +} + +func (sr *SqlWorkbenchDatasourceRepo) SaveSqlWorkbenchDatasourceCache(ctx context.Context, datasource *biz.SqlWorkbenchDatasource) error { + return transaction(sr.log, ctx, sr.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(convertBizSqlWorkbenchDatasource(datasource)).Error; err != nil { + return fmt.Errorf("failed to save sql workbench datasource cache: %v", err) + } + return nil + }) +} + +func (sr *SqlWorkbenchDatasourceRepo) DeleteSqlWorkbenchDatasourceCache(ctx context.Context, dmsDBServiceID, dmsUserID, purpose string) error { + return transaction(sr.log, ctx, sr.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Where("dms_db_service_id = ? AND dms_user_id = ? AND purpose = ?", dmsDBServiceID, dmsUserID, purpose).Delete(&model.SqlWorkbenchDatasourceCache{}).Error; err != nil { + return fmt.Errorf("failed to delete sql workbench datasource cache: %v", err) + } + return nil + }) +} + +func (sr *SqlWorkbenchDatasourceRepo) GetSqlWorkbenchDatasourcesByUserID(ctx context.Context, dmsUserID string) ([]*biz.SqlWorkbenchDatasource, error) { + var datasources []model.SqlWorkbenchDatasourceCache + err := transaction(sr.log, ctx, sr.db, func(tx *gorm.DB) error { + if err := tx.Where("dms_user_id = ?", dmsUserID).Find(&datasources).Error; err != nil { + return fmt.Errorf("failed to get sql workbench datasources by user id: %v", err) + } + return nil + }) + + if err != nil { + return nil, err + } + + var result []*biz.SqlWorkbenchDatasource + for _, ds := range datasources { + result = append(result, convertModelSqlWorkbenchDatasource(&ds)) + } + return result, nil +} + +func convertModelSqlWorkbenchDatasource(datasource *model.SqlWorkbenchDatasourceCache) *biz.SqlWorkbenchDatasource { + return &biz.SqlWorkbenchDatasource{ + DMSDBServiceID: datasource.DMSDBServiceID, + DMSUserID: datasource.DMSUserID, + DMSDBServiceFingerprint: datasource.DMSDBServiceFingerprint, + SqlWorkbenchDatasourceID: datasource.SqlWorkbenchDatasourceID, + Purpose: datasource.Purpose, + } +} + +func convertBizSqlWorkbenchDatasource(datasource *biz.SqlWorkbenchDatasource) *model.SqlWorkbenchDatasourceCache { + return &model.SqlWorkbenchDatasourceCache{ + DMSDBServiceID: datasource.DMSDBServiceID, + DMSUserID: datasource.DMSUserID, + DMSDBServiceFingerprint: datasource.DMSDBServiceFingerprint, + SqlWorkbenchDatasourceID: datasource.SqlWorkbenchDatasourceID, + Purpose: datasource.Purpose, + } +} \ No newline at end of file diff --git a/internal/dms/storage/storage.go b/internal/dms/storage/storage.go index 526ad87a9..3a74e50fc 100644 --- a/internal/dms/storage/storage.go +++ b/internal/dms/storage/storage.go @@ -1,14 +1,15 @@ package storage import ( + "context" "fmt" + "strings" pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" "github.com/actiontech/dms/internal/dms/storage/model" - pkgLog "github.com/actiontech/dms/internal/pkg/log" - utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" "gorm.io/driver/mysql" "gorm.io/gorm" gormLog "gorm.io/gorm/logger" @@ -27,22 +28,33 @@ func (s *Storage) Close() error { } type StorageConfig struct { - User string - Password string - Host string - Port string - Schema string - Debug bool // 暂时无用 + User string + Password string + Host string + Port string + Schema string + AutoMigrate bool + Debug bool } -func NewStorage(logger utilLog.Logger, conf *StorageConfig) (*Storage, error) { - log := utilLog.NewHelper(logger, utilLog.WithMessageKey("dms.storage")) +func NewStorage(logger pkgLog.Logger, conf *StorageConfig) (*Storage, error) { + log := pkgLog.NewHelper(logger, pkgLog.WithMessageKey("dms.storage")) log.Infof("connecting to storage, host: %s, port: %s, user: %s, schema: %s", conf.Host, conf.Port, conf.User, conf.Schema) + // 根据 Debug 配置设置 GORM 日志级别 + // Debug = false: 使用 Warn 级别,输出警告和错误日志,但不输出 SQL 查询 + // Debug = true: 使用 Info 级别,输出详细 SQL 日志 + logLevel := gormLog.Warn + if conf.Debug { + logLevel = gormLog.Info + log.Info("gorm debug mode enabled") + } + db, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", conf.User, conf.Password, conf.Host, conf.Port, conf.Schema)), &gorm.Config{ - Logger: pkgLog.NewGormLogWrapper(pkgLog.NewKLogWrapper(logger), gormLog.Info), + Logger: pkgLog.NewGormLogWrapper(pkgLog.NewKLogWrapper(logger), logLevel), + DisableForeignKeyConstraintWhenMigrating: true, }) if err != nil { log.Errorf("connect to storage failed, error: %v", err) @@ -50,17 +62,20 @@ func NewStorage(logger utilLog.Logger, conf *StorageConfig) (*Storage, error) { } s := &Storage{db: db} - if err := s.AutoMigrate(logger); err != nil { - log.Errorf("auto migrate failed, error: %v", err) - return nil, pkgErr.WrapStorageErr(log, err) + if conf.AutoMigrate { + if err := s.AutoMigrate(logger); err != nil { + log.Errorf("auto migrate failed, error: %v", err) + return nil, pkgErr.WrapStorageErr(log, err) + } + log.Info("auto migrate dms tables") } log.Info("connected to storage") return s, pkgErr.WrapStorageErr(log, err) } -func (s *Storage) AutoMigrate(logger utilLog.Logger) error { - log := utilLog.NewHelper(logger, utilLog.WithMessageKey("dms.storage.AutoMigrate")) - err := s.db.AutoMigrate(model.GetAllModels()...) +func (s *Storage) AutoMigrate(logger pkgLog.Logger) error { + log := pkgLog.NewHelper(logger, pkgLog.WithMessageKey("dms.storage.AutoMigrate")) + err := s.db.AutoMigrate(model.AutoMigrateList...) if err != nil { return pkgErr.WrapStorageErr(log, err) } @@ -68,10 +83,139 @@ func (s *Storage) AutoMigrate(logger utilLog.Logger) error { } func gormWhere(db *gorm.DB, condition pkgConst.FilterCondition) *gorm.DB { - if condition.Operator == pkgConst.FilterOperatorIsNull { - return db.Where(fmt.Sprintf("%s IS NULL", condition.Field)) + // TODO 临时解决ISNULL场景不需要参数问题 + query, arg := gormWhereCondition(condition) + if arg == nil { + return db.Where(query) + } + return db.Where(query, arg) +} + +func gormWhereCondition(condition pkgConst.FilterCondition) (string, interface{}) { + switch condition.Operator { + case pkgConst.FilterOperatorIsNull: + return fmt.Sprintf("%s IS NULL", condition.Field), nil + case pkgConst.FilterOperatorContains, pkgConst.FilterOperatorNotContains: + condition.Value = fmt.Sprintf("%%%s%%", condition.Value) + case pkgConst.FilterOperatorIn: + values, ok := condition.Value.([]string) + if ok && len(values) > 0 { + var itemList []string + for _, value := range values { + item := fmt.Sprintf(`'%v'`, value) + itemList = append(itemList, item) + } + + return fmt.Sprintf("%s %s (%s)", condition.Field, condition.Operator, strings.Join(itemList, ",")), nil + } + } + return fmt.Sprintf("%s %s ?", condition.Field, condition.Operator), condition.Value +} + +func gormWheresWithOptions(ctx context.Context, db *gorm.DB, opts pkgConst.FilterOptions) *gorm.DB { + if len(opts.Groups) == 0 { + return db.WithContext(ctx) } - return db.Where(fmt.Sprintf("%s %s ?", condition.Field, condition.Operator), condition.Value) + + db = db.WithContext(ctx) + groupQueries := make([]*gorm.DB, 0, len(opts.Groups)) + + for _, group := range opts.Groups { + groupQuery := buildConditionGroup(db, group) + if groupQuery != nil { + groupQueries = append(groupQueries, groupQuery) + } + } + + if len(groupQueries) == 0 { + return db + } + + result := groupQueries[0] + for i := 1; i < len(groupQueries); i++ { + if opts.Logic == pkgConst.FilterLogicOr { + result = db.Where(result).Or(groupQueries[i]) + } else { + result = db.Where(result).Where(groupQueries[i]) + } + } + + return db.Where(result) +} + +func buildConditionGroup(db *gorm.DB, group pkgConst.FilterConditionGroup) *gorm.DB { + if len(group.Conditions) == 0 && len(group.Groups) == 0 { + return nil + } + + var result *gorm.DB + + for i, condition := range group.Conditions { + if condition.Table != "" { + continue + } + condQuery := gormWhere(db, condition) + if i == 0 || result == nil { + result = condQuery + } else if group.Logic == pkgConst.FilterLogicOr { + result = db.Where(result).Or(condQuery) + } else { + result = db.Where(result).Where(condQuery) + } + } + + for _, subGroup := range group.Groups { + subQuery := buildConditionGroup(db, subGroup) + if subQuery == nil { + continue + } + if result == nil { + result = subQuery + } else if group.Logic == pkgConst.FilterLogicOr { + result = db.Where(result).Or(subQuery) + } else { + result = db.Where(result).Where(subQuery) + } + } + + return result +} + +func gormPreload(ctx context.Context, db *gorm.DB, conditions []pkgConst.FilterCondition) *gorm.DB { + for _, f := range conditions { + // Preload 关联表 + if f.Table != "" { + args := make([]interface{}, 0) + // Preload 筛选参数 + if f.Field != "" { + whereCondition, value := gormWhereCondition(f) + args = []interface{}{whereCondition, value} + } + db = db.Preload(f.Table, args) + } + } + return db +} + +func extractPreloadConditions(opts pkgConst.FilterOptions) []pkgConst.FilterCondition { + var conditions []pkgConst.FilterCondition + for _, group := range opts.Groups { + for _, condition := range group.Conditions { + if condition.Table != "" { + conditions = append(conditions, condition) + } + } + for _, subGroup := range group.Groups { + subConditions := extractPreloadConditions(pkgConst.FilterOptions{Groups: []pkgConst.FilterConditionGroup{subGroup}}) + conditions = append(conditions, subConditions...) + } + } + return conditions +} + +func gormPreloadFromOptions(ctx context.Context, db *gorm.DB, opts pkgConst.FilterOptions) *gorm.DB { + conditions := extractPreloadConditions(opts) + return gormPreload(ctx, db, conditions) } func fixPageIndices(page_number uint32) int { diff --git a/internal/dms/storage/system_variable.go b/internal/dms/storage/system_variable.go new file mode 100644 index 000000000..f85bf9caa --- /dev/null +++ b/internal/dms/storage/system_variable.go @@ -0,0 +1,104 @@ +package storage + +import ( + "context" + "fmt" + "strconv" + + "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/storage/model" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.SystemVariableRepo = (*SystemVariableRepo)(nil) + +// SystemVariableRepo 系统变量存储实现 +type SystemVariableRepo struct { + *Storage + log *utilLog.Helper +} + +// NewSystemVariableRepo 创建系统变量存储实例 +func NewSystemVariableRepo(log utilLog.Logger, s *Storage) *SystemVariableRepo { + return &SystemVariableRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.system_variable"))} +} + +// GetSystemVariables 获取所有系统变量 +func (s *SystemVariableRepo) GetSystemVariables(ctx context.Context) (map[string]biz.SystemVariable, error) { + var variables []*model.SystemVariable + + if err := transaction(s.log, ctx, s.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Find(&variables).Error; err != nil { + return fmt.Errorf("failed to get system variables: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + return convertModelSystemVariables(variables), nil +} + +// UpdateSystemVariables 更新系统变量 +func (s *SystemVariableRepo) UpdateSystemVariables(ctx context.Context, variables []*biz.SystemVariable) error { + if err := transaction(s.log, ctx, s.db, func(tx *gorm.DB) error { + for _, variable := range variables { + modelVar := &model.SystemVariable{ + Key: variable.Key, + Value: variable.Value, + } + + // 使用 Upsert 操作,如果存在则更新,不存在则插入 + if err := tx.WithContext(ctx).Save(modelVar).Error; err != nil { + return fmt.Errorf("failed to update system variable %s: %v", variable.Key, err) + } + } + return nil + }); err != nil { + return err + } + + return nil +} + +// convertModelSystemVariables 转换存储模型到业务模型 +func convertModelSystemVariables(variables []*model.SystemVariable) map[string]biz.SystemVariable { + sysVariables := make(map[string]biz.SystemVariable, len(variables)) + for _, sv := range variables { + sysVariables[sv.Key] = biz.SystemVariable{ + Key: sv.Key, + Value: sv.Value, + } + } + + if _, ok := sysVariables[biz.SystemVariableOperationRecordExpiredHours]; !ok { + sysVariables[biz.SystemVariableOperationRecordExpiredHours] = biz.SystemVariable{ + Key: biz.SystemVariableOperationRecordExpiredHours, + Value: strconv.Itoa(biz.DefaultOperationRecordExpiredHours), + } + } + + if _, ok := sysVariables[biz.SystemVariableCbOperationLogsExpiredHours]; !ok { + sysVariables[biz.SystemVariableCbOperationLogsExpiredHours] = biz.SystemVariable{ + Key: biz.SystemVariableCbOperationLogsExpiredHours, + Value: strconv.Itoa(biz.DefaultCbOperationLogsExpiredHours), + } + } + + if _, ok := sysVariables[biz.SystemVariableWorkflowExpiredHours]; !ok { + sysVariables[biz.SystemVariableWorkflowExpiredHours] = biz.SystemVariable{ + Key: biz.SystemVariableWorkflowExpiredHours, + Value: strconv.Itoa(biz.DefaultSystemVariableWorkflowExpiredHours), + } + } + + if _, ok := sysVariables[biz.SystemVariableSqlManageRawExpiredHours]; !ok { + sysVariables[biz.SystemVariableSqlManageRawExpiredHours] = biz.SystemVariable{ + Key: biz.SystemVariableSqlManageRawExpiredHours, + Value: strconv.Itoa(biz.DefaultSystemVariableSqlManageRawExpiredHours), + } + } + + return sysVariables +} diff --git a/internal/dms/storage/test_util.go b/internal/dms/storage/test_util.go index a6d66f2f5..d61e1ee64 100644 --- a/internal/dms/storage/test_util.go +++ b/internal/dms/storage/test_util.go @@ -8,7 +8,7 @@ import ( "testing" "time" - pkgLog "github.com/actiontech/dms/internal/pkg/log" + pkgLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" kLog "github.com/go-kratos/kratos/v2/log" ) diff --git a/internal/dms/storage/user.go b/internal/dms/storage/user.go index 568987699..e91897814 100644 --- a/internal/dms/storage/user.go +++ b/internal/dms/storage/user.go @@ -2,15 +2,18 @@ package storage import ( "context" + "errors" "fmt" "github.com/actiontech/dms/internal/dms/biz" + "github.com/actiontech/dms/internal/dms/pkg/constant" pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" "github.com/actiontech/dms/internal/dms/storage/model" utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" "gorm.io/gorm" + "gorm.io/gorm/clause" ) var _ biz.UserRepo = (*UserRepo)(nil) @@ -157,10 +160,8 @@ func (d *UserRepo) ListUsers(ctx context.Context, opt *biz.ListUsersOption) (use // find models { db := tx.Unscoped().WithContext(ctx).Order(opt.OrderBy) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } - db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Preload("Members.Project").Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) if err := db.Find(&models).Error; err != nil { return fmt.Errorf("failed to list users: %v", err) } @@ -169,9 +170,7 @@ func (d *UserRepo) ListUsers(ctx context.Context, opt *biz.ListUsersOption) (use // find total { db := tx.Unscoped().WithContext(ctx).Model(&model.User{}) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) if err := db.Count(&total).Error; err != nil { return fmt.Errorf("failed to count users: %v", err) } @@ -192,11 +191,41 @@ func (d *UserRepo) ListUsers(ctx context.Context, opt *biz.ListUsersOption) (use return users, total, nil } +func (d *UserRepo) CountUsers(ctx context.Context, opts []constant.FilterCondition) (total int64, err error) { + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find total + db := tx.WithContext(ctx).Model(&model.User{}) + for _, f := range opts { + db = gormWhere(db, f) + } + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count users: %v", err) + } + + return nil + }); err != nil { + return 0, err + } + + return total, nil +} + func (d *UserRepo) DelUser(ctx context.Context, userUid string) error { return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { if err := tx.WithContext(ctx).Select("OpPermissions").Delete(&model.User{Model: model.Model{UID: userUid}}).Error; err != nil { return fmt.Errorf("failed to delete user: %v", err) } + + // delete members, member_role_op_ranges + if err := tx.WithContext(ctx).Exec(`delete m, mror from members m left join member_role_op_ranges mror on m.uid = mror.member_uid where m.user_uid = ?`, userUid).Error; err != nil { + return fmt.Errorf("failed to delete user associate members: %v", err) + } + + // delete member_group_users + if err := tx.WithContext(ctx).Exec(`delete mgu from member_group_users mgu where mgu.user_uid = ?`, userUid).Error; err != nil { + return fmt.Errorf("failed to delete user associate member_groups: %v", err) + } + return nil }) } @@ -219,6 +248,28 @@ func (d *UserRepo) GetUser(ctx context.Context, userUid string) (*biz.User, erro return ret, nil } +// GetUserIncludeDeleted 查找用户,包括已删除用户 +func (d *UserRepo) GetUserIncludeDeleted(ctx context.Context, userUid string) (*biz.User, error) { + var user *model.User + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // 不加全局软删除约束 + if err := tx.Unscoped().First(&user, "uid = ?", userUid).Error; err != nil { + return fmt.Errorf("failed to get user(include deleted): %v", err) + } + return nil + }); err != nil { + return nil, err + } + if user.DeletedAt.Valid { + user.Name = user.Name + "[x]" + } + ret, err := convertModelUser(user) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model user(include deleted): %v", err)) + } + return ret, nil +} + func (d *UserRepo) GetUserByName(ctx context.Context, userName string) (*biz.User, error) { var user *model.User if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { @@ -300,3 +351,43 @@ func (d *UserRepo) GetUserByThirdPartyUserID(ctx context.Context, thirdPartyUser } return ret, nil } + +func (d *UserRepo) SaveAccessToken(ctx context.Context, tokenInfo *biz.AccessTokenInfo) error { + userAccessToekn := &model.UserAccessToken{ + Model: model.Model{ + UID: tokenInfo.UID, + }, + UserID: tokenInfo.UserID, + Token: tokenInfo.Token, + ExpiredTime: tokenInfo.ExpiredTime, + } + + tx := d.db.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "user_id"}}, + DoUpdates: clause.Assignments(map[string]interface{}{"token": tokenInfo.Token, "expired_time": tokenInfo.ExpiredTime}), + }).Create(userAccessToekn) + + if tx.Error != nil { + return fmt.Errorf("failed to save access token: %v", tx.Error) + } + + return nil +} + +func (d *UserRepo) GetAccessTokenByUser(ctx context.Context, userUid string) (*biz.AccessTokenInfo, error) { + var userToken *model.UserAccessToken + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.First(&userToken, "user_id = ?", userUid).Error; err != nil { + // 未找到记录返回空,不影响获取用户信息的功能 + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil + } + return fmt.Errorf("failed to get user access token: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + return &biz.AccessTokenInfo{Token: userToken.Token, ExpiredTime: userToken.ExpiredTime}, nil +} diff --git a/internal/dms/storage/user_group.go b/internal/dms/storage/user_group.go index 7f495227b..919cfbed2 100644 --- a/internal/dms/storage/user_group.go +++ b/internal/dms/storage/user_group.go @@ -120,9 +120,7 @@ func (d *UserGroupRepo) ListUserGroups(ctx context.Context, opt *biz.ListUserGro // find models { db := tx.WithContext(ctx).Order(opt.OrderBy) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) if err := db.Find(&models).Error; err != nil { return fmt.Errorf("failed to list user groups: %v", err) @@ -132,9 +130,7 @@ func (d *UserGroupRepo) ListUserGroups(ctx context.Context, opt *biz.ListUserGro // find total { db := tx.WithContext(ctx).Model(&model.UserGroup{}) - for _, f := range opt.FilterBy { - db = gormWhere(db, f) - } + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) if err := db.Count(&total).Error; err != nil { return fmt.Errorf("failed to count user groups: %v", err) } diff --git a/internal/dms/storage/workflow.go b/internal/dms/storage/workflow.go new file mode 100644 index 000000000..8c88f8cd5 --- /dev/null +++ b/internal/dms/storage/workflow.go @@ -0,0 +1,678 @@ +package storage + +import ( + "bytes" + "context" + "fmt" + "reflect" + "regexp" + "strings" + "text/template" + "time" + + "github.com/actiontech/dms/internal/dms/biz" + pkgErr "github.com/actiontech/dms/internal/dms/pkg/errors" + "github.com/actiontech/dms/internal/dms/storage/model" + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + "gorm.io/gorm" +) + +var _ biz.WorkflowRepo = (*WorkflowRepo)(nil) + +type WorkflowRepo struct { + *Storage + log *utilLog.Helper +} + +func NewWorkflowRepo(log utilLog.Logger, s *Storage) *WorkflowRepo { + return &WorkflowRepo{Storage: s, log: utilLog.NewHelper(log, utilLog.WithMessageKey("storage.workflow"))} +} + +func (d *WorkflowRepo) SaveWorkflow(ctx context.Context, dataExportWorkflow *biz.Workflow) error { + model := convertBizWorkflow(dataExportWorkflow) + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Save(model).Error; err != nil { + return fmt.Errorf("failed to save workflow: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *WorkflowRepo) IsDataExportWorkflowNameDuplicate(ctx context.Context, projectUID, workflowName string) (bool, error) { + var count int64 + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.Workflow{}). + Where("project_uid = ? AND name = ?", projectUID, workflowName). + Count(&count).Error; err != nil { + return fmt.Errorf("failed to check workflow name duplicate: %v", err) + } + return nil + }); err != nil { + return false, err + } + return count > 0, nil +} + +func (w *WorkflowRepo) UpdateWorkflowRecord(ctx context.Context, dataExportWorkflowRecord *biz.WorkflowRecord) error { + model := convertBizWorkflowRecord(dataExportWorkflowRecord) + + if err := transaction(w.log, ctx, w.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Omit("created_at").Save(model).Error; err != nil { + return fmt.Errorf("failed to update workflow: %v", err) + } + return nil + }); err != nil { + return err + } + + return nil +} + +func (d *WorkflowRepo) ListDataExportWorkflows(ctx context.Context, opt *biz.ListWorkflowsOption) (Workflows []*biz.Workflow, total int64, err error) { + var models []*model.Workflow + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + + // find models + { + db := tx.WithContext(ctx).Order(fmt.Sprintf("%s DESC", opt.OrderBy)) + db = gormPreloadFromOptions(ctx, db, opt.FilterByOptions) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + db = db.Limit(int(opt.LimitPerPage)).Offset(int(opt.LimitPerPage * (uint32(fixPageIndices(opt.PageNumber))))) + if err := db.Find(&models).Error; err != nil { + return fmt.Errorf("failed to list Workflows: %v", err) + } + } + + // find total + { + db := tx.WithContext(ctx).Model(&model.Workflow{}) + db = gormPreloadFromOptions(ctx, db, opt.FilterByOptions) + db = gormWheresWithOptions(ctx, db, opt.FilterByOptions) + if err := db.Count(&total).Error; err != nil { + return fmt.Errorf("failed to count Workflows: %v", err) + } + } + return nil + }); err != nil { + return nil, 0, err + } + + // convert model to biz + for _, model := range models { + ds, err := convertModelWorkflow(model) + if err != nil { + return nil, 0, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model Workflows: %v", err)) + } + Workflows = append(Workflows, ds) + } + return Workflows, total, nil +} + +func (d *WorkflowRepo) GetDataExportWorkflowsForView(ctx context.Context, userUid string) ([]string, error) { + workflowUids := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT DISTINCT w.uid + FROM workflows w + left join workflow_records wr on w.workflow_record_uid = wr.uid + LEFT JOIN workflow_steps ws on wr.uid = ws.workflow_record_uid + left join data_export_tasks det on JSON_SEARCH(wr.task_ids ,'one',det.uid) IS NOT NULL + WHERE JSON_SEARCH(ws.assignees,"one",?) IS NOT NULL + UNION + SELECT DISTINCT w.uid + FROM workflows w + WHERE w.create_user_uid = ? + `, userUid, userUid).Find(&workflowUids).Error; err != nil { + return fmt.Errorf("failed to find workflow for view: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return workflowUids, nil +} + +func (d *WorkflowRepo) GetProjectDataExportWorkflowsForView(ctx context.Context, projectUid string) ([]string, error) { + workflowUids := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT DISTINCT w.uid + FROM workflows w + WHERE w.project_uid = ? + `, projectUid).Find(&workflowUids).Error; err != nil { + return fmt.Errorf("failed to find workflow for view: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return workflowUids, nil +} + +func (d *WorkflowRepo) GetDataExportWorkflowsByStatus(ctx context.Context, status string) ([]string, error) { + workflowUids := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT w.uid + FROM workflows w + left join workflow_records wr on w.workflow_record_uid = wr.uid + WHERE wr.status = ? + `, status).Find(&workflowUids).Error; err != nil { + return fmt.Errorf("failed to get worfklow by status: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return workflowUids, nil +} + +func (d *WorkflowRepo) GetDataExportWorkflowsByAssignUser(ctx context.Context, userUid string) ([]string, error) { + workflowUids := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT DISTINCT w.uid + FROM workflows w + left join workflow_records wr on w.workflow_record_uid = wr.uid + LEFT JOIN workflow_steps ws on wr.uid = ws.workflow_record_uid and wr.current_workflow_step_id = ws.step_id + left join data_export_tasks det on JSON_SEARCH(wr.task_ids ,'one',det.uid) IS NOT NULL + WHERE JSON_SEARCH(ws.assignees,"one",?) IS NOT NULL AND ws.state = "init" + `, userUid).Find(&workflowUids).Error; err != nil { + return fmt.Errorf("failed to find workflow by assignee user: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return workflowUids, nil +} + +func (d *WorkflowRepo) GetDataExportWorkflowsByDBService(ctx context.Context, dbUid string) ([]string, error) { + workflowUids := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT w.uid + FROM workflows w + left join workflow_records wr on w.workflow_record_uid = wr.uid + left join data_export_tasks det on JSON_SEARCH(wr.task_ids ,'one',det.uid) IS NOT NULL + WHERE det.db_service_uid = ? + `, dbUid).Find(&workflowUids).Error; err != nil { + return fmt.Errorf("failed to find workflow by db uid: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return workflowUids, nil +} + +func (d *WorkflowRepo) GetProjectDataExportWorkflowsByDBServices(ctx context.Context, dbUid []string, projectUid string) ([]string, error) { + workflowUids := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT w.uid + FROM workflows w + left join workflow_records wr on w.workflow_record_uid = wr.uid + left join data_export_tasks det on JSON_SEARCH(wr.task_ids ,'one',det.uid) IS NOT NULL + WHERE det.db_service_uid IN (?) and w.project_uid = ? + `, dbUid, projectUid).Find(&workflowUids).Error; err != nil { + return fmt.Errorf("failed to find workflow by db uid: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return workflowUids, nil +} + +func (d *WorkflowRepo) GetDataExportWorkflowsByDBServices(ctx context.Context, dbUid []string) ([]string, error) { + workflowUids := make([]string, 0) + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Raw(` + SELECT w.uid + FROM workflows w + left join workflow_records wr on w.workflow_record_uid = wr.uid + left join data_export_tasks det on JSON_SEARCH(wr.task_ids ,'one',det.uid) IS NOT NULL + WHERE det.db_service_uid IN (?) + `, dbUid).Find(&workflowUids).Error; err != nil { + return fmt.Errorf("failed to find workflow by db uid: %v", err) + } + return nil + }); err != nil { + return nil, err + } + return workflowUids, nil +} + +func (d *WorkflowRepo) GetDataExportWorkflow(ctx context.Context, workflowUid string) (*biz.Workflow, error) { + var workflow *model.Workflow + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.Preload("WorkflowRecord").Preload("WorkflowRecord.Steps").First(&workflow, "uid = ?", workflowUid).Error; err != nil { + return fmt.Errorf("failed to get workflow: %v", err) + } + return nil + }); err != nil { + return nil, err + } + + ret, err := convertModelWorkflow(workflow) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model workflow: %v", err)) + } + return ret, nil +} + +func (d *WorkflowRepo) AuditWorkflow(ctx context.Context, dataExportWorkflowUid string, status biz.DataExportWorkflowStatus, step *biz.WorkflowStep, operateId, reason string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.WorkflowRecord{}).Where("uid = ?", dataExportWorkflowUid).Update("status", status).Error; err != nil { + return fmt.Errorf("failed to update workflow status, err: %v", err) + } + + operateTime := time.Now() + fields := map[string]interface{}{"operation_user_uid": operateId, "operate_at": operateTime, "reason": reason, "state": step.State} + if err := tx.WithContext(ctx).Model(&model.WorkflowStep{}).Where("step_id = ? and workflow_record_uid = ?", step.StepId, step.WorkflowRecordUid).Updates(fields).Error; err != nil { + return fmt.Errorf("failed to update workflow status, err: %v", err) + } + + return nil + }) +} + +// AdvanceWorkflowStep 推进工单审批到下一步骤:标记当前步骤为 approved 并更新 CurrentWorkflowStepId,工单状态保持 wait_for_approve +func (d *WorkflowRepo) AdvanceWorkflowStep(ctx context.Context, dataExportWorkflowUid string, currentStep *biz.WorkflowStep, nextStepId uint64, operateId string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // 更新当前步骤状态为 approved + operateTime := time.Now() + stepFields := map[string]interface{}{"operation_user_uid": operateId, "operate_at": operateTime, "state": currentStep.State} + if err := tx.WithContext(ctx).Model(&model.WorkflowStep{}).Where("step_id = ? and workflow_record_uid = ?", currentStep.StepId, currentStep.WorkflowRecordUid).Updates(stepFields).Error; err != nil { + return fmt.Errorf("failed to update current workflow step, err: %v", err) + } + + // 推进 CurrentWorkflowStepId 到下一步 + if err := tx.WithContext(ctx).Model(&model.WorkflowRecord{}).Where("uid = ?", dataExportWorkflowUid).Update("current_workflow_step_id", nextStepId).Error; err != nil { + return fmt.Errorf("failed to advance workflow step, err: %v", err) + } + + return nil + }) +} + +func (d *WorkflowRepo) UpdateWorkflowStatusById(ctx context.Context, dataExportWorkflowUid string, status biz.DataExportWorkflowStatus) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.WorkflowRecord{}).Where("uid = ?", dataExportWorkflowUid).Update("status", status).Error; err != nil { + return fmt.Errorf("failed to update workflow status, err: %v", err) + } + + return nil + }) +} + +func (d *WorkflowRepo) CancelWorkflow(ctx context.Context, workflowRecordIds []string, workflowSteps []*biz.WorkflowStep, operateId string) error { + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Model(&model.WorkflowRecord{}).Where("uid in (?)", workflowRecordIds).Update("status", biz.DataExportWorkflowStatusCancel).Error; err != nil { + return fmt.Errorf("failed to update workflow status, err: %v", err) + } + + operateTime := time.Now() + for _, step := range workflowSteps { + fields := map[string]interface{}{"operation_user_uid": operateId, "operate_at": operateTime} + if err := tx.WithContext(ctx).Model(&model.WorkflowStep{}).Where("step_id = ? and workflow_record_uid = ?", step.StepId, step.WorkflowRecordUid).Updates(fields).Error; err != nil { + return fmt.Errorf("failed to update workflow status, err: %v", err) + } + } + + return nil + }) +} + +func (d *WorkflowRepo) GetDataExportWorkflowsByIds(ctx context.Context, ids []string) ([]*biz.Workflow, error) { + var workflows []*model.Workflow + + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + if err := tx.WithContext(ctx).Preload("WorkflowRecord").Preload("WorkflowRecord.Steps").Find(&workflows, ids).Error; err != nil { + return fmt.Errorf("failed to get Workflows: %v", err) + } + + return nil + }); err != nil { + return nil, err + } + + ret := make([]*biz.Workflow, 0, len(workflows)) + for _, workflow := range workflows { + ds, err := convertModelWorkflow(workflow) + if err != nil { + return nil, pkgErr.WrapStorageErr(d.log, fmt.Errorf("failed to convert model Workflows: %v", err)) + } + + ret = append(ret, ds) + } + + return ret, nil +} + +func (d *WorkflowRepo) DeleteDataExportWorkflowsByIds(ctx context.Context, dataExportWorkflowUids []string) error { + if len(dataExportWorkflowUids) == 0 { + return nil + } + return transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + err := tx.Exec(`DELETE + FROM + workflow_steps + WHERE + workflow_record_uid IN ( + SELECT + uid + FROM + workflow_records + WHERE + workflow_uid IN ? + )`, dataExportWorkflowUids).Error + if err != nil { + return err + } + + err = tx.Exec("DELETE FROM workflow_records WHERE workflow_uid in ?", dataExportWorkflowUids).Error + if err != nil { + return err + } + + err = tx.WithContext(ctx).Exec("DELETE FROM workflows WHERE uid in ?", dataExportWorkflowUids).Error + if err != nil { + return err + } + return nil + }) +} + +var workflowsQueryTpl = ` +SELECT + w.project_uid, + p.priority AS project_priority, + p.name AS project_name, + w.name AS subject, + w.uid AS workflow_uid, + w.desc, + w.create_user_uid, + CAST("" AS DATETIME) AS create_user_deleted_at, + w.created_at AS create_time, + curr_ws.assignees AS current_step_assignee_user_id_list, + curr_ws.state AS current_step_state, + wr.status, + wr.current_workflow_step_id AS current_workflow_step_id, + wr.uid AS workflow_record_uid, + t.db_service_uid AS db_service_uid, + ds.name AS db_service_name +{{- template "body" . -}} + +ORDER BY wr.updated_at DESC +{{- if .limit }} +LIMIT :limit OFFSET :offset +{{- end -}} +` + +var workflowsQueryBodyTpl = ` +{{ define "body" }} +FROM workflows w +INNER JOIN projects p ON w.project_uid = p.uid +INNER JOIN workflow_records AS wr ON w.workflow_record_uid = wr.uid +INNER JOIN data_export_tasks t ON JSON_CONTAINS(wr.task_ids, JSON_QUOTE(t.uid), '$') +LEFT JOIN workflow_steps AS curr_ws ON wr.uid = curr_ws.workflow_record_uid AND wr.current_workflow_step_id = curr_ws.step_id +LEFT JOIN db_services ds ON t.db_service_uid = ds.uid + +WHERE +w.workflow_type='data_export' +{{- if .check_user_can_access }} +AND ( +w.create_user_uid = :current_user_id +OR curr_ws.assignees REGEXP :current_user_id + + +{{- if .viewable_db_service_uids }} +OR t.db_service_uid IN (:viewable_db_service_uids) +{{- end }} + +) +{{- end }} + +{{- if .filter_subject }} +AND w.name = :filter_subject +{{- end }} + +{{- if .filter_by_create_user_uid }} +AND w.create_user_uid = :filter_by_create_user_uid +{{- end }} + +{{- if .filter_create_user_id }} +AND w.create_user_id = :filter_create_user_id +{{- end }} + +{{- if .filter_status }} +AND wr.status IN (:filter_status) +{{- end }} + +{{- if .filter_current_step_assignee_user_id }} +AND curr_ws.assignees REGEXP :filter_current_step_assignee_user_id +{{- end }} + +{{- if .filter_db_service_uid }} +AND t.db_service_uid = :filter_db_service_uid +{{- end }} + +{{- if .filter_workflow_id }} +AND w.uid = :filter_workflow_id +{{- end }} + +{{- if .filter_project_uid }} +AND w.project_uid = :filter_project_uid +{{- end }} + +{{- if .filter_status_list }} +AND wr.status IN (:filter_status_list) +{{- end }} + +{{- if .filter_project_uids }} +AND w.project_uid IN (:filter_project_uids) +{{- end }} + +{{- if .fuzzy_keyword }} +AND (w.name like :fuzzy_keyword or w.uid like :fuzzy_keyword or w.desc like :fuzzy_keyword) +{{- end }} + + + +{{ end }} + +` + +func (d *WorkflowRepo) GetGlobalWorkflowsByParameterMap(ctx context.Context, data map[string]interface{}) (workflows []*biz.Workflow, total int64, err error) { + type workflowQueryResult struct { + ProjectUID string `gorm:"column:project_uid"` + ProjectName string `gorm:"column:project_name"` + ProjectPriority uint8 `gorm:"column:project_priority"` + Subject string `gorm:"column:subject"` + WorkflowUID string `gorm:"column:workflow_uid"` + Desc string `gorm:"column:desc"` + CreateUserUID string `gorm:"column:create_user_uid"` + CreateUserDeletedAt *time.Time `gorm:"column:create_user_deleted_at"` + CreateTime time.Time `gorm:"column:create_time"` + CurrentStepAssigneeUserIDList model.Strings `gorm:"column:current_step_assignee_user_id_list"` + CurrentStepState string `gorm:"column:current_step_state"` + Status string `gorm:"column:status"` + CurrentWorkflowStepId uint64 `gorm:"column:current_workflow_step_id"` + WorkflowRecordUID string `gorm:"column:workflow_record_uid"` + DBServiceUID string `gorm:"column:db_service_uid"` + DBServiceName string `gorm:"column:db_service_name"` + } + + var results []workflowQueryResult + if err := transaction(d.log, ctx, d.db, func(tx *gorm.DB) error { + // find results + { + sqlQuery, params, err := d.buildWorkflowQuerySQL(data) + if err != nil { + return fmt.Errorf("failed to build workflow query SQL: %v", err) + } + + if err := tx.WithContext(ctx).Raw(sqlQuery, params...).Scan(&results).Error; err != nil { + return fmt.Errorf("failed to query workflows: %v", err) + } + } + + // find total + { + sqlQuery, params, err := d.buildWorkflowCountSQL(data) + if err != nil { + return fmt.Errorf("failed to build workflow count SQL: %v", err) + } + + if err := tx.WithContext(ctx).Raw(sqlQuery, params...).Count(&total).Error; err != nil { + return fmt.Errorf("failed to count workflows: %v", err) + } + } + + return nil + }); err != nil { + return nil, 0, err + } + + // convert results to biz.Workflow + workflows = make([]*biz.Workflow, 0, len(results)) + for _, result := range results { + workflow := &biz.Workflow{ + Base: biz.Base{ + CreatedAt: result.CreateTime, + }, + UID: result.WorkflowUID, + Name: result.Subject, + ProjectUID: result.ProjectUID, + Desc: result.Desc, + CreateTime: result.CreateTime, + CreateUserUID: result.CreateUserUID, + Status: result.Status, + ProjectInfo: &dmsCommonV1.ProjectInfo{ + ProjectUid: result.ProjectUID, + ProjectName: result.ProjectName, + ProjectPriority: dmsCommonV1.ToPriority(result.ProjectPriority), + }, + } + + if result.DBServiceUID != "" { + workflow.DBServiceInfos = []*dmsCommonV1.DBServiceUidWithNameInfo{ + { + DBServiceUid: result.DBServiceUID, + DBServiceName: result.DBServiceName, + }, + } + } + + // Build WorkflowRecord with WorkflowSteps array + workflow.WorkflowRecord = &biz.WorkflowRecord{ + UID: result.WorkflowRecordUID, + Status: biz.DataExportWorkflowStatus(result.Status), + CurrentWorkflowStepId: result.CurrentWorkflowStepId, + WorkflowSteps: make([]*biz.WorkflowStep, result.CurrentWorkflowStepId), + } + + // Fill the WorkflowSteps array with placeholder steps + for i := uint64(0); i < result.CurrentWorkflowStepId; i++ { + workflow.WorkflowRecord.WorkflowSteps[i] = &biz.WorkflowStep{ + StepId: i + 1, + WorkflowRecordUid: result.WorkflowRecordUID, + State: "", + Assignees: []string{}, + } + } + + // Set the current step data + if result.CurrentWorkflowStepId > 0 { + currentStepIndex := result.CurrentWorkflowStepId - 1 + workflow.WorkflowRecord.WorkflowSteps[currentStepIndex] = &biz.WorkflowStep{ + StepId: result.CurrentWorkflowStepId, + WorkflowRecordUid: result.WorkflowRecordUID, + State: result.CurrentStepState, + Assignees: result.CurrentStepAssigneeUserIDList, + } + workflow.WorkflowRecord.CurrentStep = workflow.WorkflowRecord.WorkflowSteps[currentStepIndex] + } + + workflows = append(workflows, workflow) + } + + return workflows, total, nil +} + +func (d *WorkflowRepo) buildWorkflowQuerySQL(data map[string]interface{}) (string, []interface{}, error) { + return renderSQL(workflowsQueryTpl, workflowsQueryBodyTpl, data) +} + +func (d *WorkflowRepo) buildWorkflowCountSQL(data map[string]interface{}) (string, []interface{}, error) { + const countQueryTpl = `SELECT COUNT(*) as total {{- template "body" . -}}` + + templateData := make(map[string]interface{}) + for k, v := range data { + templateData[k] = v + } + + delete(templateData, "limit") + delete(templateData, "offset") + + return renderSQL(countQueryTpl, workflowsQueryBodyTpl, templateData) +} + +func renderSQL(mainTpl, bodyTpl string, params map[string]interface{}) (string, []interface{}, error) { + // Parse templates together so that the main template can reference the body definition + tmpl, err := template.New("workflows").Parse(bodyTpl) + if err != nil { + return "", nil, fmt.Errorf("failed to parse body template: %v", err) + } + + if _, err = tmpl.Parse(mainTpl); err != nil { + return "", nil, fmt.Errorf("failed to parse main template: %v", err) + } + + var buf bytes.Buffer + if err = tmpl.Execute(&buf, params); err != nil { + return "", nil, fmt.Errorf("failed to execute template: %v", err) + } + + query := buf.String() + + // Replace named params like :param with positional placeholders and collect args + var args []interface{} + re := regexp.MustCompile(`:([a-zA-Z_]+)`) + query = re.ReplaceAllStringFunc(query, func(m string) string { + key := m[1:] // Remove the leading ':' + if v, ok := params[key]; ok { + // Handle IN clause for slices + if v != nil && reflect.TypeOf(v).Kind() == reflect.Slice { + s := reflect.ValueOf(v) + if s.Len() == 0 { + // Empty slice, return NULL to avoid SQL error + return "NULL" + } + placeholders := make([]string, s.Len()) + for i := 0; i < s.Len(); i++ { + args = append(args, s.Index(i).Interface()) + placeholders[i] = "?" + } + // Return comma-separated placeholders + // SQL template has: IN (:param), this becomes: IN (?, ?, ?) + return strings.Join(placeholders, ", ") + } + args = append(args, v) + return "?" + } + // If key not present, keep original (should not happen due to template conditionals) + return m + }) + + return query, args, nil +} diff --git a/internal/pkg/cloudbeaver/client.go b/internal/pkg/cloudbeaver/client.go index 9cbe988dd..64ac5f33d 100644 --- a/internal/pkg/cloudbeaver/client.go +++ b/internal/pkg/cloudbeaver/client.go @@ -9,6 +9,9 @@ import ( "io" "mime/multipart" "net/http" + "time" + + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" ) // Client is a client for interacting with a GraphQL API. @@ -28,6 +31,9 @@ type Client struct { Log func(s string) HttpResHandler func(res *http.Response) + + // maxRetries 最大重试次数,默认为0表示不重试 + maxRetries int } // NewClient makes a new Client capable of making GraphQL requests. @@ -70,147 +76,227 @@ func (c *Client) Run(ctx context.Context, req *Request, resp interface{}) error } func (c *Client) runWithJSON(ctx context.Context, req *Request, resp interface{}) error { - var requestBody bytes.Buffer - requestBodyObj := struct { - Query string `json:"query"` - Variables map[string]interface{} `json:"variables"` - OperationName string `json:"operationName"` - }{ - Query: req.q, - Variables: req.vars, - } - if req.operationName != "" { - requestBodyObj.OperationName = req.operationName - } - if err := json.NewEncoder(&requestBody).Encode(requestBodyObj); err != nil { - return fmt.Errorf("encode body %w", err) - } - c.logf(">> variables: %v", req.vars) - c.logf(">> query: %s", req.q) - gr := &graphResponse{ - Data: resp, - } - r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) - if err != nil { - return err - } - r.Close = c.closeReq - r.Header.Set("Content-Type", "application/json; charset=utf-8") - r.Header.Set("Accept", "application/json; charset=utf-8") - for _, cookie := range c.cookies { - r.AddCookie(cookie) - } - for key, values := range req.Header { - for _, value := range values { - r.Header.Add(key, value) + var lastErr error + maxAttempts := c.maxRetries + 1 // 总尝试次数 = 重试次数 + 1 + + for attempt := 0; attempt < maxAttempts; attempt++ { + if attempt > 0 { + // 重试前等待,使用指数退避策略 + waitTime := time.Duration(attempt) * 100 * time.Millisecond + c.logf(">> retry attempt %d/%d after %v", attempt, c.maxRetries, waitTime) + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(waitTime): + } } - } - c.logf(">> headers: %v", r.Header) - r = r.WithContext(ctx) - res, err := c.httpClient.Do(r) - if err != nil { - return err - } - if c.HttpResHandler != nil { - c.HttpResHandler(res) - } - defer res.Body.Close() - var buf bytes.Buffer - if _, err := io.Copy(&buf, res.Body); err != nil { - return fmt.Errorf("reading body %w", err) - } - c.logf("<< %s", buf.String()) - if err := json.NewDecoder(&buf).Decode(&gr); err != nil { - if res.StatusCode != http.StatusOK { - return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) + var requestBody bytes.Buffer + requestBodyObj := struct { + Query string `json:"query"` + Variables map[string]interface{} `json:"variables"` + OperationName string `json:"operationName"` + }{ + Query: req.q, + Variables: req.vars, + } + if req.operationName != "" { + requestBodyObj.OperationName = req.operationName + } + if err := json.NewEncoder(&requestBody).Encode(requestBodyObj); err != nil { + return fmt.Errorf("encode body %w", err) + } + c.logf(">> variables: %v", req.vars) + c.logf(">> query: %s", req.q) + gr := &graphResponse{ + Data: resp, + } + r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) + if err != nil { + return err + } + r.Close = c.closeReq + r.Header.Set("Content-Type", "application/json; charset=utf-8") + r.Header.Set("Accept", "application/json; charset=utf-8") + for _, cookie := range c.cookies { + r.AddCookie(cookie) + } + for key, values := range req.Header { + for _, value := range values { + r.Header.Add(key, value) + } + } + c.logf(">> headers: %v", r.Header) + r = r.WithContext(ctx) + res, err := c.httpClient.Do(r) + if err != nil { + lastErr = err + if attempt < c.maxRetries { + c.logf(">> request failed: %v, will retry", err) + continue + } + return err + } + if c.HttpResHandler != nil { + c.HttpResHandler(res) + } + + func() { + defer res.Body.Close() + var buf bytes.Buffer + if err := func() error { + if _, err := io.Copy(&buf, res.Body); err != nil { + return fmt.Errorf("reading body %w", err) + } + c.logf("<< %s", buf.String()) + if err := json.NewDecoder(&buf).Decode(&gr); err != nil { + if res.StatusCode != http.StatusOK { + return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) + } + return fmt.Errorf("decoding response %w", err) + } + if len(gr.Errors) > 0 { + // return first error + return gr.Errors[0] + } + return nil + }(); err != nil { + lastErr = err + } else { + lastErr = nil + } + }() + + if lastErr == nil { + return nil + } + + if attempt < c.maxRetries { + c.logf(">> request failed: %v, will retry", lastErr) } - return fmt.Errorf("decoding response %w", err) - } - if len(gr.Errors) > 0 { - // return first error - return gr.Errors[0] } - return nil + + return lastErr } func (c *Client) runWithPostFields(ctx context.Context, req *Request, resp interface{}) error { - var requestBody bytes.Buffer - writer := multipart.NewWriter(&requestBody) - if err := writer.WriteField("query", req.q); err != nil { - return fmt.Errorf("write query field %w", err) - } - var variablesBuf bytes.Buffer - if len(req.vars) > 0 { - variablesField, err := writer.CreateFormField("variables") - if err != nil { - return fmt.Errorf("create variables field %w", err) + var lastErr error + maxAttempts := c.maxRetries + 1 // 总尝试次数 = 重试次数 + 1 + + for attempt := 0; attempt < maxAttempts; attempt++ { + if attempt > 0 { + // 重试前等待,使用指数退避策略 + waitTime := time.Duration(attempt) * 100 * time.Millisecond + c.logf(">> retry attempt %d/%d after %v", attempt, c.maxRetries, waitTime) + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(waitTime): + } } - if err := json.NewEncoder(io.MultiWriter(variablesField, &variablesBuf)).Encode(req.vars); err != nil { - return fmt.Errorf("encode variables %w", err) + + var requestBody bytes.Buffer + writer := multipart.NewWriter(&requestBody) + if err := writer.WriteField("query", req.q); err != nil { + return fmt.Errorf("write query field %w", err) } - } - for i := range req.files { - part, err := writer.CreateFormFile(req.files[i].Field, req.files[i].Name) + var variablesBuf bytes.Buffer + if len(req.vars) > 0 { + variablesField, err := writer.CreateFormField("variables") + if err != nil { + return fmt.Errorf("create variables field %w", err) + } + if err := json.NewEncoder(io.MultiWriter(variablesField, &variablesBuf)).Encode(req.vars); err != nil { + return fmt.Errorf("encode variables %w", err) + } + } + for i := range req.files { + part, err := writer.CreateFormFile(req.files[i].Field, req.files[i].Name) + if err != nil { + return fmt.Errorf("create form file %w", err) + } + if _, err := io.Copy(part, req.files[i].R); err != nil { + return fmt.Errorf("preparing file %w", err) + } + } + if err := writer.Close(); err != nil { + return fmt.Errorf("close writer %w", err) + } + c.logf(">> variables: %s", variablesBuf.String()) + c.logf(">> files: %d", len(req.files)) + c.logf(">> query: %s", req.q) + gr := &graphResponse{ + Data: resp, + } + r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) if err != nil { - return fmt.Errorf("create form file %w", err) + return err } - if _, err := io.Copy(part, req.files[i].R); err != nil { - return fmt.Errorf("preparing file %w", err) + r.Close = c.closeReq + r.Header.Set("Content-Type", writer.FormDataContentType()) + r.Header.Set("Accept", "application/json; charset=utf-8") + for _, cookie := range c.cookies { + r.AddCookie(cookie) } - } - if err := writer.Close(); err != nil { - return fmt.Errorf("close writer %w", err) - } - c.logf(">> variables: %s", variablesBuf.String()) - c.logf(">> files: %d", len(req.files)) - c.logf(">> query: %s", req.q) - gr := &graphResponse{ - Data: resp, - } - r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody) - if err != nil { - return err - } - r.Close = c.closeReq - r.Header.Set("Content-Type", writer.FormDataContentType()) - r.Header.Set("Accept", "application/json; charset=utf-8") - for _, cookie := range c.cookies { - r.AddCookie(cookie) - } - for key, values := range req.Header { - for _, value := range values { - r.Header.Add(key, value) + for key, values := range req.Header { + for _, value := range values { + r.Header.Add(key, value) + } } - } - c.logf(">> headers: %v", r.Header) - r = r.WithContext(ctx) - res, err := c.httpClient.Do(r) - if err != nil { - return err - } - defer res.Body.Close() - var buf bytes.Buffer - if _, err := io.Copy(&buf, res.Body); err != nil { - return fmt.Errorf("reading body %w", err) - } - c.logf("<< %s", buf.String()) - if err := json.NewDecoder(&buf).Decode(&gr); err != nil { - if res.StatusCode != http.StatusOK { - return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) + c.logf(">> headers: %v", r.Header) + r = r.WithContext(ctx) + res, err := c.httpClient.Do(r) + if err != nil { + lastErr = err + if attempt < c.maxRetries { + c.logf(">> request failed: %v, will retry", err) + continue + } + return err + } + + func() { + defer res.Body.Close() + var buf bytes.Buffer + if err := func() error { + if _, err := io.Copy(&buf, res.Body); err != nil { + return fmt.Errorf("reading body %w", err) + } + c.logf("<< %s", buf.String()) + if err := json.NewDecoder(&buf).Decode(&gr); err != nil { + if res.StatusCode != http.StatusOK { + return fmt.Errorf("graphql: server returned a non-200 status code: %v", res.StatusCode) + } + return fmt.Errorf("decoding response %w", err) + } + if len(gr.Errors) > 0 { + // return first error + return gr.Errors[0] + } + return nil + }(); err != nil { + lastErr = err + } else { + lastErr = nil + } + }() + + if lastErr == nil { + return nil + } + + if attempt < c.maxRetries { + c.logf(">> request failed: %v, will retry", lastErr) } - return fmt.Errorf("decoding response %w", err) - } - if len(gr.Errors) > 0 { - // return first error - return gr.Errors[0] } - return nil + + return lastErr } // WithHTTPClient specifies the underlying http.Client to use when // making requests. -// NewClient(endpoint, WithHTTPClient(specificHTTPClient)) +// +// NewClient(endpoint, WithHTTPClient(specificHTTPClient)) func WithHTTPClient(httpclient *http.Client) ClientOption { return func(client *Client) { client.httpClient = httpclient @@ -225,7 +311,7 @@ func UseMultipartForm() ClientOption { } } -//ImmediatelyCloseReqBody will close the req body immediately after each request body is ready +// ImmediatelyCloseReqBody will close the req body immediately after each request body is ready func ImmediatelyCloseReqBody() ClientOption { return func(client *Client) { client.closeReq = true @@ -244,6 +330,24 @@ func WithCookie(cookie []*http.Cookie) ClientOption { } } +func WithLogger(logger *utilLog.Helper) ClientOption { + return func(client *Client) { + client.Log = func(s string) { + logger.Debugf("%s", s) + } + } +} + +// WithMaxRetries 设置最大重试次数,默认为0表示不重试 +func WithMaxRetries(maxRetries int) ClientOption { + return func(client *Client) { + if maxRetries < 0 { + maxRetries = 0 + } + client.maxRetries = maxRetries + } +} + // ClientOption are functions that are passed into NewClient to // modify the behaviour of the Client. type ClientOption func(*Client) diff --git a/internal/pkg/cloudbeaver/cloudbeaver.go b/internal/pkg/cloudbeaver/cloudbeaver.go index 3c64b2440..81eeef3d9 100644 --- a/internal/pkg/cloudbeaver/cloudbeaver.go +++ b/internal/pkg/cloudbeaver/cloudbeaver.go @@ -19,6 +19,12 @@ var ( Version2223 = CBVersion{ version: []int{22, 2, 3}, } + Version2321 = CBVersion{ + version: []int{23, 2, 1}, + } + Version2521 = CBVersion{ + version: []int{25, 2, 1}, + } ) // CloudBeaver 版本号格式一般为 X.X.X.X 格式,例如 '22.3.1.202212261505' , 其中前三位为版本号 @@ -59,7 +65,6 @@ func (v CBVersion) LessThan(version CBVersion) bool { return false } return v.version[2] < version.version[2] - } // 不同版本的CloudBeaver间存在不兼容查询语句 @@ -67,14 +72,16 @@ func (v CBVersion) LessThan(version CBVersion) bool { type GraphQLImpl interface { CreateConnectionQuery() string UpdateConnectionQuery() string + DeleteConnectionQuery() string GetUserConnectionsQuery() string SetUserConnectionsQuery() string - IsUserExistQuery() string + IsUserExistQuery(userId string) (string, map[string]interface{}) UpdatePasswordQuery() string CreateUserQuery() string GrantUserRoleQuery() string LoginQuery() string GetActiveUserQuery() string + GetExecutionContextListQuery() string } // TODO 暂时无法确定这套查询语句是兼容到22.1.5版本还是22.1.4版本, 因为虽然找到了22.1.4版本的镜像, 但没找到22.1.4版本的代码 @@ -112,6 +119,17 @@ fragment DatabaseConnection on ConnectionInfo { ` } +func (CloudBeaverV2215) DeleteConnectionQuery() string { + return ` +mutation deleteConnection( + $projectId: ID! + $connectionId: ID! +) { + deleteConnection(projectId: $projectId, id: $connectionId) +} +` +} + func (CloudBeaverV2215) GetUserConnectionsQuery() string { return ` query getUserConnections ( @@ -124,6 +142,7 @@ query getUserConnections ( } fragment DatabaseConnection on ConnectionInfo { id + template } ` } @@ -139,7 +158,7 @@ query setConnections($userId: ID!, $connections: [ID!]!) { ` } -func (CloudBeaverV2215) IsUserExistQuery() string { +func (CloudBeaverV2215) IsUserExistQuery(userId string) (string, map[string]interface{}) { return ` query getUserList( $userId: ID @@ -150,8 +169,7 @@ query getUserList( } fragment adminUserInfo on AdminUserInfo { userId -} -` +}`, map[string]interface{}{"userId": userId} } func (CloudBeaverV2215) UpdatePasswordQuery() string { @@ -218,6 +236,28 @@ func (CloudBeaverV2215) GetActiveUserQuery() string { ` } +func (CloudBeaverV2215) GetExecutionContextListQuery() string { + return ` +query executionContextList($projectId: ID, $connectionId: ID, $contextId: ID) { + contexts: sqlListContexts( + projectId: $projectId + connectionId: $connectionId + contextId: $contextId + ) { + ...ExecutionContextInfo + } +} + +fragment ExecutionContextInfo on SQLContextInfo { + id + projectId + connectionId + defaultCatalog + defaultSchema +} +` +} + type CloudBeaverV2221 struct { CloudBeaverV2215 } @@ -270,6 +310,60 @@ query serverConfig { } }` +type CloudBeaverV2321 struct { + CloudBeaverV2223 +} + +type CloudBeaverV2521 struct { + CloudBeaverV2321 +} + +func (CloudBeaverV2521) GetUserConnectionsQuery() string { + return ` +query getUserConnections ( + $projectId: ID + $connectionId: ID + $projectIds: [ID!] +){ + connections: userConnections(projectId: $projectId, id: $connectionId, projectIds: $projectIds) { + ...DatabaseConnection + } +} +fragment DatabaseConnection on ConnectionInfo { + id +} +` +} + +func (CloudBeaverV2321) IsUserExistQuery(userId string) (string, map[string]interface{}) { + return ` +query getUserList( + $page: PageInput! + $filter: AdminUserFilterInput! +){ + listUsers(page: $page, filter: $filter) { + ...adminUserInfo + } +} +fragment adminUserInfo on AdminUserInfo { + userId +} +`, map[string]interface{}{ + "page": map[string]interface{}{"offset": 0, "limit": 100}, + "filter": map[string]interface{}{"userIdMask": userId, "enabledState": true}, + } +} + +func (CloudBeaverV2321) GetActiveUserQuery() string { + return ` + query getActiveUser { + user: activeUser { + userId + } + } +` +} + func NewGraphQL(url string) (GraphQLImpl, error) { client := NewGraphQlClient(url) req := NewRequest(GraphQLConfigVersionQuery, map[string]interface{}{}) @@ -289,9 +383,15 @@ func NewGraphQL(url string) (GraphQLImpl, error) { return nil, err } - var queryGraphQL GraphQLImpl = CloudBeaverV2223{} + var queryGraphQL GraphQLImpl = CloudBeaverV2521{} - // QueryGQL 默认值是 CloudBeaverV2223{} + // QueryGQL 默认值是 CloudBeaverV2521{} + if version.LessThan(Version2521) { + queryGraphQL = CloudBeaverV2321{} + } + if version.LessThan(Version2321) { + queryGraphQL = CloudBeaverV2223{} + } if version.LessThan(Version2223) { queryGraphQL = CloudBeaverV2221{} } diff --git a/internal/pkg/cloudbeaver/graphql.go b/internal/pkg/cloudbeaver/graphql.go index 2e14abd92..be7a67a78 100644 --- a/internal/pkg/cloudbeaver/graphql.go +++ b/internal/pkg/cloudbeaver/graphql.go @@ -4,12 +4,14 @@ import ( "context" "encoding/json" "fmt" - "net/http" + "log" "strconv" "strings" + dbmodel "github.com/actiontech/dms/internal/dms/storage/model" "github.com/actiontech/dms/internal/pkg/cloudbeaver/model" "github.com/actiontech/dms/internal/pkg/cloudbeaver/resolver" + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" @@ -23,13 +25,30 @@ type ResolverImpl struct { *resolver.Resolver Ctx echo.Context Next Next + + // SQLExecuteResultsHandlerFn 为对SQL结果集的处理方法,具体处理逻辑为业务行为,由外部biz层定义后传入 + SQLExecuteResultsHandlerFn SQLExecuteResultsHandler + EnableResultsHandlerFn bool +} + +func NewResolverImpl(ctx echo.Context, next Next, SQLExecuteResultsHandlerFn SQLExecuteResultsHandler, enableResultsHandlerFn bool) *ResolverImpl { + return &ResolverImpl{ + Ctx: ctx, + Next: next, + SQLExecuteResultsHandlerFn: SQLExecuteResultsHandlerFn, + EnableResultsHandlerFn: enableResultsHandlerFn, + } } func (r *ResolverImpl) Mutation() resolver.MutationResolver { - return &MutationResolverImpl{ + m := &MutationResolverImpl{ Ctx: r.Ctx, Next: r.Next, } + if r.EnableResultsHandlerFn { + m.SQLExecuteResultsHandlerFn = r.SQLExecuteResultsHandlerFn + } + return m } // Query returns generated.QueryResolver implementation. @@ -40,10 +59,15 @@ func (r *ResolverImpl) Query() resolver.QueryResolver { } } +type SQLExecuteResultsHandler func(ctx context.Context, result *model.SQLExecuteInfo) error + type MutationResolverImpl struct { *resolver.MutationResolverImpl Ctx echo.Context Next Next + + // SQLExecuteResultsHandlerFn 为对SQL结果集的处理方法,具体处理逻辑为业务行为,由外部biz层定义后传入 + SQLExecuteResultsHandlerFn SQLExecuteResultsHandler } type QueryResolverImpl struct { @@ -79,9 +103,9 @@ func (r *QueryResolverImpl) ActiveUser(ctx context.Context) (*model.UserInfo, er type ContextKey string const ( - UsernamePrefix = "dms-" - SQLEProxyAddrName ContextKey = "sqle_addr" - SQLEProxyName = "sqle-api" + UsernamePrefix = "dms-" + SQLEDirectAudit ContextKey = "sqle_direct_audit" + SQLEProxyName = _const.SqleComponentName ) func GenerateCloudbeaverUserId(name string) string { @@ -92,24 +116,29 @@ func RemoveCloudbeaverUserIdPrefix(name string) string { return strings.TrimPrefix(name, UsernamePrefix) } -type auditSQLReq struct { +type AuditSQLReq struct { InstanceType string `json:"instance_type" form:"instance_type" example:"MySQL" valid:"required"` // 调用方不应该关心SQL是否被完美的拆分成独立的条目, 拆分SQL由SQLE实现 - SQLContent string `json:"sql_content" form:"sql_content" example:"select * from t1; select * from t2;" valid:"required"` - SQLType string `json:"sql_type" form:"sql_type" example:"sql" enums:"sql,mybatis," valid:"omitempty,oneof=sql mybatis"` + SQLContent string `json:"sql_content" form:"sql_content" example:"select * from t1; select * from t2;" valid:"required"` + SQLType string `json:"sql_type" form:"sql_type" example:"sql" enums:"sql,mybatis," valid:"omitempty,oneof=sql mybatis"` + ProjectId string `json:"project_id" form:"project_id" example:"700300" valid:"required"` + RuleTemplateName string `json:"rule_template_name" form:"rule_template_name" example:"default" valid:"required"` + InstanceName string `json:"instance_name" form:"instance_name" example:"instance1"` + SchemaName string `json:"schema_name" form:"schema_name" example:"schema1"` } -type AuditResult struct { - Level string `json:"level" example:"warn"` - Message string `json:"message" example:"避免使用不必要的内置函数md5()"` - RuleName string `json:"rule_name"` +type DirectAuditParams struct { + AuditSQLReq + SQLEAddr string + AllowQueryWhenLessThanAuditLevel string } type AuditSQLResV2 struct { - Number uint `json:"number"` - ExecSQL string `json:"exec_sql"` - AuditResult []AuditResult `json:"audit_result"` - AuditLevel string `json:"audit_level"` + Number uint `json:"number"` + ExecSQL string `json:"exec_sql"` + AuditResult dbmodel.AuditResults `json:"audit_result"` + AuditLevel string `json:"audit_level"` + SQLType string `json:"sql_type"` } type AuditResDataV2 struct { @@ -119,7 +148,7 @@ type AuditResDataV2 struct { SQLResults []AuditSQLResV2 `json:"sql_results"` } -type auditSQLReply struct { +type AuditSQLReply struct { Code int `json:"code" example:"0"` Message string `json:"message" example:"ok"` Data *AuditResDataV2 `json:"data"` @@ -130,73 +159,80 @@ func (r *MutationResolverImpl) AuditSQL(ctx context.Context, sql string, connect header := map[string]string{ "Authorization": pkgHttp.DefaultDMSToken, } - req := auditSQLReq{ - InstanceType: "MySQL", - SQLContent: sql, - SQLType: "sql", - } - reply := &auditSQLReply{} - addr := ctx.Value(SQLEProxyAddrName) - sqleAddr, ok := addr.(string) + ctxVal := ctx.Value(SQLEDirectAudit) + directAuditParams, ok := ctxVal.(DirectAuditParams) if !ok { - return false, nil, fmt.Errorf("ctx.value %s failed", SQLEProxyAddrName) + return false, nil, fmt.Errorf("ctx.value %v failed", SQLEDirectAudit) } - if sqleAddr == "" { - return false, nil, fmt.Errorf("%s is empty", SQLEProxyAddrName) + if directAuditParams.SQLEAddr == "" { + return false, nil, fmt.Errorf("%v is empty", SQLEDirectAudit) } - if err = pkgHttp.POST(ctx, sqleAddr, header, req, reply); err != nil { + req := AuditSQLReq{ + InstanceType: directAuditParams.InstanceType, + SQLContent: sql, + SQLType: "sql", + ProjectId: directAuditParams.ProjectId, + RuleTemplateName: directAuditParams.RuleTemplateName, + InstanceName: directAuditParams.InstanceName, + SchemaName: directAuditParams.SchemaName, + } + + reply := &AuditSQLReply{} + if err = pkgHttp.POST(ctx, directAuditParams.SQLEAddr, header, req, reply); err != nil { return false, nil, err } if reply.Code != 0 { return false, nil, fmt.Errorf("reply code(%v) error: %v", reply.Code, reply.Message) } - + for _, sqlResult := range reply.Data.SQLResults { + for _, res := range sqlResult.AuditResult { + if res.ExecutionFailed { + return false, reply.Data.SQLResults, nil + } + } + } if reply.Data.PassRate == 0 { + if AllowQuery(directAuditParams.AllowQueryWhenLessThanAuditLevel, reply.Data.SQLResults) { + return true, reply.Data.SQLResults, nil + } return false, reply.Data.SQLResults, nil } + return true, reply.Data.SQLResults, nil +} + +// AllowQuery 根据AllowQueryWhenLessThanAuditLevel字段判断能否执行SQL +func AllowQuery(allowQueryWhenLessThanAuditLevel string, sqlResults []AuditSQLResV2) bool { + for _, sqlResult := range sqlResults { + if dbmodel.RuleLevel(sqlResult.AuditLevel).LessOrEqual(dbmodel.RuleLevel(allowQueryWhenLessThanAuditLevel)) { + continue + } + return false + } + return true +} - return true, nil, nil +type AuditResults struct { + SQL string + IsSuccess bool + Results []AuditSQLResV2 } -func (r *MutationResolverImpl) AsyncSQLExecuteQuery(ctx context.Context, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) { +const AuditResultKey = "audit_result" + +func (r *MutationResolverImpl) AsyncSQLExecuteQuery(ctx context.Context, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) (*model.AsyncTaskInfo, error) { success, results, err := r.AuditSQL(ctx, sql, connectionID) if err != nil { return nil, err } - if !success { - var messages []string - for _, sqlResult := range results { - for _, audit := range sqlResult.AuditResult { - messages = append(messages, audit.Message) - } - } - - messageStr := strings.Join(messages, ",") - name := "SQL Audit Failed" - return nil, r.Ctx.JSON(http.StatusOK, struct { - Data struct { - TaskInfo model.AsyncTaskInfo `json:"taskInfo"` - } `json:"data"` - }{ - struct { - TaskInfo model.AsyncTaskInfo `json:"taskInfo"` - }{ - TaskInfo: model.AsyncTaskInfo{ - Name: &name, - Running: false, - Status: &sql, - Error: &model.ServerError{ - Message: &messageStr, - StackTrace: &messageStr, - }, - }, - }, - }) - } + r.Ctx.Set(AuditResultKey, AuditResults{ + SQL: sql, + IsSuccess: success, + Results: results, + }) _, err = r.Next(r.Ctx) if err != nil { @@ -206,6 +242,33 @@ func (r *MutationResolverImpl) AsyncSQLExecuteQuery(ctx context.Context, connect return nil, err } +func (r *MutationResolverImpl) AsyncSQLExecuteResults(ctx context.Context, taskID string) (*model.SQLExecuteInfo, error) { + + data, err := r.Next(r.Ctx) + if err != nil { + return nil, err + } + + resp := &struct { + Data struct { + Result *model.SQLExecuteInfo `json:"result"` + } `json:"data"` + }{} + + err = json.Unmarshal(data, resp) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal sql execute info: %v", err) + } + + if resp.Data.Result != nil && r.SQLExecuteResultsHandlerFn != nil { + if err := r.SQLExecuteResultsHandlerFn(ctx, resp.Data.Result); err != nil { + return nil, fmt.Errorf("failed to handle sql result: %v", err) + } + } + + return resp.Data.Result, err +} + type gqlBehavior struct { UseLocalHandler bool NeedModifyRemoteRes bool @@ -214,8 +277,41 @@ type gqlBehavior struct { Preprocessing func(ctx echo.Context, params *graphql.RawParams) error } +func convertKeysToInt(data interface{}, keysToConvert map[string]struct{}) error { + switch v := data.(type) { + case map[string]interface{}: + for key, val := range v { + // 若 key 是需要转 int 的字段 + if _, shouldConvert := keysToConvert[key]; shouldConvert && val != nil { + if intVal, err := toInt(val); err == nil { + v[key] = intVal + } else { + return fmt.Errorf("failed to convert key %s: %v", key, err) + } + } else { + // 否则递归处理嵌套结构 + if err := convertKeysToInt(val, keysToConvert); err != nil { + return err + } + } + } + case []interface{}: + for i := range v { + if err := convertKeysToInt(v[i], keysToConvert); err != nil { + return err + } + } + } + return nil +} + +// 通用字符串转 int 工具 +func toInt(value interface{}) (int, error) { + return strconv.Atoi(fmt.Sprintf("%v", value)) +} + var GraphQLHandlerRouters = map[string] /* gql operation name */ gqlBehavior{ - "asyncSqlExecuteQuery": { + "asyncReadDataFromContainer": { UseLocalHandler: true, NeedModifyRemoteRes: false, Preprocessing: func(ctx echo.Context, params *graphql.RawParams) (err error) { @@ -228,6 +324,38 @@ var GraphQLHandlerRouters = map[string] /* gql operation name */ gqlBehavior{ return err }, }, + "asyncSqlExecuteQuery": { + UseLocalHandler: true, + NeedModifyRemoteRes: false, + Preprocessing: func(ctx echo.Context, params *graphql.RawParams) (err error) { + // json中没有int类型, 这将导致执行json.Unmarshal()时int会被当作float64, 从而导致后面出现类型错误的异常 + keysToConvert := map[string]struct{}{ + "limit": {}, + "attributePosition": {}, + "orderPosition": {}, + } + if filter, ok := params.Variables["filter"]; ok { + if err := convertKeysToInt(filter, keysToConvert); err != nil { + log.Printf("convertKeysToInt error: %v", err) + } + } + + return err + }, + }, + "getAsyncTaskInfo": { + UseLocalHandler: true, + }, + "getSqlExecuteTaskResults": { + UseLocalHandler: true, + NeedModifyRemoteRes: true, + }, + "updateResultsDataBatch": { + UseLocalHandler: true, + }, + "asyncUpdateResultsDataBatch": { + UseLocalHandler: true, + }, "getActiveUser": { UseLocalHandler: true, NeedModifyRemoteRes: true, @@ -260,4 +388,35 @@ var GraphQLHandlerRouters = map[string] /* gql operation name */ gqlBehavior{ }, "authChangeLocalPassword": { Disable: true, }, + "navNodeChildren": {}, +} + +// NavNodeObject 导航节点对象信息 +type NavNodeObject struct { + Features []string `json:"features"` +} + +// NavNodeInfo 导航节点信息 +type NavNodeInfo struct { + ID string `json:"id"` + Name string `json:"name"` + PlainName *string `json:"plainName"` + HasChildren bool `json:"hasChildren"` + NodeType string `json:"nodeType"` + Icon string `json:"icon"` + Folder bool `json:"folder"` + Inline bool `json:"inline"` + Navigable bool `json:"navigable"` + Filtered bool `json:"filtered"` + Features []string `json:"features"` + ProjectID string `json:"projectId"` + Object *NavNodeObject `json:"object"` +} + +// NavNodeChildrenResponse 导航节点子节点响应 +type NavNodeChildrenResponse struct { + Data struct { + NavNodeChildren []NavNodeInfo `json:"navNodeChildren"` + NavNodeInfo NavNodeInfo `json:"navNodeInfo"` + } `json:"data"` } diff --git a/internal/pkg/cloudbeaver/model/models_gen.go b/internal/pkg/cloudbeaver/model/models_gen.go index 25c513118..9fb606358 100644 --- a/internal/pkg/cloudbeaver/model/models_gen.go +++ b/internal/pkg/cloudbeaver/model/models_gen.go @@ -3,6 +3,7 @@ package model import ( + "bytes" "fmt" "io" "strconv" @@ -10,17 +11,19 @@ import ( ) type AdminAuthProviderConfiguration struct { - ProviderID string `json:"providerId"` - ID string `json:"id"` - DisplayName string `json:"displayName"` - Disabled bool `json:"disabled"` - IconURL *string `json:"iconURL"` - Description *string `json:"description"` - Parameters interface{} `json:"parameters"` - SignInLink *string `json:"signInLink"` - SignOutLink *string `json:"signOutLink"` - RedirectLink *string `json:"redirectLink"` - MetadataLink *string `json:"metadataLink"` + ProviderID string `json:"providerId"` + ID string `json:"id"` + DisplayName string `json:"displayName"` + Disabled bool `json:"disabled"` + IconURL *string `json:"iconURL,omitempty"` + Description *string `json:"description,omitempty"` + Parameters any `json:"parameters"` + SignInLink *string `json:"signInLink,omitempty"` + SignOutLink *string `json:"signOutLink,omitempty"` + RedirectLink *string `json:"redirectLink,omitempty"` + MetadataLink *string `json:"metadataLink,omitempty"` + AcsLink *string `json:"acsLink,omitempty"` + EntityIDLink *string `json:"entityIdLink,omitempty"` } type AdminConnectionGrantInfo struct { @@ -38,190 +41,358 @@ type AdminConnectionSearchInfo struct { DefaultDriver string `json:"defaultDriver"` } +type AdminObjectGrantInfo struct { + SubjectID string `json:"subjectId"` + SubjectType AdminSubjectType `json:"subjectType"` + ObjectPermissions *AdminObjectPermissions `json:"objectPermissions"` +} + +type AdminObjectPermissions struct { + ObjectID string `json:"objectId"` + Permissions []string `json:"permissions"` +} + type AdminPermissionInfo struct { ID string `json:"id"` - Label *string `json:"label"` - Description *string `json:"description"` + Label *string `json:"label,omitempty"` + Description *string `json:"description,omitempty"` Provider string `json:"provider"` - Category *string `json:"category"` + Category *string `json:"category,omitempty"` } -type AdminRoleInfo struct { - RoleID string `json:"roleId"` - RoleName *string `json:"roleName"` - Description *string `json:"description"` +type AdminTeamInfo struct { + TeamID string `json:"teamId"` + TeamName *string `json:"teamName,omitempty"` + Description *string `json:"description,omitempty"` + MetaParameters any `json:"metaParameters"` GrantedUsers []string `json:"grantedUsers"` + GrantedUsersInfo []*AdminUserTeamGrantInfo `json:"grantedUsersInfo"` GrantedConnections []*AdminConnectionGrantInfo `json:"grantedConnections"` - RolePermissions []string `json:"rolePermissions"` + TeamPermissions []string `json:"teamPermissions"` +} + +type AdminUserFilterInput struct { + UserIDMask *string `json:"userIdMask,omitempty"` + EnabledState *bool `json:"enabledState,omitempty"` } type AdminUserInfo struct { UserID string `json:"userId"` - MetaParameters interface{} `json:"metaParameters"` - ConfigurationParameters interface{} `json:"configurationParameters"` - GrantedRoles []string `json:"grantedRoles"` + MetaParameters any `json:"metaParameters"` + ConfigurationParameters any `json:"configurationParameters"` + GrantedTeams []string `json:"grantedTeams"` GrantedConnections []*AdminConnectionGrantInfo `json:"grantedConnections"` Origins []*ObjectOrigin `json:"origins"` LinkedAuthProviders []string `json:"linkedAuthProviders"` Enabled bool `json:"enabled"` + AuthRole *string `json:"authRole,omitempty"` + DisableDate *time.Time `json:"disableDate,omitempty"` + DisabledBy *string `json:"disabledBy,omitempty"` + DisableReason *string `json:"disableReason,omitempty"` } +type AdminUserTeamGrantInfo struct { + UserID string `json:"userId"` + TeamRole *string `json:"teamRole,omitempty"` +} + +// Async types type AsyncTaskInfo struct { - ID string `json:"id"` - Name *string `json:"name"` - Running bool `json:"running"` - Status *string `json:"status"` - Error *ServerError `json:"error"` - Result *SQLExecuteInfo `json:"result"` - TaskResult interface{} `json:"taskResult"` + // Task unique identifier + ID string `json:"id"` + // Async task name + Name *string `json:"name,omitempty"` + // Indicates if the task is currently running + Running bool `json:"running"` + // Current status of the async task + Status *string `json:"status,omitempty"` + // Error information if the task failed + Error *ServerError `json:"error,omitempty"` + // Task result. + // Can be some kind of identifier to obtain real result using another API function + TaskResult any `json:"taskResult,omitempty"` } type AuthCredentialInfo struct { ID string `json:"id"` DisplayName string `json:"displayName"` - Description *string `json:"description"` + Description *string `json:"description,omitempty"` Admin bool `json:"admin"` User bool `json:"user"` Identifying bool `json:"identifying"` - PossibleValues []*string `json:"possibleValues"` - Encryption *AuthCredentialEncryption `json:"encryption"` + PossibleValues []*string `json:"possibleValues,omitempty"` + Encryption *AuthCredentialEncryption `json:"encryption,omitempty"` } type AuthInfo struct { - RedirectLink *string `json:"redirectLink"` - AuthID *string `json:"authId"` + RedirectLink *string `json:"redirectLink,omitempty"` + AuthID *string `json:"authId,omitempty"` AuthStatus AuthStatus `json:"authStatus"` - UserTokens []*UserAuthToken `json:"userTokens"` + UserTokens []*UserAuthToken `json:"userTokens,omitempty"` } type AuthProviderConfiguration struct { - ID string `json:"id"` - DisplayName string `json:"displayName"` - Disabled bool `json:"disabled"` - IconURL *string `json:"iconURL"` - Description *string `json:"description"` - SignInLink *string `json:"signInLink"` - SignOutLink *string `json:"signOutLink"` - MetadataLink *string `json:"metadataLink"` + ID string `json:"id"` + DisplayName string `json:"displayName"` + Disabled bool `json:"disabled"` + AuthRoleProvided *bool `json:"authRoleProvided,omitempty"` + IconURL *string `json:"iconURL,omitempty"` + Description *string `json:"description,omitempty"` + // URL to external authentication service. + // If specified then it is external authentication provider (SSO). + // Otherwise authLogin function must be called. + SignInLink *string `json:"signInLink,omitempty"` + SignOutLink *string `json:"signOutLink,omitempty"` + RedirectLink *string `json:"redirectLink,omitempty"` + MetadataLink *string `json:"metadataLink,omitempty"` + AcsLink *string `json:"acsLink,omitempty"` + EntityIDLink *string `json:"entityIdLink,omitempty"` } type AuthProviderCredentialsProfile struct { - ID *string `json:"id"` - Label *string `json:"label"` - Description *string `json:"description"` + ID *string `json:"id,omitempty"` + Label *string `json:"label,omitempty"` + Description *string `json:"description,omitempty"` CredentialParameters []*AuthCredentialInfo `json:"credentialParameters"` } type AuthProviderInfo struct { - ID string `json:"id"` - Label string `json:"label"` - Icon *string `json:"icon"` - Description *string `json:"description"` - DefaultProvider bool `json:"defaultProvider"` - Configurable bool `json:"configurable"` - Configurations []*AuthProviderConfiguration `json:"configurations"` - CredentialProfiles []*AuthProviderCredentialsProfile `json:"credentialProfiles"` - RequiredFeatures []string `json:"requiredFeatures"` -} - + ID string `json:"id"` + Label string `json:"label"` + Icon *string `json:"icon,omitempty"` + Description *string `json:"description,omitempty"` + DefaultProvider bool `json:"defaultProvider"` + Trusted bool `json:"trusted"` + Private bool `json:"private"` + AuthHidden bool `json:"authHidden"` + SupportProvisioning bool `json:"supportProvisioning"` + // Configurable providers must be configured first. See configurations field. + Configurable bool `json:"configurable"` + // Federated providers means authorization must occur asynchronously through redirects. + Federated bool `json:"federated"` + // Provider configurations (applicable only if configurable=true) + Configurations []*AuthProviderConfiguration `json:"configurations,omitempty"` + TemplateConfiguration *AuthProviderConfiguration `json:"templateConfiguration"` + CredentialProfiles []*AuthProviderCredentialsProfile `json:"credentialProfiles"` + RequiredFeatures []string `json:"requiredFeatures"` + Required bool `json:"required"` +} + +// Represents a dynamic condition for a property, such as visibility or read-only state +type Condition struct { + // The logical expression that defines when the condition applies + Expression string `json:"expression"` + // The type of condition (e.g., HIDE or READ_ONLY) + ConditionType ConditionType `json:"conditionType"` +} + +// Configuration of particular connection. Used for new connection create. Includes auth info type ConnectionConfig struct { - ConnectionID *string `json:"connectionId"` - Name *string `json:"name"` - Description *string `json:"description"` - TemplateID *string `json:"templateId"` - DriverID *string `json:"driverId"` - Host *string `json:"host"` - Port *string `json:"port"` - ServerName *string `json:"serverName"` - DatabaseName *string `json:"databaseName"` - URL *string `json:"url"` - Properties interface{} `json:"properties"` - Template *bool `json:"template"` - ReadOnly *bool `json:"readOnly"` - SaveCredentials *bool `json:"saveCredentials"` - AuthModelID *string `json:"authModelId"` - Credentials interface{} `json:"credentials"` - ProviderProperties interface{} `json:"providerProperties"` - NetworkHandlersConfig []*NetworkHandlerConfigInput `json:"networkHandlersConfig"` - DataSourceID *string `json:"dataSourceId"` - UserName *string `json:"userName"` - UserPassword *string `json:"userPassword"` - Folder *string `json:"folder"` + // used only for testing created connection + ConnectionID *string `json:"connectionId,omitempty"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + // ID of database driver + DriverID *string `json:"driverId,omitempty"` + Host *string `json:"host,omitempty"` + Port *string `json:"port,omitempty"` + ServerName *string `json:"serverName,omitempty"` + DatabaseName *string `json:"databaseName,omitempty"` + // Host, port, serverName, databaseName are also stored in mainPropertyValues for custom pages + MainPropertyValues any `json:"mainPropertyValues,omitempty"` + // Keep-alive, auto-commit, read-only and other expert settings are stored in expertSettingsValues + ExpertSettingsValues any `json:"expertSettingsValues,omitempty"` + // Sets connection URL jdbc:{driver}://{host}[:{port}]/[{database}] + URL *string `json:"url,omitempty"` + // Set properties list + Properties any `json:"properties,omitempty"` + // Set keep-alive interval + KeepAliveInterval *int `json:"keepAliveInterval,omitempty"` + // Sets auto-commit connection state + Autocommit *bool `json:"autocommit,omitempty"` + // Sets read-only connection state + ReadOnly *bool `json:"readOnly,omitempty"` + // Flag for saving credentials in secure storage + SaveCredentials *bool `json:"saveCredentials,omitempty"` + // Flag for using shared credentials. + SharedCredentials *bool `json:"sharedCredentials,omitempty"` + // Auth model ID that will be used for connection + AuthModelID *string `json:"authModelId,omitempty"` + // Secret ID that will be used for connection + SelectedSecretID *string `json:"selectedSecretId,omitempty"` + // Credentials for the connection (usually user name and password but it may vary for different auth models) + Credentials any `json:"credentials,omitempty"` + // Returns map of provider properties (name/value) + ProviderProperties any `json:"providerProperties,omitempty"` + // Returns network handlers configuration. Map of id->property map (name/value). + NetworkHandlersConfig []*NetworkHandlerConfigInput `json:"networkHandlersConfig,omitempty"` + // ID of predefined datasource + DataSourceID *string `json:"dataSourceId,omitempty"` + // Direct user credentials + UserName *string `json:"userName,omitempty"` + UserPassword *string `json:"userPassword,omitempty"` + // Defines in which connection folder the connection should be created + Folder *string `json:"folder,omitempty"` + // Configuration type (MANUAL, URL) + ConfigurationType *DriverConfigurationType `json:"configurationType,omitempty"` + // Sets catalog name for the connection + DefaultCatalogName *string `json:"defaultCatalogName,omitempty"` + // Sets schema name for the connection + DefaultSchemaName *string `json:"defaultSchemaName,omitempty"` } type ConnectionFolderInfo struct { ID string `json:"id"` - Description *string `json:"description"` + ProjectID string `json:"projectId"` + Description *string `json:"description,omitempty"` } +// Connection instance type ConnectionInfo struct { - ID string `json:"id"` - DriverID string `json:"driverId"` - Name string `json:"name"` - Description *string `json:"description"` - Host *string `json:"host"` - Port *string `json:"port"` - ServerName *string `json:"serverName"` - DatabaseName *string `json:"databaseName"` - URL *string `json:"url"` - Properties interface{} `json:"properties"` - Template bool `json:"template"` - Connected bool `json:"connected"` - Provided bool `json:"provided"` - ReadOnly bool `json:"readOnly"` - UseURL bool `json:"useUrl"` - SaveCredentials bool `json:"saveCredentials"` - Folder *string `json:"folder"` - NodePath *string `json:"nodePath"` - ConnectTime *string `json:"connectTime"` - ConnectionError *ServerError `json:"connectionError"` - ServerVersion *string `json:"serverVersion"` - ClientVersion *string `json:"clientVersion"` - Origin *ObjectOrigin `json:"origin"` - AuthNeeded bool `json:"authNeeded"` - AuthModel *string `json:"authModel"` + // Connection unique ID + ID string `json:"id"` + // ID of the driver that is used for this connection (see DriverInfo) + DriverID string `json:"driverId"` + // Connection name + Name string `json:"name"` + // Connection description + Description *string `json:"description,omitempty"` + Host *string `json:"host,omitempty"` + Port *string `json:"port,omitempty"` + ServerName *string `json:"serverName,omitempty"` + DatabaseName *string `json:"databaseName,omitempty"` + URL *string `json:"url,omitempty"` + // Main connection properties. Contains host, port, database, server name fields + MainPropertyValues any `json:"mainPropertyValues,omitempty"` + // Expert connection settings. Contains expert settings properties (like keep-alive interval or auto-commit) that are not often used + ExpertSettingsValues any `json:"expertSettingsValues,omitempty"` + // Connection keep-alive interval in seconds + KeepAliveInterval int `json:"keepAliveInterval"` + // Defines if the connection is in auto-commit mode + Autocommit *bool `json:"autocommit,omitempty"` + Properties any `json:"properties,omitempty"` + // Indicates if the connection is already connected to the database + Connected bool `json:"connected"` + Provided bool `json:"provided"` + // Indicates if the connection is read-only (no data modification allowed) + ReadOnly bool `json:"readOnly"` + // Forces connection URL use, host/port/database parameters will be ignored + UseURL bool `json:"useUrl"` + // Forces credentials save. This flag doesn't work in shared projects. + SaveCredentials bool `json:"saveCredentials"` + // Shared credentials - the same for all users, stored in secure storage. + SharedCredentials bool `json:"sharedCredentials"` + SharedSecrets []*SecretInfo `json:"sharedSecrets"` + // Determines that credentials were saved for current user. + // This field read is slow, it should be read only when it really needed + CredentialsSaved bool `json:"credentialsSaved"` + // Determines that additional credentials are needed to connect + // This field read is slow, it should be read only when it really needed + AuthNeeded bool `json:"authNeeded"` + // ID of the connection folder where this connection is stored + Folder *string `json:"folder,omitempty"` + // Node path of the connection in the navigator + NodePath *string `json:"nodePath,omitempty"` + // Connection time in ISO format + ConnectTime *string `json:"connectTime,omitempty"` + // Connection error if any + ConnectionError *ServerError `json:"connectionError,omitempty"` + // Server version that is used for this connection + ServerVersion *string `json:"serverVersion,omitempty"` + // Client version that is used for this connection + ClientVersion *string `json:"clientVersion,omitempty"` + Origin *ObjectOrigin `json:"origin"` + // ID of the auth model that is used for this connection (see authModels) + AuthModel *string `json:"authModel,omitempty"` AuthProperties []*ObjectPropertyInfo `json:"authProperties"` - ProviderProperties interface{} `json:"providerProperties"` + ProviderProperties any `json:"providerProperties"` NetworkHandlersConfig []*NetworkHandlerConfig `json:"networkHandlersConfig"` - Features []string `json:"features"` - NavigatorSettings *NavigatorSettings `json:"navigatorSettings"` - SupportedDataFormats []ResultDataFormat `json:"supportedDataFormats"` + // Supported features (provided etc) + Features []string `json:"features"` + NavigatorSettings *NavigatorSettings `json:"navigatorSettings"` + SupportedDataFormats []ResultDataFormat `json:"supportedDataFormats"` + ConfigurationType *DriverConfigurationType `json:"configurationType,omitempty"` + CanViewSettings bool `json:"canViewSettings"` + CanEdit bool `json:"canEdit"` + CanDelete bool `json:"canDelete"` + ProjectID string `json:"projectId"` + RequiredAuth *string `json:"requiredAuth,omitempty"` + DefaultCatalogName *string `json:"defaultCatalogName,omitempty"` + DefaultSchemaName *string `json:"defaultSchemaName,omitempty"` + // List of tools that can be used with this connection. Returns empty list if no tools are available + Tools []string `json:"tools"` +} + +type DataTransferDefaultExportSettings struct { + OutputSettings *DataTransferOutputSettings `json:"outputSettings"` + SupportedEncodings []string `json:"supportedEncodings"` +} + +type DataTransferOutputSettings struct { + InsertBom bool `json:"insertBom"` + Encoding string `json:"encoding"` + TimestampPattern string `json:"timestampPattern"` + Compress bool `json:"compress"` +} + +type DataTransferOutputSettingsInput struct { + InsertBom *bool `json:"insertBom,omitempty"` + Encoding *string `json:"encoding,omitempty"` + TimestampPattern *string `json:"timestampPattern,omitempty"` + Compress *bool `json:"compress,omitempty"` + FileName *string `json:"fileName,omitempty"` } type DataTransferParameters struct { - ProcessorID string `json:"processorId"` - Settings interface{} `json:"settings"` - ProcessorProperties interface{} `json:"processorProperties"` - Filter *SQLDataFilter `json:"filter"` + // Processor ID + ProcessorID string `json:"processorId"` + // General settings: + // - openNewConnection: opens new database connection for data transfer task + Settings any `json:"settings,omitempty"` + // Processor properties. See DataTransferProcessorInfo.properties + ProcessorProperties any `json:"processorProperties"` + // Consumer properties. See StreamConsumerSettings + OutputSettings *DataTransferOutputSettingsInput `json:"outputSettings,omitempty"` + // Data filter settings + Filter *SQLDataFilter `json:"filter,omitempty"` } type DataTransferProcessorInfo struct { ID string `json:"id"` - Name *string `json:"name"` - Description *string `json:"description"` - FileExtension *string `json:"fileExtension"` - AppFileExtension *string `json:"appFileExtension"` - AppName *string `json:"appName"` + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + FileExtension *string `json:"fileExtension,omitempty"` + AppFileExtension *string `json:"appFileExtension,omitempty"` + AppName *string `json:"appName,omitempty"` Order int `json:"order"` - Icon *string `json:"icon"` - Properties []*ObjectPropertyInfo `json:"properties"` - IsBinary *bool `json:"isBinary"` - IsHTML *bool `json:"isHTML"` + Icon *string `json:"icon,omitempty"` + Properties []*ObjectPropertyInfo `json:"properties,omitempty"` + IsBinary *bool `json:"isBinary,omitempty"` + IsHTML *bool `json:"isHTML,omitempty"` } type DataTypeLogicalOperation struct { ID string `json:"id"` Expression string `json:"expression"` - ArgumentCount *int `json:"argumentCount"` + ArgumentCount *int `json:"argumentCount,omitempty"` } +// Drivers and connections type DatabaseAuthModel struct { - ID string `json:"id"` - DisplayName string `json:"displayName"` - Description *string `json:"description"` - Icon *string `json:"icon"` - RequiresLocalConfiguration *bool `json:"requiresLocalConfiguration"` - Properties []*ObjectPropertyInfo `json:"properties"` + // Auth model unique ID + ID string `json:"id"` + // Display name of the auth model + DisplayName string `json:"displayName"` + // Description of the auth model + Description *string `json:"description,omitempty"` + // Path to the auth model icon + Icon *string `json:"icon,omitempty"` + // Checks if the auth model needs a configuration on a local file system + RequiresLocalConfiguration *bool `json:"requiresLocalConfiguration,omitempty"` + // Returns id of the required auth provider if the auth model requires it + RequiredAuth *string `json:"requiredAuth,omitempty"` + // List of properties for the auth model that can be displayed in the UI + Properties []*ObjectPropertyInfo `json:"properties"` } type DatabaseCatalog struct { @@ -230,87 +401,223 @@ type DatabaseCatalog struct { } type DatabaseDocument struct { - ID *string `json:"id"` - ContentType *string `json:"contentType"` - Properties interface{} `json:"properties"` - Data interface{} `json:"data"` + ID *string `json:"id,omitempty"` + ContentType *string `json:"contentType,omitempty"` + Properties any `json:"properties,omitempty"` + Data any `json:"data,omitempty"` } type DatabaseObjectInfo struct { - Name *string `json:"name"` - Description *string `json:"description"` - Type *string `json:"type"` - Properties []*ObjectPropertyInfo `json:"properties"` - OrdinalPosition *int `json:"ordinalPosition"` - FullyQualifiedName *string `json:"fullyQualifiedName"` - OverloadedName *string `json:"overloadedName"` - UniqueName *string `json:"uniqueName"` - State *string `json:"state"` - Features []string `json:"features"` - Editors []string `json:"editors"` + // Object name + Name *string `json:"name,omitempty"` + // Description - optional + Description *string `json:"description,omitempty"` + // Object type. Java class name in most cases + Type *string `json:"type,omitempty"` + // Read object properties. + // Optional parameter 'ids' filters properties by id. null means all properties. + // Note: property value reading may take a lot of time so don't read all property values always + // Examine property meta (features in particular) before reading them + Properties []*ObjectPropertyInfo `json:"properties,omitempty"` + OrdinalPosition *int `json:"ordinalPosition,omitempty"` + FullyQualifiedName *string `json:"fullyQualifiedName,omitempty"` + OverloadedName *string `json:"overloadedName,omitempty"` + UniqueName *string `json:"uniqueName,omitempty"` + State *string `json:"state,omitempty"` + // Features: script, scriptExtended, dataContainer, dataManipulator, entity, schema, catalog + Features []string `json:"features,omitempty"` + // Supported editors: ddl, permissions, sourceDeclaration, sourceDefinition + Editors []string `json:"editors,omitempty"` } type DatabaseStructContainers struct { + ParentNode *NavigatorNodeInfo `json:"parentNode,omitempty"` CatalogList []*DatabaseCatalog `json:"catalogList"` SchemaList []*NavigatorNodeInfo `json:"schemaList"` SupportsCatalogChange bool `json:"supportsCatalogChange"` SupportsSchemaChange bool `json:"supportsSchemaChange"` } +// Driver file information. +type DriverFileInfo struct { + // Driver file unique ID + ID string `json:"id"` + // Driver file name + FileName string `json:"fileName"` + // Path to the driver file icon + Icon *string `json:"icon,omitempty"` +} + type DriverInfo struct { - ID string `json:"id"` - Name *string `json:"name"` - Description *string `json:"description"` - Icon *string `json:"icon"` - IconBig *string `json:"iconBig"` - ProviderID *string `json:"providerId"` - DriverClassName *string `json:"driverClassName"` - DefaultHost *string `json:"defaultHost"` - DefaultPort *string `json:"defaultPort"` - DefaultDatabase *string `json:"defaultDatabase"` - DefaultServer *string `json:"defaultServer"` - DefaultUser *string `json:"defaultUser"` - SampleURL *string `json:"sampleURL"` - DriverInfoURL *string `json:"driverInfoURL"` - DriverPropertiesURL *string `json:"driverPropertiesURL"` - Embedded *bool `json:"embedded"` - Enabled bool `json:"enabled"` - RequiresServerName *bool `json:"requiresServerName"` - AllowsEmptyPassword *bool `json:"allowsEmptyPassword"` - LicenseRequired *bool `json:"licenseRequired"` - License *string `json:"license"` - Custom *bool `json:"custom"` - PromotedScore *int `json:"promotedScore"` - DriverProperties []*ObjectPropertyInfo `json:"driverProperties"` - DriverParameters interface{} `json:"driverParameters"` - ProviderProperties []*ObjectPropertyInfo `json:"providerProperties"` - AnonymousAccess *bool `json:"anonymousAccess"` - DefaultAuthModel string `json:"defaultAuthModel"` - ApplicableAuthModels []string `json:"applicableAuthModels"` - ApplicableNetworkHandlers []*string `json:"applicableNetworkHandlers"` + // Driver unique full ID. It is `providerId + "." + driverId`. + // It is recommended to use providerId and driverId separately. + ID string `json:"id"` + // Name of the driver + Name *string `json:"name,omitempty"` + // Description of the driver + Description *string `json:"description,omitempty"` + // Path to the driver icon + Icon *string `json:"icon,omitempty"` + // Path to the driver icon for big size + IconBig *string `json:"iconBig,omitempty"` + // Driver ID. It is unique within provider + DriverID string `json:"driverId"` + // Driver provider ID. It is globally unique + ProviderID string `json:"providerId"` + // Driver Java class name + DriverClassName *string `json:"driverClassName,omitempty"` + // Default host for the driver + DefaultHost *string `json:"defaultHost,omitempty"` + // Default port for the driver + DefaultPort *string `json:"defaultPort,omitempty"` + // Default database name for the driver + DefaultDatabase *string `json:"defaultDatabase,omitempty"` + // Default server name for the driver + DefaultServer *string `json:"defaultServer,omitempty"` + // Default user name for the driver + DefaultUser *string `json:"defaultUser,omitempty"` + // Default connection URL for the driver + SampleURL *string `json:"sampleURL,omitempty"` + // Returns link to the driver documentation page + DriverInfoURL *string `json:"driverInfoURL,omitempty"` + // Returns link to the driver properties page + DriverPropertiesURL *string `json:"driverPropertiesURL,omitempty"` + // Defines if the database for this driver is embedded + Embedded *bool `json:"embedded,omitempty"` + // Defines if the driver is enabled + Enabled bool `json:"enabled"` + // Defines if the driver page requires server name field + RequiresServerName *bool `json:"requiresServerName,omitempty"` + // Defines if the driver page requires database name field + RequiresDatabaseName *bool `json:"requiresDatabaseName,omitempty"` + // Defines if host, port, database, server name fields are using a custom page + UseCustomPage bool `json:"useCustomPage"` + // Defines if driver license is required + LicenseRequired *bool `json:"licenseRequired,omitempty"` + // Driver license information + License *string `json:"license,omitempty"` + // Defines if the driver is a custom driver + Custom *bool `json:"custom,omitempty"` + // Driver score for ordering, biggest first + PromotedScore *int `json:"promotedScore,omitempty"` + // Driver properties. + // Note: it is expensive property and it may produce database server roundtrips. + // Call it only when you really need it. + // These properties are for advanced users in usually shouldn't be specified for new connections. + DriverProperties []*ObjectPropertyInfo `json:"driverProperties"` + // Driver parameters (map name->value) + DriverParameters any `json:"driverParameters"` + // Main driver properties. + // Contains info about main fields (host, port, database, server name) that are used in main connection page + MainProperties []*ObjectPropertyInfo `json:"mainProperties"` + // Additional driver provider properties. + // These properties can be configured by user on main connection page to provide important connection settings + ProviderProperties []*ObjectPropertyInfo `json:"providerProperties"` + // Expert driver settings properties. Returns properties (like keep-alive interval) that are not often used and can be hidden in UI + ExpertSettingsProperties []*ObjectPropertyInfo `json:"expertSettingsProperties"` + // False for drivers which do not support authentication. + AnonymousAccess *bool `json:"anonymousAccess,omitempty"` + // Default auth model that is used for this driver (see authModels) + DefaultAuthModel string `json:"defaultAuthModel"` + // List of auth models that can be used with this driver (see authModels) + ApplicableAuthModels []string `json:"applicableAuthModels"` + // List of network handlers that can be used with this driver (SSH/SSL) + ApplicableNetworkHandlers []*string `json:"applicableNetworkHandlers"` + // Configuration types are used in UI to determine how to display connection settings (show host/port/database fields or use URL field) + ConfigurationTypes []*DriverConfigurationType `json:"configurationTypes"` + // Defines if the driver can be downloaded remotely + Downloadable bool `json:"downloadable"` + // Defines if the driver is installed on the server + DriverInstalled bool `json:"driverInstalled"` + // List of driver libraries that are used for connecting to the database + DriverLibraries []*DriverLibraryInfo `json:"driverLibraries"` + // Defines if embedded driver is safe to use in the server + SafeEmbeddedDriver bool `json:"safeEmbeddedDriver"` +} + +// Driver library information. Used to display driver files in UI +type DriverLibraryInfo struct { + // Driver library unique ID + ID string `json:"id"` + // Driver library name + Name string `json:"name"` + // Path to the driver library icon + Icon *string `json:"icon,omitempty"` + // List of files that are used by the driver + LibraryFiles []*DriverFileInfo `json:"libraryFiles,omitempty"` +} + +type DynamicTraceProperty struct { + Name string `json:"name"` + Value *string `json:"value,omitempty"` + Description *string `json:"description,omitempty"` +} + +type FederatedAuthInfo struct { + RedirectLink string `json:"redirectLink"` + TaskInfo *AsyncTaskInfo `json:"taskInfo"` +} + +type FederatedAuthResult struct { + UserTokens []*UserAuthToken `json:"userTokens"` } type LogEntry struct { - Time *time.Time `json:"time"` + Time *time.Time `json:"time,omitempty"` Type string `json:"type"` - Message *string `json:"message"` - StackTrace *string `json:"stackTrace"` + Message *string `json:"message,omitempty"` + StackTrace *string `json:"stackTrace,omitempty"` +} + +type LogoutInfo struct { + RedirectLinks []string `json:"redirectLinks"` +} + +type Mutation struct { +} + +type NavigatorNodeFilter struct { + Include []string `json:"include,omitempty"` + Exclude []string `json:"exclude,omitempty"` } type NavigatorNodeInfo struct { - ID string `json:"id"` - Name *string `json:"name"` - FullName *string `json:"fullName"` - Icon *string `json:"icon"` - Description *string `json:"description"` - NodeType *string `json:"nodeType"` - HasChildren *bool `json:"hasChildren"` - Object *DatabaseObjectInfo `json:"object"` - Features []string `json:"features"` - NodeDetails []*ObjectPropertyInfo `json:"nodeDetails"` - Folder *bool `json:"folder"` - Inline *bool `json:"inline"` - Navigable *bool `json:"navigable"` + // Node ID - generally a full path to the node from root of tree + ID string `json:"id"` + // Node URI - a unique path to a node including all parent nodes + URI string `json:"uri"` + // Node human readable name + Name *string `json:"name,omitempty"` + // Node full name + FullName *string `json:"fullName,omitempty"` + // Node plain name (23.2.0) + PlainName *string `json:"plainName,omitempty"` + // Node icon path + Icon *string `json:"icon,omitempty"` + // Node description + Description *string `json:"description,omitempty"` + // Node type + NodeType *string `json:"nodeType,omitempty"` + // Can this property have child nodes? + HasChildren bool `json:"hasChildren"` + // Project id of the node + ProjectID *string `json:"projectId,omitempty"` + // Associated object. Maybe null for non-database objects + Object *DatabaseObjectInfo `json:"object,omitempty"` + // Associated object. Return value depends on the node type - connectionId for connection node, resource path for resource node, etc. + // null - if node currently not support this property + ObjectID *string `json:"objectId,omitempty"` + // Supported features: item, container, leaf, canDelete, canRename + Features []string `json:"features,omitempty"` + // Object detailed info. + // If is different than properties. It doesn't perform any expensive operation and doesn't require authentication. + NodeDetails []*ObjectPropertyInfo `json:"nodeDetails,omitempty"` + Folder bool `json:"folder"` + Inline bool `json:"inline"` + Navigable bool `json:"navigable"` + Filtered bool `json:"filtered"` + // Reads node filter. Expensive invocation, read only when it is really needed + Filter *NavigatorNodeFilter `json:"filter,omitempty"` } type NavigatorSettings struct { @@ -334,149 +641,273 @@ type NavigatorSettingsInput struct { } type NetworkEndpointInfo struct { - Message *string `json:"message"` - ClientVersion *string `json:"clientVersion"` - ServerVersion *string `json:"serverVersion"` + Message *string `json:"message,omitempty"` + ClientVersion *string `json:"clientVersion,omitempty"` + ServerVersion *string `json:"serverVersion,omitempty"` } +// SSH/SSL network handler config. Name without prefix only for backward compatibility type NetworkHandlerConfig struct { - ID string `json:"id"` - Enabled bool `json:"enabled"` - AuthType NetworkHandlerAuthType `json:"authType"` - UserName *string `json:"userName"` - Password *string `json:"password"` - Key *string `json:"key"` - SavePassword bool `json:"savePassword"` - Properties interface{} `json:"properties"` + ID string `json:"id"` + // Defines if the network handler is enabled + Enabled bool `json:"enabled"` + // SSH network handler auth type + AuthType NetworkHandlerAuthType `json:"authType"` + // SSH network handler user name + UserName *string `json:"userName,omitempty"` + // SSH network handler user password + Password *string `json:"password,omitempty"` + // SSH network handler private key + Key *string `json:"key,omitempty"` + // A flag that indicates if the password should be saved in the secure storage + SavePassword bool `json:"savePassword"` + // Network handler properties (name/value) + Properties any `json:"properties"` + // Network handler secure properties (name/value). Used for passwords and keys + SecureProperties any `json:"secureProperties"` } type NetworkHandlerConfigInput struct { - ID string `json:"id"` - Enabled *bool `json:"enabled"` - AuthType *NetworkHandlerAuthType `json:"authType"` - UserName *string `json:"userName"` - Password *string `json:"password"` - Key *string `json:"key"` - SavePassword *bool `json:"savePassword"` - Properties interface{} `json:"properties"` -} - + ID string `json:"id"` + // Defines if the network handler should be enabled + Enabled *bool `json:"enabled,omitempty"` + // Network handler type (TUNNEL, PROXY, CONFIG) + AuthType *NetworkHandlerAuthType `json:"authType,omitempty"` + // Sets user name for the network handler (SSH) + UserName *string `json:"userName,omitempty"` + // Sets user password for the network handler (SSH) + Password *string `json:"password,omitempty"` + // Sets private key for the network handler (SSH) + Key *string `json:"key,omitempty"` + // Sets a flag that indicates if the password should be saved in the secure storage + SavePassword *bool `json:"savePassword,omitempty"` + // Network handler properties (name/value) + Properties any `json:"properties,omitempty"` + // Network handler secure properties (name/value). Used for passwords and keys + SecureProperties any `json:"secureProperties,omitempty"` +} + +// Network handler descriptor. +// This descriptor is used to describe network handlers (SSH/SSL) that can be used for connections. type NetworkHandlerDescriptor struct { - ID string `json:"id"` - CodeName string `json:"codeName"` - Label string `json:"label"` - Description *string `json:"description"` - Secured bool `json:"secured"` - Type *NetworkHandlerType `json:"type"` - Properties []*ObjectPropertyInfo `json:"properties"` + ID string `json:"id"` + CodeName string `json:"codeName"` + Label string `json:"label"` + Description *string `json:"description,omitempty"` + Secured bool `json:"secured"` + Type *NetworkHandlerType `json:"type,omitempty"` + // Properties that can be displayed in the UI + Properties []*ObjectPropertyInfo `json:"properties"` } type ObjectDescriptor struct { - ID *int `json:"id"` - DisplayName *string `json:"displayName"` - FullName *string `json:"fullName"` - UniqueName *string `json:"uniqueName"` - Description *string `json:"description"` - Value *string `json:"value"` + ID *int `json:"id,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + FullName *string `json:"fullName,omitempty"` + UniqueName *string `json:"uniqueName,omitempty"` + Description *string `json:"description,omitempty"` + Value *string `json:"value,omitempty"` } type ObjectDetails struct { - ID *int `json:"id"` - DisplayName *string `json:"displayName"` - Description *string `json:"description"` - Value interface{} `json:"value"` + ID *int `json:"id,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + Description *string `json:"description,omitempty"` + Value any `json:"value,omitempty"` } type ObjectOrigin struct { Type string `json:"type"` - SubType *string `json:"subType"` + SubType *string `json:"subType,omitempty"` DisplayName string `json:"displayName"` - Icon *string `json:"icon"` - Configuration interface{} `json:"configuration"` - Details []*ObjectPropertyInfo `json:"details"` + Icon *string `json:"icon,omitempty"` + Configuration any `json:"configuration,omitempty"` + Details []*ObjectPropertyInfo `json:"details,omitempty"` } type ObjectPropertyFilter struct { - Ids []string `json:"ids"` - Features []string `json:"features"` - Categories []string `json:"categories"` - DataTypes []string `json:"dataTypes"` + Ids []string `json:"ids,omitempty"` + Features []string `json:"features,omitempty"` + Categories []string `json:"categories,omitempty"` + DataTypes []string `json:"dataTypes,omitempty"` } +// Information about the object property used to generate its UI type ObjectPropertyInfo struct { - ID *string `json:"id"` - DisplayName *string `json:"displayName"` - Description *string `json:"description"` - Category *string `json:"category"` - DataType *string `json:"dataType"` - Value interface{} `json:"value"` - ValidValues []interface{} `json:"validValues"` - DefaultValue interface{} `json:"defaultValue"` - Length ObjectPropertyLength `json:"length"` - Features []string `json:"features"` - Order int `json:"order"` -} - + // Unique property identifier + ID *string `json:"id,omitempty"` + // Human-readable name + DisplayName *string `json:"displayName,omitempty"` + // Property description + Description *string `json:"description,omitempty"` + // Usage hint for the property + Hint *string `json:"hint,omitempty"` + // Property category (may be used if object has a lot of properties) + Category *string `json:"category,omitempty"` + // Property data type (e.g., int, String) + DataType *string `json:"dataType,omitempty"` + // Property value (can be resource-intensive for some properties, e.g., RowCount for tables) + Value any `json:"value,omitempty"` + // List of allowed values (for enumerable properties) + ValidValues []any `json:"validValues,omitempty"` + // Default property value + DefaultValue any `json:"defaultValue,omitempty"` + // Property value length + Length ObjectPropertyLength `json:"length"` + // List of supported features (e.g., system, hidden, inherited, foreign, expensive) + Features []string `json:"features"` + // Order position + Order int `json:"order"` + // Supported configuration types (for driver properties) + SupportedConfigurationTypes []string `json:"supportedConfigurationTypes,omitempty"` + // Is the property required + Required bool `json:"required"` + // List of preference scopes (e.g., global, user) + Scopes []string `json:"scopes,omitempty"` + // Dynamic conditions for the property (e.g., visibility or read-only) + Conditions []*Condition `json:"conditions,omitempty"` +} + +type PageInput struct { + Limit *int `json:"limit,omitempty"` + Offset *int `json:"offset,omitempty"` +} + +// Password policy configuration +type PasswordPolicyConfig struct { + // Minimum password length + MinLength int `json:"minLength"` + // Minimum number of digits required + MinNumberCount int `json:"minNumberCount"` + // Minimum number of symbols required + MinSymbolCount int `json:"minSymbolCount"` + // Require both uppercase and lowercase letters + RequireMixedCase bool `json:"requireMixedCase"` +} + +// Product information type ProductInfo struct { - ID string `json:"id"` - Version string `json:"version"` - Name string `json:"name"` - Description *string `json:"description"` - BuildTime string `json:"buildTime"` - ReleaseTime string `json:"releaseTime"` - LicenseInfo *string `json:"licenseInfo"` - LatestVersionInfo *string `json:"latestVersionInfo"` + // ID of the product + ID string `json:"id"` + // The product version + Version string `json:"version"` + // The product name + Name string `json:"name"` + // The product description + Description *string `json:"description,omitempty"` + // The build timestamp of the product + BuildTime string `json:"buildTime"` + // The release timestamp of the product + ReleaseTime string `json:"releaseTime"` + // Information about the product license + LicenseInfo *string `json:"licenseInfo,omitempty"` + // Information about the latest available version + LatestVersionInfo *string `json:"latestVersionInfo,omitempty"` + // URL for purchasing the product + ProductPurchaseURL *string `json:"productPurchaseURL,omitempty"` +} + +type ProductSettings struct { + Groups []*ProductSettingsGroup `json:"groups"` + // each property is associated with a group by category + Settings []*ObjectPropertyInfo `json:"settings"` +} + +type ProductSettingsGroup struct { + ID string `json:"id"` + DisplayName string `json:"displayName"` +} + +type ProjectInfo struct { + ID string `json:"id"` + Global bool `json:"global"` + Shared bool `json:"shared"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + CanEditDataSources bool `json:"canEditDataSources"` + CanViewDataSources bool `json:"canViewDataSources"` + CanEditResources bool `json:"canEditResources"` + CanViewResources bool `json:"canViewResources"` + ResourceTypes []*RMResourceType `json:"resourceTypes"` +} + +type Query struct { } type RMProject struct { - ID string `json:"id"` - Name string `json:"name"` - Description *string `json:"description"` - Shared bool `json:"shared"` - CreateTime time.Time `json:"createTime"` - Creator string `json:"creator"` + ID string `json:"id"` + Name string `json:"name"` + Description *string `json:"description,omitempty"` + Shared bool `json:"shared"` + Global bool `json:"global"` + CreateTime time.Time `json:"createTime"` + Creator string `json:"creator"` + ProjectPermissions []string `json:"projectPermissions"` + ResourceTypes []*RMResourceType `json:"resourceTypes"` +} + +type RMProjectPermissions struct { + ProjectID string `json:"projectId"` + Permissions []string `json:"permissions"` } type RMResource struct { - Name string `json:"name"` - Folder bool `json:"folder"` - Length int `json:"length"` + Name string `json:"name"` + Folder bool `json:"folder"` + Length int `json:"length"` + Properties any `json:"properties,omitempty"` +} + +type RMResourceType struct { + ID string `json:"id"` + DisplayName string `json:"displayName"` + Icon *string `json:"icon,omitempty"` + FileExtensions []string `json:"fileExtensions"` + RootFolder *string `json:"rootFolder,omitempty"` +} + +type RMSubjectProjectPermissions struct { + SubjectID string `json:"subjectId"` + Permissions []string `json:"permissions"` } type SQLCompletionProposal struct { DisplayString string `json:"displayString"` Type string `json:"type"` - Score *int `json:"score"` + Score *int `json:"score,omitempty"` ReplacementString string `json:"replacementString"` ReplacementOffset int `json:"replacementOffset"` ReplacementLength int `json:"replacementLength"` - CursorPosition *int `json:"cursorPosition"` - Icon *string `json:"icon"` - NodePath *string `json:"nodePath"` + CursorPosition *int `json:"cursorPosition,omitempty"` + Icon *string `json:"icon,omitempty"` + NodePath *string `json:"nodePath,omitempty"` } type SQLContextInfo struct { ID string `json:"id"` + ProjectID string `json:"projectId"` ConnectionID string `json:"connectionId"` - DefaultCatalog *string `json:"defaultCatalog"` - DefaultSchema *string `json:"defaultSchema"` + AutoCommit *bool `json:"autoCommit,omitempty"` + DefaultCatalog *string `json:"defaultCatalog,omitempty"` + DefaultSchema *string `json:"defaultSchema,omitempty"` } type SQLDataFilter struct { - Offset *float64 `json:"offset"` - Limit *int `json:"limit"` - Constraints []*SQLDataFilterConstraint `json:"constraints"` - Where *string `json:"where"` - OrderBy *string `json:"orderBy"` + // Row offset. We use Float because offset may be bigger than 32 bit. + Offset *float64 `json:"offset,omitempty"` + Limit *int `json:"limit,omitempty"` + Constraints []*SQLDataFilterConstraint `json:"constraints,omitempty"` + Where *string `json:"where,omitempty"` + OrderBy *string `json:"orderBy,omitempty"` } type SQLDataFilterConstraint struct { - AttributePosition int `json:"attributePosition"` - OrderPosition *int `json:"orderPosition"` - OrderAsc *bool `json:"orderAsc"` - Criteria *string `json:"criteria"` - Operator *string `json:"operator"` - Value interface{} `json:"value"` + AttributePosition int `json:"attributePosition"` + OrderPosition *int `json:"orderPosition,omitempty"` + OrderAsc *bool `json:"orderAsc,omitempty"` + Criteria *string `json:"criteria,omitempty"` + Operator *string `json:"operator,omitempty"` + Value any `json:"value,omitempty"` } type SQLDialectInfo struct { @@ -487,16 +918,17 @@ type SQLDialectInfo struct { QuoteStrings [][]*string `json:"quoteStrings"` SingleLineComments []*string `json:"singleLineComments"` MultiLineComments [][]*string `json:"multiLineComments"` - CatalogSeparator *string `json:"catalogSeparator"` - StructSeparator *string `json:"structSeparator"` - ScriptDelimiter *string `json:"scriptDelimiter"` + CatalogSeparator *string `json:"catalogSeparator,omitempty"` + StructSeparator *string `json:"structSeparator,omitempty"` + ScriptDelimiter *string `json:"scriptDelimiter,omitempty"` SupportsExplainExecutionPlan bool `json:"supportsExplainExecutionPlan"` } type SQLExecuteInfo struct { - StatusMessage *string `json:"statusMessage"` + StatusMessage *string `json:"statusMessage,omitempty"` Duration int `json:"duration"` - FilterText *string `json:"filterText"` + FilterText *string `json:"filterText,omitempty"` + FullQuery *string `json:"fullQuery,omitempty"` Results []*SQLQueryResults `json:"results"` } @@ -507,61 +939,93 @@ type SQLExecutionPlan struct { type SQLExecutionPlanNode struct { ID string `json:"id"` - ParentID *string `json:"parentId"` + ParentID *string `json:"parentId,omitempty"` Kind string `json:"kind"` - Name *string `json:"name"` + Name *string `json:"name,omitempty"` Type string `json:"type"` - Condition *string `json:"condition"` - Description *string `json:"description"` + Condition *string `json:"condition,omitempty"` + Description *string `json:"description,omitempty"` Properties []*ObjectPropertyInfo `json:"properties"` } type SQLQueryGenerator struct { ID string `json:"id"` Label string `json:"label"` - Description *string `json:"description"` + Description *string `json:"description,omitempty"` Order int `json:"order"` MultiObject bool `json:"multiObject"` } type SQLQueryResults struct { - Title *string `json:"title"` - UpdateRowCount *float64 `json:"updateRowCount"` - SourceQuery *string `json:"sourceQuery"` - DataFormat *ResultDataFormat `json:"dataFormat"` - ResultSet *SQLResultSet `json:"resultSet"` + Title *string `json:"title,omitempty"` + UpdateRowCount *float64 `json:"updateRowCount,omitempty"` + SourceQuery *string `json:"sourceQuery,omitempty"` + DataFormat *ResultDataFormat `json:"dataFormat,omitempty"` + ResultSet *SQLResultSet `json:"resultSet,omitempty"` } type SQLResultColumn struct { - Position int `json:"position"` - Name *string `json:"name"` - Label *string `json:"label"` - Icon *string `json:"icon"` - EntityName *string `json:"entityName"` - DataKind *string `json:"dataKind"` - TypeName *string `json:"typeName"` - FullTypeName *string `json:"fullTypeName"` - MaxLength *float64 `json:"maxLength"` - Scale *int `json:"scale"` - Precision *int `json:"precision"` - Required bool `json:"required"` - ReadOnly bool `json:"readOnly"` - ReadOnlyStatus *string `json:"readOnlyStatus"` + Position int `json:"position"` + Name *string `json:"name,omitempty"` + Label *string `json:"label,omitempty"` + Icon *string `json:"icon,omitempty"` + EntityName *string `json:"entityName,omitempty"` + DataKind *string `json:"dataKind,omitempty"` + TypeName *string `json:"typeName,omitempty"` + FullTypeName *string `json:"fullTypeName,omitempty"` + // Column value max length. We use Float because it may be bigger than 32 bit + MaxLength *float64 `json:"maxLength,omitempty"` + Scale *int `json:"scale,omitempty"` + Precision *int `json:"precision,omitempty"` + Required bool `json:"required"` + AutoGenerated bool `json:"autoGenerated"` + ReadOnly bool `json:"readOnly"` + ReadOnlyStatus *string `json:"readOnlyStatus,omitempty"` + // Operations supported for this attribute SupportedOperations []*DataTypeLogicalOperation `json:"supportedOperations"` + // Description of the column + Description *string `json:"description,omitempty"` } type SQLResultRow struct { - Data []interface{} `json:"data"` - UpdateValues interface{} `json:"updateValues"` + Data []any `json:"data"` + UpdateValues any `json:"updateValues,omitempty"` + MetaData any `json:"metaData,omitempty"` +} + +type SQLResultRowMetaData struct { + Data []any `json:"data"` + MetaData any `json:"metaData,omitempty"` +} + +type SQLResultRowMetaDataInput struct { + Data []any `json:"data,omitempty"` + MetaData any `json:"metaData"` } type SQLResultSet struct { - ID string `json:"id"` - Columns []*SQLResultColumn `json:"columns"` - Rows [][]interface{} `json:"rows"` - SingleEntity bool `json:"singleEntity"` - HasMoreData bool `json:"hasMoreData"` - HasRowIdentifier bool `json:"hasRowIdentifier"` + // Result set ID + ID string `json:"id"` + // Returns list of columns in the result set + Columns []*SQLResultColumn `json:"columns,omitempty"` + // Returns list of rows in the result set. Each row is an array of column values + Rows [][]any `json:"rows,omitempty"` + // Returns list of rows in the result set. Each row contains data and metadata + RowsWithMetaData []*SQLResultRowMetaData `json:"rowsWithMetaData,omitempty"` + SingleEntity bool `json:"singleEntity"` + HasMoreData bool `json:"hasMoreData"` + // Identifies if result set has row identifier. If true then it is possible update data or load LOB files + HasRowIdentifier bool `json:"hasRowIdentifier"` + // Identifies if result has children collections. If true then children collections can be read from the result set + HasChildrenCollection bool `json:"hasChildrenCollection"` + // Identifies if result set supports dynamic trace. If true then dynamic trace can be read from the result set + HasDynamicTrace bool `json:"hasDynamicTrace"` + // Identifies if result set supports data filter. If true then data filter can be applied to the result set + IsSupportsDataFilter bool `json:"isSupportsDataFilter"` + // Identifies if result set is read-only. If true then no updates are allowed + ReadOnly bool `json:"readOnly"` + // Status of read-only result set. If readOnly is true then this field contains reason why result set is read-only + ReadOnlyStatus *string `json:"readOnlyStatus,omitempty"` } type SQLScriptInfo struct { @@ -573,134 +1037,217 @@ type SQLScriptQuery struct { End int `json:"end"` } -type ServerConfig struct { - Name string `json:"name"` - Version string `json:"version"` - WorkspaceID string `json:"workspaceId"` - ServerURL string `json:"serverURL"` - RootURI string `json:"rootURI"` - HostName string `json:"hostName"` - AnonymousAccessEnabled *bool `json:"anonymousAccessEnabled"` - AuthenticationEnabled *bool `json:"authenticationEnabled"` - SupportsCustomConnections *bool `json:"supportsCustomConnections"` - SupportsConnectionBrowser *bool `json:"supportsConnectionBrowser"` - SupportsWorkspaces *bool `json:"supportsWorkspaces"` - ResourceManagerEnabled *bool `json:"resourceManagerEnabled"` - PublicCredentialsSaveEnabled *bool `json:"publicCredentialsSaveEnabled"` - AdminCredentialsSaveEnabled *bool `json:"adminCredentialsSaveEnabled"` - LicenseRequired bool `json:"licenseRequired"` - LicenseValid bool `json:"licenseValid"` - SessionExpireTime *int `json:"sessionExpireTime"` - LocalHostAddress *string `json:"localHostAddress"` - ConfigurationMode *bool `json:"configurationMode"` - DevelopmentMode *bool `json:"developmentMode"` - RedirectOnFederatedAuth *bool `json:"redirectOnFederatedAuth"` - EnabledFeatures []string `json:"enabledFeatures"` - EnabledAuthProviders []string `json:"enabledAuthProviders"` - SupportedLanguages []*ServerLanguage `json:"supportedLanguages"` - Services []*WebServiceConfig `json:"services"` - ProductConfiguration interface{} `json:"productConfiguration"` - ProductInfo *ProductInfo `json:"productInfo"` - DefaultNavigatorSettings *NavigatorSettings `json:"defaultNavigatorSettings"` - DisabledDrivers []string `json:"disabledDrivers"` - ResourceQuotas interface{} `json:"resourceQuotas"` +type SecretInfo struct { + DisplayName string `json:"displayName"` + SecretID string `json:"secretId"` } -type ServerConfigInput struct { - ServerName *string `json:"serverName"` - ServerURL *string `json:"serverURL"` - AdminName *string `json:"adminName"` - AdminPassword *string `json:"adminPassword"` - AnonymousAccessEnabled *bool `json:"anonymousAccessEnabled"` - AuthenticationEnabled *bool `json:"authenticationEnabled"` - CustomConnectionsEnabled *bool `json:"customConnectionsEnabled"` - PublicCredentialsSaveEnabled *bool `json:"publicCredentialsSaveEnabled"` - AdminCredentialsSaveEnabled *bool `json:"adminCredentialsSaveEnabled"` - ResourceManagerEnabled *bool `json:"resourceManagerEnabled"` - EnabledFeatures []string `json:"enabledFeatures"` - EnabledAuthProviders []string `json:"enabledAuthProviders"` - DisabledDrivers []string `json:"disabledDrivers"` - SessionExpireTime *int `json:"sessionExpireTime"` +// Server configuration +type ServerConfig struct { + // Server name + Name string `json:"name"` + // Version of the server + Version string `json:"version"` + // ID of the server workspace + WorkspaceID string `json:"workspaceId"` + // Defines if the anonymous access is enabled + AnonymousAccessEnabled bool `json:"anonymousAccessEnabled"` + // Defines if non-admin users can create connections + SupportsCustomConnections bool `json:"supportsCustomConnections"` + // Defines if resource manager is enabled + ResourceManagerEnabled bool `json:"resourceManagerEnabled"` + // Defines if secret manager is enabled + SecretManagerEnabled bool `json:"secretManagerEnabled"` + // Defines is it is possible to save user database credentials + PublicCredentialsSaveEnabled bool `json:"publicCredentialsSaveEnabled"` + // Defines is it is possible to save global database credentials + AdminCredentialsSaveEnabled bool `json:"adminCredentialsSaveEnabled"` + // Defines if the server requires a license + LicenseRequired bool `json:"licenseRequired"` + // Defines if the server license is valid + LicenseValid bool `json:"licenseValid"` + // Returns information about the server license status + LicenseStatus *string `json:"licenseStatus,omitempty"` + // Defines if the server is in configuration mode + ConfigurationMode bool `json:"configurationMode"` + // Defines if the server is in development mode + DevelopmentMode bool `json:"developmentMode"` + // Defines if the server is distributed + Distributed bool `json:"distributed"` + // List of enabled features + EnabledFeatures []string `json:"enabledFeatures"` + // List of disabled beta features + DisabledBetaFeatures []string `json:"disabledBetaFeatures,omitempty"` + // List of server features + ServerFeatures []string `json:"serverFeatures,omitempty"` + // List of supported languages + SupportedLanguages []*ServerLanguage `json:"supportedLanguages"` + // Product configuration + ProductConfiguration any `json:"productConfiguration"` + // Product information + ProductInfo *ProductInfo `json:"productInfo"` + // Navigator settings for the server + DefaultNavigatorSettings *NavigatorSettings `json:"defaultNavigatorSettings"` + // List of disabled drivers (IDs of DriverInfo) + DisabledDrivers []string `json:"disabledDrivers"` + // Resource quotas (e.g., max amount of running SQL queries) + ResourceQuotas any `json:"resourceQuotas"` } +type ServerConfigInput struct { + ServerName *string `json:"serverName,omitempty"` + ServerURL *string `json:"serverURL,omitempty"` + AdminName *string `json:"adminName,omitempty"` + AdminPassword *string `json:"adminPassword,omitempty"` + AnonymousAccessEnabled *bool `json:"anonymousAccessEnabled,omitempty"` + AuthenticationEnabled *bool `json:"authenticationEnabled,omitempty"` + CustomConnectionsEnabled *bool `json:"customConnectionsEnabled,omitempty"` + PublicCredentialsSaveEnabled *bool `json:"publicCredentialsSaveEnabled,omitempty"` + AdminCredentialsSaveEnabled *bool `json:"adminCredentialsSaveEnabled,omitempty"` + ResourceManagerEnabled *bool `json:"resourceManagerEnabled,omitempty"` + SecretManagerEnabled *bool `json:"secretManagerEnabled,omitempty"` + EnabledFeatures []string `json:"enabledFeatures,omitempty"` + EnabledAuthProviders []string `json:"enabledAuthProviders,omitempty"` + DisabledDrivers []string `json:"disabledDrivers,omitempty"` + SessionExpireTime *int `json:"sessionExpireTime,omitempty"` + ForceHTTPS *bool `json:"forceHttps,omitempty"` + SupportedHosts []string `json:"supportedHosts,omitempty"` + BindSessionToIP *string `json:"bindSessionToIp,omitempty"` +} + +// Various server errors descriptor type ServerError struct { - Message *string `json:"message"` - ErrorCode *string `json:"errorCode"` - ErrorType *string `json:"errorType"` - StackTrace *string `json:"stackTrace"` - CausedBy *ServerError `json:"causedBy"` -} - + // Error message text + Message *string `json:"message,omitempty"` + // Retrieves the vendor-specific error code + ErrorCode *string `json:"errorCode,omitempty"` + // Type/category of the error + ErrorType *string `json:"errorType,omitempty"` + // Stack trace for debugging + StackTrace *string `json:"stackTrace,omitempty"` + // Nested error that caused this error (recursive) + CausedBy *ServerError `json:"causedBy,omitempty"` + // TODO 临时使用,后续需要删除 + ExecutionFailedMessage *string `json:"executionFailedMessage,omitempty"` +} + +// Languages supported by server type ServerLanguage struct { - IsoCode string `json:"isoCode"` - DisplayName *string `json:"displayName"` - NativeName *string `json:"nativeName"` + // ISO 639-1 or similar language code (e.g., "en", "ru") + IsoCode string `json:"isoCode"` + // Display name of the language in the current locale (e.g., "English") + DisplayName *string `json:"displayName,omitempty"` + // Native name of the language (e.g., "English", "Русский") + NativeName *string `json:"nativeName,omitempty"` } type ServerMessage struct { - Time *string `json:"time"` - Message *string `json:"message"` + // The time when the server message was created + Time *string `json:"time,omitempty"` + // The content of the message + Message *string `json:"message,omitempty"` } type SessionInfo struct { - CreateTime string `json:"createTime"` - LastAccessTime string `json:"lastAccessTime"` - Locale string `json:"locale"` - CacheExpired bool `json:"cacheExpired"` - ServerMessages []*ServerMessage `json:"serverMessages"` - Connections []*ConnectionInfo `json:"connections"` - ActionParameters interface{} `json:"actionParameters"` + // The time when the session was created + CreateTime string `json:"createTime"` + // The last time the session was accessed + LastAccessTime string `json:"lastAccessTime"` + // The current locale of the session + Locale string `json:"locale"` + // Indicates whether the session cache has expired + CacheExpired bool `json:"cacheExpired"` + // List of active connections in the session + Connections []*ConnectionInfo `json:"connections"` + // Action parameters for the session (e.g., opening a connection) + ActionParameters any `json:"actionParameters,omitempty"` + // Indicates if the session is valid + Valid bool `json:"valid"` + // Remaining time before the session expires (in seconds) + RemainingTime int `json:"remainingTime"` +} + +type TransactionLogInfoItem struct { + ID int `json:"id"` + Time time.Time `json:"time"` + Type string `json:"type"` + QueryString string `json:"queryString"` + DurationMs int `json:"durationMs"` + Rows int `json:"rows"` + Result string `json:"result"` +} + +type TransactionLogInfos struct { + Count int `json:"count"` + TransactionLogInfos []*TransactionLogInfoItem `json:"transactionLogInfos"` } type UserAuthToken struct { - AuthProvider string `json:"authProvider"` - AuthConfiguration *string `json:"authConfiguration"` - LoginTime time.Time `json:"loginTime"` - UserID string `json:"userId"` - DisplayName string `json:"displayName"` - Message *string `json:"message"` - Origin *ObjectOrigin `json:"origin"` + // Auth provider used for authorization + AuthProvider string `json:"authProvider"` + // Auth provider configuration ID + AuthConfiguration *string `json:"authConfiguration,omitempty"` + // Authorization time + LoginTime time.Time `json:"loginTime"` + // User identity (aka user name) specific to auth provider + UserID string `json:"userId"` + // User display name specific to auth provider + DisplayName string `json:"displayName"` + // Optional login message + Message *string `json:"message,omitempty"` + // Auth origin + Origin *ObjectOrigin `json:"origin"` } type UserInfo struct { - UserID string `json:"userId"` - DisplayName *string `json:"displayName"` - AuthTokens []*UserAuthToken `json:"authTokens"` - LinkedAuthProviders []string `json:"linkedAuthProviders"` - MetaParameters interface{} `json:"metaParameters"` - ConfigurationParameters interface{} `json:"configurationParameters"` + // User unique identifier + UserID string `json:"userId"` + // Human readable display name. It is taken from the first auth provider which was used for user login. + DisplayName *string `json:"displayName,omitempty"` + // User auth role ID. Optional. + AuthRole *string `json:"authRole,omitempty"` + // All authentication tokens used during current session + AuthTokens []*UserAuthToken `json:"authTokens"` + LinkedAuthProviders []string `json:"linkedAuthProviders"` + // User profile properties map + MetaParameters any `json:"metaParameters"` + // User configuration parameters + ConfigurationParameters any `json:"configurationParameters"` + // User teams + Teams []*UserTeamInfo `json:"teams"` + // Indicates whether the user is anonymous (not authenticated). + IsAnonymous bool `json:"isAnonymous"` +} + +type UserTeamInfo struct { + TeamID string `json:"teamId"` + TeamName string `json:"teamName"` + TeamRole *string `json:"teamRole,omitempty"` } type WebFeatureSet struct { ID string `json:"id"` Label string `json:"label"` - Description *string `json:"description"` - Icon *string `json:"icon"` + Description *string `json:"description,omitempty"` + Icon *string `json:"icon,omitempty"` Enabled bool `json:"enabled"` } -type WebServiceConfig struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - BundleVersion string `json:"bundleVersion"` -} - type AdminSubjectType string const ( AdminSubjectTypeUser AdminSubjectType = "user" - AdminSubjectTypeRole AdminSubjectType = "role" + AdminSubjectTypeTeam AdminSubjectType = "team" ) var AllAdminSubjectType = []AdminSubjectType{ AdminSubjectTypeUser, - AdminSubjectTypeRole, + AdminSubjectTypeTeam, } func (e AdminSubjectType) IsValid() bool { switch e { - case AdminSubjectTypeUser, AdminSubjectTypeRole: + case AdminSubjectTypeUser, AdminSubjectTypeTeam: return true } return false @@ -710,7 +1257,7 @@ func (e AdminSubjectType) String() string { return string(e) } -func (e *AdminSubjectType) UnmarshalGQL(v interface{}) error { +func (e *AdminSubjectType) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -727,6 +1274,20 @@ func (e AdminSubjectType) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } +func (e *AdminSubjectType) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e AdminSubjectType) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + type AuthCredentialEncryption string const ( @@ -753,7 +1314,7 @@ func (e AuthCredentialEncryption) String() string { return string(e) } -func (e *AuthCredentialEncryption) UnmarshalGQL(v interface{}) error { +func (e *AuthCredentialEncryption) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -770,6 +1331,20 @@ func (e AuthCredentialEncryption) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } +func (e *AuthCredentialEncryption) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e AuthCredentialEncryption) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + type AuthStatus string const ( @@ -796,7 +1371,7 @@ func (e AuthStatus) String() string { return string(e) } -func (e *AuthStatus) UnmarshalGQL(v interface{}) error { +func (e *AuthStatus) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -813,6 +1388,135 @@ func (e AuthStatus) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } +func (e *AuthStatus) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e AuthStatus) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + +type ConditionType string + +const ( + // hiding property condition + ConditionTypeHide ConditionType = "HIDE" + // restriction for setting a property value + ConditionTypeReadOnly ConditionType = "READ_ONLY" +) + +var AllConditionType = []ConditionType{ + ConditionTypeHide, + ConditionTypeReadOnly, +} + +func (e ConditionType) IsValid() bool { + switch e { + case ConditionTypeHide, ConditionTypeReadOnly: + return true + } + return false +} + +func (e ConditionType) String() string { + return string(e) +} + +func (e *ConditionType) UnmarshalGQL(v any) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("enums must be strings") + } + + *e = ConditionType(str) + if !e.IsValid() { + return fmt.Errorf("%s is not a valid ConditionType", str) + } + return nil +} + +func (e ConditionType) MarshalGQL(w io.Writer) { + fmt.Fprint(w, strconv.Quote(e.String())) +} + +func (e *ConditionType) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e ConditionType) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + +type DriverConfigurationType string + +const ( + // Driver uses host, port, database and server name fields + DriverConfigurationTypeManual DriverConfigurationType = "MANUAL" + // Driver uses URL field + DriverConfigurationTypeURL DriverConfigurationType = "URL" +) + +var AllDriverConfigurationType = []DriverConfigurationType{ + DriverConfigurationTypeManual, + DriverConfigurationTypeURL, +} + +func (e DriverConfigurationType) IsValid() bool { + switch e { + case DriverConfigurationTypeManual, DriverConfigurationTypeURL: + return true + } + return false +} + +func (e DriverConfigurationType) String() string { + return string(e) +} + +func (e *DriverConfigurationType) UnmarshalGQL(v any) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("enums must be strings") + } + + *e = DriverConfigurationType(str) + if !e.IsValid() { + return fmt.Errorf("%s is not a valid DriverConfigurationType", str) + } + return nil +} + +func (e DriverConfigurationType) MarshalGQL(w io.Writer) { + fmt.Fprint(w, strconv.Quote(e.String())) +} + +func (e *DriverConfigurationType) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e DriverConfigurationType) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + +// SSH network handler authentication type type NetworkHandlerAuthType string const ( @@ -839,7 +1543,7 @@ func (e NetworkHandlerAuthType) String() string { return string(e) } -func (e *NetworkHandlerAuthType) UnmarshalGQL(v interface{}) error { +func (e *NetworkHandlerAuthType) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -856,6 +1560,20 @@ func (e NetworkHandlerAuthType) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } +func (e *NetworkHandlerAuthType) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e NetworkHandlerAuthType) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + type NetworkHandlerType string const ( @@ -882,7 +1600,7 @@ func (e NetworkHandlerType) String() string { return string(e) } -func (e *NetworkHandlerType) UnmarshalGQL(v interface{}) error { +func (e *NetworkHandlerType) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -899,13 +1617,32 @@ func (e NetworkHandlerType) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } +func (e *NetworkHandlerType) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e NetworkHandlerType) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + type ObjectPropertyLength string const ( - ObjectPropertyLengthTiny ObjectPropertyLength = "TINY" - ObjectPropertyLengthShort ObjectPropertyLength = "SHORT" - ObjectPropertyLengthMedium ObjectPropertyLength = "MEDIUM" - ObjectPropertyLengthLong ObjectPropertyLength = "LONG" + // 1 character + ObjectPropertyLengthTiny ObjectPropertyLength = "TINY" + // 20 characters + ObjectPropertyLengthShort ObjectPropertyLength = "SHORT" + // <= 64 characters + ObjectPropertyLengthMedium ObjectPropertyLength = "MEDIUM" + // Full line length. The default + ObjectPropertyLengthLong ObjectPropertyLength = "LONG" + // Multi-line long text ObjectPropertyLengthMultiline ObjectPropertyLength = "MULTILINE" ) @@ -929,7 +1666,7 @@ func (e ObjectPropertyLength) String() string { return string(e) } -func (e *ObjectPropertyLength) UnmarshalGQL(v interface{}) error { +func (e *ObjectPropertyLength) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -946,6 +1683,20 @@ func (e ObjectPropertyLength) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } +func (e *ObjectPropertyLength) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e ObjectPropertyLength) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} + type ResultDataFormat string const ( @@ -974,7 +1725,7 @@ func (e ResultDataFormat) String() string { return string(e) } -func (e *ResultDataFormat) UnmarshalGQL(v interface{}) error { +func (e *ResultDataFormat) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -990,3 +1741,17 @@ func (e *ResultDataFormat) UnmarshalGQL(v interface{}) error { func (e ResultDataFormat) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } + +func (e *ResultDataFormat) UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) +} + +func (e ResultDataFormat) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil +} diff --git a/internal/pkg/cloudbeaver/resolver/executor_gen.go b/internal/pkg/cloudbeaver/resolver/executor_gen.go index 8b84e6d84..1d3b1543b 100644 --- a/internal/pkg/cloudbeaver/resolver/executor_gen.go +++ b/internal/pkg/cloudbeaver/resolver/executor_gen.go @@ -3,7 +3,6 @@ package resolver import ( - "github.com/actiontech/dms/internal/pkg/cloudbeaver/model" "bytes" "context" "errors" @@ -15,6 +14,7 @@ import ( "github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/graphql/introspection" + "github.com/actiontech/dms/internal/pkg/cloudbeaver/model" gqlparser "github.com/vektah/gqlparser/v2" "github.com/vektah/gqlparser/v2/ast" ) @@ -24,6 +24,7 @@ import ( // NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { return &executableSchema{ + schema: cfg.Schema, resolvers: cfg.Resolvers, directives: cfg.Directives, complexity: cfg.Complexity, @@ -31,6 +32,7 @@ func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { } type Config struct { + Schema *ast.Schema Resolvers ResolverRoot Directives DirectiveRoot Complexity ComplexityRoot @@ -42,13 +44,16 @@ type ResolverRoot interface { } type DirectiveRoot struct { + Since func(ctx context.Context, obj any, next graphql.Resolver, version string) (res any, err error) } type ComplexityRoot struct { AdminAuthProviderConfiguration struct { + AcsLink func(childComplexity int) int Description func(childComplexity int) int Disabled func(childComplexity int) int DisplayName func(childComplexity int) int + EntityIDLink func(childComplexity int) int ID func(childComplexity int) int IconURL func(childComplexity int) int MetadataLink func(childComplexity int) int @@ -74,6 +79,17 @@ type ComplexityRoot struct { PossibleDrivers func(childComplexity int) int } + AdminObjectGrantInfo struct { + ObjectPermissions func(childComplexity int) int + SubjectID func(childComplexity int) int + SubjectType func(childComplexity int) int + } + + AdminObjectPermissions struct { + ObjectID func(childComplexity int) int + Permissions func(childComplexity int) int + } + AdminPermissionInfo struct { Category func(childComplexity int) int Description func(childComplexity int) int @@ -82,31 +98,41 @@ type ComplexityRoot struct { Provider func(childComplexity int) int } - AdminRoleInfo struct { + AdminTeamInfo struct { Description func(childComplexity int) int GrantedConnections func(childComplexity int) int GrantedUsers func(childComplexity int) int - RoleID func(childComplexity int) int - RoleName func(childComplexity int) int - RolePermissions func(childComplexity int) int + GrantedUsersInfo func(childComplexity int) int + MetaParameters func(childComplexity int) int + TeamID func(childComplexity int) int + TeamName func(childComplexity int) int + TeamPermissions func(childComplexity int) int } AdminUserInfo struct { + AuthRole func(childComplexity int) int ConfigurationParameters func(childComplexity int) int + DisableDate func(childComplexity int) int + DisableReason func(childComplexity int) int + DisabledBy func(childComplexity int) int Enabled func(childComplexity int) int GrantedConnections func(childComplexity int) int - GrantedRoles func(childComplexity int) int + GrantedTeams func(childComplexity int) int LinkedAuthProviders func(childComplexity int) int MetaParameters func(childComplexity int) int Origins func(childComplexity int) int UserID func(childComplexity int) int } + AdminUserTeamGrantInfo struct { + TeamRole func(childComplexity int) int + UserID func(childComplexity int) int + } + AsyncTaskInfo struct { Error func(childComplexity int) int ID func(childComplexity int) int Name func(childComplexity int) int - Result func(childComplexity int) int Running func(childComplexity int) int Status func(childComplexity int) int TaskResult func(childComplexity int) int @@ -131,14 +157,18 @@ type ComplexityRoot struct { } AuthProviderConfiguration struct { - Description func(childComplexity int) int - Disabled func(childComplexity int) int - DisplayName func(childComplexity int) int - ID func(childComplexity int) int - IconURL func(childComplexity int) int - MetadataLink func(childComplexity int) int - SignInLink func(childComplexity int) int - SignOutLink func(childComplexity int) int + AcsLink func(childComplexity int) int + AuthRoleProvided func(childComplexity int) int + Description func(childComplexity int) int + Disabled func(childComplexity int) int + DisplayName func(childComplexity int) int + EntityIDLink func(childComplexity int) int + ID func(childComplexity int) int + IconURL func(childComplexity int) int + MetadataLink func(childComplexity int) int + RedirectLink func(childComplexity int) int + SignInLink func(childComplexity int) int + SignOutLink func(childComplexity int) int } AuthProviderCredentialsProfile struct { @@ -149,56 +179,96 @@ type ComplexityRoot struct { } AuthProviderInfo struct { - Configurable func(childComplexity int) int - Configurations func(childComplexity int) int - CredentialProfiles func(childComplexity int) int - DefaultProvider func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Icon func(childComplexity int) int - Label func(childComplexity int) int - RequiredFeatures func(childComplexity int) int + AuthHidden func(childComplexity int) int + Configurable func(childComplexity int) int + Configurations func(childComplexity int) int + CredentialProfiles func(childComplexity int) int + DefaultProvider func(childComplexity int) int + Description func(childComplexity int) int + Federated func(childComplexity int) int + ID func(childComplexity int) int + Icon func(childComplexity int) int + Label func(childComplexity int) int + Private func(childComplexity int) int + Required func(childComplexity int) int + RequiredFeatures func(childComplexity int) int + SupportProvisioning func(childComplexity int) int + TemplateConfiguration func(childComplexity int) int + Trusted func(childComplexity int) int + } + + Condition struct { + ConditionType func(childComplexity int) int + Expression func(childComplexity int) int } ConnectionFolderInfo struct { Description func(childComplexity int) int ID func(childComplexity int) int + ProjectID func(childComplexity int) int } ConnectionInfo struct { AuthModel func(childComplexity int) int AuthNeeded func(childComplexity int) int AuthProperties func(childComplexity int) int + Autocommit func(childComplexity int) int + CanDelete func(childComplexity int) int + CanEdit func(childComplexity int) int + CanViewSettings func(childComplexity int) int ClientVersion func(childComplexity int) int + ConfigurationType func(childComplexity int) int ConnectTime func(childComplexity int) int Connected func(childComplexity int) int ConnectionError func(childComplexity int) int + CredentialsSaved func(childComplexity int) int DatabaseName func(childComplexity int) int + DefaultCatalogName func(childComplexity int) int + DefaultSchemaName func(childComplexity int) int Description func(childComplexity int) int DriverID func(childComplexity int) int + ExpertSettingsValues func(childComplexity int) int Features func(childComplexity int) int Folder func(childComplexity int) int Host func(childComplexity int) int ID func(childComplexity int) int + KeepAliveInterval func(childComplexity int) int + MainPropertyValues func(childComplexity int) int Name func(childComplexity int) int NavigatorSettings func(childComplexity int) int NetworkHandlersConfig func(childComplexity int) int NodePath func(childComplexity int) int Origin func(childComplexity int) int Port func(childComplexity int) int + ProjectID func(childComplexity int) int Properties func(childComplexity int) int Provided func(childComplexity int) int ProviderProperties func(childComplexity int) int ReadOnly func(childComplexity int) int + RequiredAuth func(childComplexity int) int SaveCredentials func(childComplexity int) int ServerName func(childComplexity int) int ServerVersion func(childComplexity int) int + SharedCredentials func(childComplexity int) int + SharedSecrets func(childComplexity int) int SupportedDataFormats func(childComplexity int) int - Template func(childComplexity int) int + Tools func(childComplexity int) int URL func(childComplexity int) int UseURL func(childComplexity int) int } + DataTransferDefaultExportSettings struct { + OutputSettings func(childComplexity int) int + SupportedEncodings func(childComplexity int) int + } + + DataTransferOutputSettings struct { + Compress func(childComplexity int) int + Encoding func(childComplexity int) int + InsertBom func(childComplexity int) int + TimestampPattern func(childComplexity int) int + } + DataTransferProcessorInfo struct { AppFileExtension func(childComplexity int) int AppName func(childComplexity int) int @@ -225,6 +295,7 @@ type ComplexityRoot struct { ID func(childComplexity int) int Icon func(childComplexity int) int Properties func(childComplexity int) int + RequiredAuth func(childComplexity int) int RequiresLocalConfiguration func(childComplexity int) int } @@ -256,16 +327,23 @@ type ComplexityRoot struct { DatabaseStructContainers struct { CatalogList func(childComplexity int) int + ParentNode func(childComplexity int) int SchemaList func(childComplexity int) int SupportsCatalogChange func(childComplexity int) int SupportsSchemaChange func(childComplexity int) int } + DriverFileInfo struct { + FileName func(childComplexity int) int + ID func(childComplexity int) int + Icon func(childComplexity int) int + } + DriverInfo struct { - AllowsEmptyPassword func(childComplexity int) int AnonymousAccess func(childComplexity int) int ApplicableAuthModels func(childComplexity int) int ApplicableNetworkHandlers func(childComplexity int) int + ConfigurationTypes func(childComplexity int) int Custom func(childComplexity int) int DefaultAuthModel func(childComplexity int) int DefaultDatabase func(childComplexity int) int @@ -274,24 +352,55 @@ type ComplexityRoot struct { DefaultServer func(childComplexity int) int DefaultUser func(childComplexity int) int Description func(childComplexity int) int + Downloadable func(childComplexity int) int DriverClassName func(childComplexity int) int + DriverID func(childComplexity int) int DriverInfoURL func(childComplexity int) int + DriverInstalled func(childComplexity int) int + DriverLibraries func(childComplexity int) int DriverParameters func(childComplexity int) int DriverProperties func(childComplexity int) int DriverPropertiesURL func(childComplexity int) int Embedded func(childComplexity int) int Enabled func(childComplexity int) int + ExpertSettingsProperties func(childComplexity int) int ID func(childComplexity int) int Icon func(childComplexity int) int IconBig func(childComplexity int) int License func(childComplexity int) int LicenseRequired func(childComplexity int) int + MainProperties func(childComplexity int) int Name func(childComplexity int) int PromotedScore func(childComplexity int) int ProviderID func(childComplexity int) int ProviderProperties func(childComplexity int) int + RequiresDatabaseName func(childComplexity int) int RequiresServerName func(childComplexity int) int + SafeEmbeddedDriver func(childComplexity int) int SampleURL func(childComplexity int) int + UseCustomPage func(childComplexity int) int + } + + DriverLibraryInfo struct { + ID func(childComplexity int) int + Icon func(childComplexity int) int + LibraryFiles func(childComplexity int) int + Name func(childComplexity int) int + } + + DynamicTraceProperty struct { + Description func(childComplexity int) int + Name func(childComplexity int) int + Value func(childComplexity int) int + } + + FederatedAuthInfo struct { + RedirectLink func(childComplexity int) int + TaskInfo func(childComplexity int) int + } + + FederatedAuthResult struct { + UserTokens func(childComplexity int) int } LogEntry struct { @@ -301,53 +410,84 @@ type ComplexityRoot struct { Type func(childComplexity int) int } + LogoutInfo struct { + RedirectLinks func(childComplexity int) int + } + Mutation struct { - AsyncReadDataFromContainer func(childComplexity int, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) int - AsyncSQLExecuteQuery func(childComplexity int, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) int + AdminUpdateProductConfiguration func(childComplexity int, configuration any) int + AsyncReadDataFromContainer func(childComplexity int, projectID *string, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) int + AsyncSQLCommitTransaction func(childComplexity int, projectID string, connectionID string, contextID string) int + AsyncSQLExecuteQuery func(childComplexity int, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) int AsyncSQLExecuteResults func(childComplexity int, taskID string) int - AsyncSQLExplainExecutionPlan func(childComplexity int, connectionID string, contextID string, query string, configuration interface{}) int + AsyncSQLExplainExecutionPlan func(childComplexity int, projectID *string, connectionID string, contextID string, query string, configuration any) int AsyncSQLExplainExecutionPlanResult func(childComplexity int, taskID string) int + AsyncSQLRollbackTransaction func(childComplexity int, projectID string, connectionID string, contextID string) int + AsyncSQLRowDataCount func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string) int + AsyncSQLRowDataCountResult func(childComplexity int, taskID string) int + AsyncSQLSetAutoCommit func(childComplexity int, projectID string, connectionID string, contextID string, autoCommit bool) int AsyncTaskCancel func(childComplexity int, id string) int AsyncTaskInfo func(childComplexity int, id string, removeOnFinish bool) int - AsyncTaskStatus func(childComplexity int, id string) int + AsyncUpdateResultsDataBatch func(childComplexity int, projectID string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) int ChangeSessionLanguage func(childComplexity int, locale *string) int - CloseConnection func(childComplexity int, id string) int + CloseConnection func(childComplexity int, id string, projectID *string) int CloseSession func(childComplexity int) int - CopyConnectionFromNode func(childComplexity int, nodePath string, config *model.ConnectionConfig) int - CreateConnection func(childComplexity int, config model.ConnectionConfig) int - CreateConnectionFolder func(childComplexity int, parentFolderPath *string, folderName string) int - CreateConnectionFromTemplate func(childComplexity int, templateID string, connectionName *string) int - DeleteConnection func(childComplexity int, id string) int - DeleteConnectionFolder func(childComplexity int, folderPath string) int - InitConnection func(childComplexity int, id string, credentials interface{}, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool) int + CopyConnectionFromNode func(childComplexity int, nodePath string, config *model.ConnectionConfig, projectID *string) int + CreateConnection func(childComplexity int, config model.ConnectionConfig, projectID *string) int + CreateConnectionFolder func(childComplexity int, parentFolderPath *string, folderName string, projectID *string) int + DeleteConnection func(childComplexity int, id string, projectID *string) int + DeleteConnectionFolder func(childComplexity int, folderPath string, projectID *string) int + FederatedLogin func(childComplexity int, provider string, configuration *string, linkUser *bool, forceSessionsLogout *bool) int + GetTransactionLogInfo func(childComplexity int, projectID string, connectionID string, contextID string) int + InitConnection func(childComplexity int, id string, projectID *string, credentials any, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool, sharedCredentials *bool, selectedSecretID *string) int NavDeleteNodes func(childComplexity int, nodePaths []string) int NavMoveNodesToFolder func(childComplexity int, nodePaths []string, folderPath string) int + NavReloadNode func(childComplexity int, nodePath string) int NavRenameNode func(childComplexity int, nodePath string, newName string) int - OpenConnection func(childComplexity int, config model.ConnectionConfig) int + NavSetFolderFilter func(childComplexity int, nodePath string, include []string, exclude []string) int OpenSession func(childComplexity int, defaultLocale *string) int - ReadLobValue func(childComplexity int, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) int + ReadLobValue func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) int RefreshSessionConnections func(childComplexity int) int + RmAddProjectsPermissions func(childComplexity int, projectIds []string, subjectIds []string, permissions []string) int + RmCreateProject func(childComplexity int, projectID *string, projectName string, description *string) int RmCreateResource func(childComplexity int, projectID string, resourcePath string, isFolder bool) int + RmDeleteProject func(childComplexity int, projectID string) int + RmDeleteProjectsPermissions func(childComplexity int, projectIds []string, subjectIds []string, permissions []string) int RmDeleteResource func(childComplexity int, projectID string, resourcePath string, recursive bool) int RmMoveResource func(childComplexity int, projectID string, oldResourcePath string, newResourcePath *string) int - RmWriteResourceStringContent func(childComplexity int, projectID string, resourcePath string, data string) int - SQLContextCreate func(childComplexity int, connectionID string, defaultCatalog *string, defaultSchema *string) int - SQLContextDestroy func(childComplexity int, connectionID string, contextID string) int - SQLContextSetDefaults func(childComplexity int, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) int - SQLResultClose func(childComplexity int, connectionID string, contextID string, resultID string) int - SetConnectionNavigatorSettings func(childComplexity int, id string, settings model.NavigatorSettingsInput) int - SetUserConfigurationParameter func(childComplexity int, name string, value interface{}) int - TestConnection func(childComplexity int, config model.ConnectionConfig) int + RmSetProjectPermissions func(childComplexity int, projectID string, permissions []*model.RMSubjectProjectPermissions) int + RmSetResourceProperty func(childComplexity int, projectID string, resourcePath string, name string, value *string) int + RmSetSubjectProjectPermissions func(childComplexity int, subjectID string, permissions []*model.RMProjectPermissions) int + RmWriteResourceStringContent func(childComplexity int, projectID string, resourcePath string, data string, forceOverwrite bool) int + SQLContextCreate func(childComplexity int, projectID *string, connectionID string, defaultCatalog *string, defaultSchema *string) int + SQLContextDestroy func(childComplexity int, projectID *string, connectionID string, contextID string) int + SQLContextSetDefaults func(childComplexity int, projectID *string, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) int + SQLGetDynamicTrace func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string) int + SQLReadLobValue func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string, lobColumnIndex int, row model.SQLResultRow) int + SQLReadStringValue func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string, columnIndex int, row model.SQLResultRow) int + SQLResultClose func(childComplexity int, projectID *string, connectionID string, contextID string, resultID string) int + SetConnectionNavigatorSettings func(childComplexity int, id string, projectID *string, settings model.NavigatorSettingsInput) int + SetUserConfigurationParameter func(childComplexity int, name string, value any) int + SetUserPreferences func(childComplexity int, preferences any) int + TestConnection func(childComplexity int, config model.ConnectionConfig, projectID *string) int TestNetworkHandler func(childComplexity int, config model.NetworkHandlerConfigInput) int TouchSession func(childComplexity int) int - UpdateConnection func(childComplexity int, config model.ConnectionConfig) int - UpdateResultsDataBatch func(childComplexity int, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) int - UpdateResultsDataBatchScript func(childComplexity int, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) int + UpdateConnection func(childComplexity int, config model.ConnectionConfig, projectID *string) int + UpdateResultsDataBatch func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) int + UpdateResultsDataBatchScript func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) int + UpdateSession func(childComplexity int) int + } + + NavigatorNodeFilter struct { + Exclude func(childComplexity int) int + Include func(childComplexity int) int } NavigatorNodeInfo struct { Description func(childComplexity int) int Features func(childComplexity int) int + Filter func(childComplexity int) int + Filtered func(childComplexity int) int Folder func(childComplexity int) int FullName func(childComplexity int) int HasChildren func(childComplexity int) int @@ -359,6 +499,10 @@ type ComplexityRoot struct { NodeDetails func(childComplexity int) int NodeType func(childComplexity int) int Object func(childComplexity int) int + ObjectID func(childComplexity int) int + PlainName func(childComplexity int) int + ProjectID func(childComplexity int) int + URI func(childComplexity int) int } NavigatorSettings struct { @@ -378,14 +522,15 @@ type ComplexityRoot struct { } NetworkHandlerConfig struct { - AuthType func(childComplexity int) int - Enabled func(childComplexity int) int - ID func(childComplexity int) int - Key func(childComplexity int) int - Password func(childComplexity int) int - Properties func(childComplexity int) int - SavePassword func(childComplexity int) int - UserName func(childComplexity int) int + AuthType func(childComplexity int) int + Enabled func(childComplexity int) int + ID func(childComplexity int) int + Key func(childComplexity int) int + Password func(childComplexity int) int + Properties func(childComplexity int) int + SavePassword func(childComplexity int) int + SecureProperties func(childComplexity int) int + UserName func(childComplexity int) int } NetworkHandlerDescriptor struct { @@ -424,120 +569,185 @@ type ComplexityRoot struct { } ObjectPropertyInfo struct { - Category func(childComplexity int) int - DataType func(childComplexity int) int - DefaultValue func(childComplexity int) int - Description func(childComplexity int) int - DisplayName func(childComplexity int) int - Features func(childComplexity int) int - ID func(childComplexity int) int - Length func(childComplexity int) int - Order func(childComplexity int) int - ValidValues func(childComplexity int) int - Value func(childComplexity int) int + Category func(childComplexity int) int + Conditions func(childComplexity int) int + DataType func(childComplexity int) int + DefaultValue func(childComplexity int) int + Description func(childComplexity int) int + DisplayName func(childComplexity int) int + Features func(childComplexity int) int + Hint func(childComplexity int) int + ID func(childComplexity int) int + Length func(childComplexity int) int + Order func(childComplexity int) int + Required func(childComplexity int) int + Scopes func(childComplexity int) int + SupportedConfigurationTypes func(childComplexity int) int + ValidValues func(childComplexity int) int + Value func(childComplexity int) int + } + + PasswordPolicyConfig struct { + MinLength func(childComplexity int) int + MinNumberCount func(childComplexity int) int + MinSymbolCount func(childComplexity int) int + RequireMixedCase func(childComplexity int) int } ProductInfo struct { - BuildTime func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - LatestVersionInfo func(childComplexity int) int - LicenseInfo func(childComplexity int) int - Name func(childComplexity int) int - ReleaseTime func(childComplexity int) int - Version func(childComplexity int) int + BuildTime func(childComplexity int) int + Description func(childComplexity int) int + ID func(childComplexity int) int + LatestVersionInfo func(childComplexity int) int + LicenseInfo func(childComplexity int) int + Name func(childComplexity int) int + ProductPurchaseURL func(childComplexity int) int + ReleaseTime func(childComplexity int) int + Version func(childComplexity int) int + } + + ProductSettings struct { + Groups func(childComplexity int) int + Settings func(childComplexity int) int + } + + ProductSettingsGroup struct { + DisplayName func(childComplexity int) int + ID func(childComplexity int) int + } + + ProjectInfo struct { + CanEditDataSources func(childComplexity int) int + CanEditResources func(childComplexity int) int + CanViewDataSources func(childComplexity int) int + CanViewResources func(childComplexity int) int + Description func(childComplexity int) int + Global func(childComplexity int) int + ID func(childComplexity int) int + Name func(childComplexity int) int + ResourceTypes func(childComplexity int) int + Shared func(childComplexity int) int } Query struct { - ActiveUser func(childComplexity int) int - AllConnections func(childComplexity int, id *string) int - AuthChangeLocalPassword func(childComplexity int, oldPassword string, newPassword string) int - AuthLogin func(childComplexity int, provider string, configuration *string, credentials interface{}, linkUser *bool) int - AuthLogout func(childComplexity int, provider *string, configuration *string) int - AuthModels func(childComplexity int) int - AuthProviders func(childComplexity int) int - AuthUpdateStatus func(childComplexity int, authID string, linkUser *bool) int - ConfigureServer func(childComplexity int, configuration model.ServerConfigInput) int - ConnectionFolders func(childComplexity int, path *string) int - ConnectionInfo func(childComplexity int, id string) int - ConnectionState func(childComplexity int, id string) int - CopyConnectionConfiguration func(childComplexity int, nodePath string, config *model.ConnectionConfig) int - CreateConnectionConfiguration func(childComplexity int, config model.ConnectionConfig) int - CreateRole func(childComplexity int, roleID string, roleName *string, description *string) int - CreateUser func(childComplexity int, userID string) int - DataTransferAvailableStreamProcessors func(childComplexity int) int - DataTransferExportDataFromContainer func(childComplexity int, connectionID string, containerNodePath string, parameters model.DataTransferParameters) int - DataTransferExportDataFromResults func(childComplexity int, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) int - DataTransferRemoveDataFile func(childComplexity int, dataFileID string) int - DeleteAuthProviderConfiguration func(childComplexity int, id string) int - DeleteConnectionConfiguration func(childComplexity int, id string) int - DeleteRole func(childComplexity int, roleID string) int - DeleteUser func(childComplexity int, userID string) int - DeleteUserMetaParameter func(childComplexity int, id string) int - DriverList func(childComplexity int, id *string) int - EnableUser func(childComplexity int, userID string, enabled bool) int - GetConnectionSubjectAccess func(childComplexity int, connectionID *string) int - GetSubjectConnectionAccess func(childComplexity int, subjectID *string) int - GrantUserRole func(childComplexity int, userID string, roleID string) int - ListAuthProviderConfigurationParameters func(childComplexity int, providerID string) int - ListAuthProviderConfigurations func(childComplexity int, providerID *string) int - ListFeatureSets func(childComplexity int) int - ListPermissions func(childComplexity int) int - ListRoles func(childComplexity int, roleID *string) int - ListUserProfileProperties func(childComplexity int) int - ListUsers func(childComplexity int, userID *string) int - MetadataGetNodeDdl func(childComplexity int, nodeID string, options interface{}) int - NavGetStructContainers func(childComplexity int, connectionID string, contextID *string, catalog *string) int - NavNodeChildren func(childComplexity int, parentPath string, offset *int, limit *int, onlyFolders *bool) int - NavNodeInfo func(childComplexity int, nodePath string) int - NavNodeParents func(childComplexity int, nodePath string) int - NavRefreshNode func(childComplexity int, nodePath string) int - NetworkHandlers func(childComplexity int) int - ReadSessionLog func(childComplexity int, maxEntries *int, clearEntries *bool) int - RevokeUserRole func(childComplexity int, userID string, roleID string) int - RmListProjects func(childComplexity int) int - RmListResources func(childComplexity int, projectID string, folder *string, nameMask *string, readProperties *bool, readHistory *bool) int - RmReadResourceAsString func(childComplexity int, projectID string, resourcePath string) int - SQLCompletionProposals func(childComplexity int, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) int - SQLDialectInfo func(childComplexity int, connectionID string) int - SQLEntityQueryGenerators func(childComplexity int, nodePathList []string) int - SQLFormatQuery func(childComplexity int, connectionID string, contextID string, query string) int - SQLGenerateEntityQuery func(childComplexity int, generatorID string, options interface{}, nodePathList []string) int - SQLListContexts func(childComplexity int, connectionID *string, contextID *string) int - SQLParseQuery func(childComplexity int, connectionID string, script string, position int) int - SQLParseScript func(childComplexity int, connectionID string, script string) int - SQLSupportedOperations func(childComplexity int, connectionID string, contextID string, resultsID string, attributeIndex int) int - SaveAuthProviderConfiguration func(childComplexity int, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters interface{}) int - SaveUserMetaParameter func(childComplexity int, id string, displayName string, description *string, required bool) int - SearchConnections func(childComplexity int, hostNames []string) int - ServerConfig func(childComplexity int) int - SessionPermissions func(childComplexity int) int - SessionState func(childComplexity int) int - SetConnectionSubjectAccess func(childComplexity int, connectionID string, subjects []string) int - SetDefaultNavigatorSettings func(childComplexity int, settings model.NavigatorSettingsInput) int - SetSubjectConnectionAccess func(childComplexity int, subjectID string, connections []string) int - SetSubjectPermissions func(childComplexity int, roleID string, permissions []string) int - SetUserCredentials func(childComplexity int, userID string, providerID string, credentials interface{}) int - SetUserMetaParameterValues func(childComplexity int, userID string, parameters interface{}) int - TemplateConnections func(childComplexity int) int - UpdateConnectionConfiguration func(childComplexity int, id string, config model.ConnectionConfig) int - UpdateRole func(childComplexity int, roleID string, roleName *string, description *string) int - UserConnections func(childComplexity int, id *string) int + ActiveUser func(childComplexity int) int + AddConnectionsAccess func(childComplexity int, projectID string, connectionIds []string, subjects []string) int + AdminUserInfo func(childComplexity int, userID string) int + AuthChangeLocalPassword func(childComplexity int, oldPassword string, newPassword string) int + AuthLogin func(childComplexity int, provider string, configuration *string, credentials any, linkUser *bool, forceSessionsLogout *bool) int + AuthLogout func(childComplexity int, provider *string, configuration *string) int + AuthLogoutExtended func(childComplexity int, provider *string, configuration *string) int + AuthModels func(childComplexity int) int + AuthProviders func(childComplexity int) int + AuthUpdateStatus func(childComplexity int, authID string, linkUser *bool) int + ConfigureServer func(childComplexity int, configuration model.ServerConfigInput) int + ConnectionFolders func(childComplexity int, projectID *string, path *string) int + ConnectionInfo func(childComplexity int, projectID string, id string) int + CreateTeam func(childComplexity int, teamID string, teamName *string, description *string) int + CreateUser func(childComplexity int, userID string, enabled bool, authRole *string) int + DataTransferAvailableImportStreamProcessors func(childComplexity int) int + DataTransferAvailableStreamProcessors func(childComplexity int) int + DataTransferDefaultExportSettings func(childComplexity int) int + DataTransferExportDataFromContainer func(childComplexity int, projectID *string, connectionID string, containerNodePath string, parameters model.DataTransferParameters) int + DataTransferExportDataFromResults func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) int + DataTransferRemoveDataFile func(childComplexity int, dataFileID string) int + DeleteAuthProviderConfiguration func(childComplexity int, id string) int + DeleteConnectionsAccess func(childComplexity int, projectID string, connectionIds []string, subjects []string) int + DeleteTeam func(childComplexity int, teamID string, force *bool) int + DeleteUser func(childComplexity int, userID string) int + DeleteUserCredentials func(childComplexity int, userID string, providerID string) int + DeleteUserMetaParameter func(childComplexity int, id string) int + DriverList func(childComplexity int, id *string) int + EnableUser func(childComplexity int, userID string, enabled bool) int + FederatedAuthTaskResult func(childComplexity int, taskID string) int + GetConnectionSubjectAccess func(childComplexity int, projectID string, connectionID *string) int + GetSubjectConnectionAccess func(childComplexity int, subjectID string) int + GrantUserTeam func(childComplexity int, userID string, teamID string) int + ListAuthProviderConfigurationParameters func(childComplexity int, providerID string) int + ListAuthProviderConfigurations func(childComplexity int, providerID *string) int + ListAuthRoles func(childComplexity int) int + ListFeatureSets func(childComplexity int) int + ListPermissions func(childComplexity int) int + ListProjects func(childComplexity int) int + ListTeamMetaParameters func(childComplexity int) int + ListTeamRoles func(childComplexity int) int + ListTeams func(childComplexity int, teamID *string) int + ListUserProfileProperties func(childComplexity int) int + ListUsers func(childComplexity int, page model.PageInput, filter model.AdminUserFilterInput) int + MetadataGetNodeDdl func(childComplexity int, nodeID string, options any) int + MetadataGetNodeExtendedDdl func(childComplexity int, nodeID string) int + NavGetStructContainers func(childComplexity int, projectID *string, connectionID string, contextID *string, catalog *string) int + NavNodeChildren func(childComplexity int, parentPath string, offset *int, limit *int, onlyFolders *bool) int + NavNodeInfo func(childComplexity int, nodePath string) int + NavNodeParents func(childComplexity int, nodePath string) int + NavRefreshNode func(childComplexity int, nodePath string) int + NetworkHandlers func(childComplexity int) int + ProductSettings func(childComplexity int) int + ReadSessionLog func(childComplexity int, maxEntries *int, clearEntries *bool) int + RevokeUserTeam func(childComplexity int, userID string, teamID string) int + RmListProjectGrantedPermissions func(childComplexity int, projectID string) int + RmListProjectPermissions func(childComplexity int) int + RmListProjects func(childComplexity int) int + RmListResources func(childComplexity int, projectID string, folder *string, nameMask *string, readProperties *bool, readHistory *bool) int + RmListSharedProjects func(childComplexity int) int + RmListSubjectProjectsPermissionGrants func(childComplexity int, subjectID string) int + RmProject func(childComplexity int, projectID string) int + RmReadResourceAsString func(childComplexity int, projectID string, resourcePath string) int + SQLCompletionProposals func(childComplexity int, projectID *string, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) int + SQLDialectInfo func(childComplexity int, projectID *string, connectionID string) int + SQLEntityQueryGenerators func(childComplexity int, nodePathList []string) int + SQLFormatQuery func(childComplexity int, projectID *string, connectionID string, contextID string, query string) int + SQLGenerateEntityQuery func(childComplexity int, generatorID string, options any, nodePathList []string) int + SQLGenerateGroupingQuery func(childComplexity int, projectID *string, contextID string, connectionID string, resultsID string, columnNames []string, functions []string, showDuplicatesOnly *bool) int + SQLListContexts func(childComplexity int, projectID *string, connectionID *string, contextID *string) int + SQLParseQuery func(childComplexity int, projectID *string, connectionID string, script string, position int) int + SQLParseScript func(childComplexity int, projectID *string, connectionID string, script string) int + SQLSupportedOperations func(childComplexity int, projectID *string, connectionID string, contextID string, resultsID string, attributeIndex int) int + SaveAuthProviderConfiguration func(childComplexity int, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters any) int + SaveUserMetaParameter func(childComplexity int, id string, displayName string, description *string, required bool) int + SearchConnections func(childComplexity int, hostNames []string) int + ServerConfig func(childComplexity int) int + SessionPermissions func(childComplexity int) int + SessionState func(childComplexity int) int + SetConnectionSubjectAccess func(childComplexity int, projectID string, connectionID string, subjects []string) int + SetDefaultNavigatorSettings func(childComplexity int, settings model.NavigatorSettingsInput) int + SetSubjectConnectionAccess func(childComplexity int, subjectID string, connections []string) int + SetSubjectPermissions func(childComplexity int, subjectID string, permissions []string) int + SetTeamMetaParameterValues func(childComplexity int, teamID string, parameters any) int + SetUserAuthRole func(childComplexity int, userID string, authRole *string) int + SetUserCredentials func(childComplexity int, userID string, providerID string, credentials any) int + SetUserMetaParameterValues func(childComplexity int, userID string, parameters any) int + SetUserTeamRole func(childComplexity int, userID string, teamID string, teamRole *string) int + SystemInfo func(childComplexity int) int + UpdateTeam func(childComplexity int, teamID string, teamName *string, description *string) int + UserConnections func(childComplexity int, projectID *string, id *string, projectIds []string) int } RMProject struct { - CreateTime func(childComplexity int) int - Creator func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - Shared func(childComplexity int) int + CreateTime func(childComplexity int) int + Creator func(childComplexity int) int + Description func(childComplexity int) int + Global func(childComplexity int) int + ID func(childComplexity int) int + Name func(childComplexity int) int + ProjectPermissions func(childComplexity int) int + ResourceTypes func(childComplexity int) int + Shared func(childComplexity int) int } RMResource struct { - Folder func(childComplexity int) int - Length func(childComplexity int) int - Name func(childComplexity int) int + Folder func(childComplexity int) int + Length func(childComplexity int) int + Name func(childComplexity int) int + Properties func(childComplexity int) int + } + + RMResourceType struct { + DisplayName func(childComplexity int) int + FileExtensions func(childComplexity int) int + ID func(childComplexity int) int + Icon func(childComplexity int) int + RootFolder func(childComplexity int) int } SQLCompletionProposal struct { @@ -553,10 +763,12 @@ type ComplexityRoot struct { } SQLContextInfo struct { + AutoCommit func(childComplexity int) int ConnectionID func(childComplexity int) int DefaultCatalog func(childComplexity int) int DefaultSchema func(childComplexity int) int ID func(childComplexity int) int + ProjectID func(childComplexity int) int } SQLDialectInfo struct { @@ -576,6 +788,7 @@ type ComplexityRoot struct { SQLExecuteInfo struct { Duration func(childComplexity int) int FilterText func(childComplexity int) int + FullQuery func(childComplexity int) int Results func(childComplexity int) int StatusMessage func(childComplexity int) int } @@ -613,7 +826,9 @@ type ComplexityRoot struct { } SQLResultColumn struct { + AutoGenerated func(childComplexity int) int DataKind func(childComplexity int) int + Description func(childComplexity int) int EntityName func(childComplexity int) int FullTypeName func(childComplexity int) int Icon func(childComplexity int) int @@ -630,13 +845,24 @@ type ComplexityRoot struct { TypeName func(childComplexity int) int } + SQLResultRowMetaData struct { + Data func(childComplexity int) int + MetaData func(childComplexity int) int + } + SQLResultSet struct { - Columns func(childComplexity int) int - HasMoreData func(childComplexity int) int - HasRowIdentifier func(childComplexity int) int - ID func(childComplexity int) int - Rows func(childComplexity int) int - SingleEntity func(childComplexity int) int + Columns func(childComplexity int) int + HasChildrenCollection func(childComplexity int) int + HasDynamicTrace func(childComplexity int) int + HasMoreData func(childComplexity int) int + HasRowIdentifier func(childComplexity int) int + ID func(childComplexity int) int + IsSupportsDataFilter func(childComplexity int) int + ReadOnly func(childComplexity int) int + ReadOnlyStatus func(childComplexity int) int + Rows func(childComplexity int) int + RowsWithMetaData func(childComplexity int) int + SingleEntity func(childComplexity int) int } SQLScriptInfo struct { @@ -648,35 +874,34 @@ type ComplexityRoot struct { Start func(childComplexity int) int } + SecretInfo struct { + DisplayName func(childComplexity int) int + SecretID func(childComplexity int) int + } + ServerConfig struct { AdminCredentialsSaveEnabled func(childComplexity int) int AnonymousAccessEnabled func(childComplexity int) int - AuthenticationEnabled func(childComplexity int) int ConfigurationMode func(childComplexity int) int DefaultNavigatorSettings func(childComplexity int) int DevelopmentMode func(childComplexity int) int + DisabledBetaFeatures func(childComplexity int) int DisabledDrivers func(childComplexity int) int - EnabledAuthProviders func(childComplexity int) int + Distributed func(childComplexity int) int EnabledFeatures func(childComplexity int) int - HostName func(childComplexity int) int LicenseRequired func(childComplexity int) int + LicenseStatus func(childComplexity int) int LicenseValid func(childComplexity int) int - LocalHostAddress func(childComplexity int) int Name func(childComplexity int) int ProductConfiguration func(childComplexity int) int ProductInfo func(childComplexity int) int PublicCredentialsSaveEnabled func(childComplexity int) int - RedirectOnFederatedAuth func(childComplexity int) int ResourceManagerEnabled func(childComplexity int) int ResourceQuotas func(childComplexity int) int - RootURI func(childComplexity int) int - ServerURL func(childComplexity int) int - Services func(childComplexity int) int - SessionExpireTime func(childComplexity int) int + SecretManagerEnabled func(childComplexity int) int + ServerFeatures func(childComplexity int) int SupportedLanguages func(childComplexity int) int - SupportsConnectionBrowser func(childComplexity int) int SupportsCustomConnections func(childComplexity int) int - SupportsWorkspaces func(childComplexity int) int Version func(childComplexity int) int WorkspaceID func(childComplexity int) int } @@ -707,7 +932,23 @@ type ComplexityRoot struct { CreateTime func(childComplexity int) int LastAccessTime func(childComplexity int) int Locale func(childComplexity int) int - ServerMessages func(childComplexity int) int + RemainingTime func(childComplexity int) int + Valid func(childComplexity int) int + } + + TransactionLogInfoItem struct { + DurationMs func(childComplexity int) int + ID func(childComplexity int) int + QueryString func(childComplexity int) int + Result func(childComplexity int) int + Rows func(childComplexity int) int + Time func(childComplexity int) int + Type func(childComplexity int) int + } + + TransactionLogInfos struct { + Count func(childComplexity int) int + TransactionLogInfos func(childComplexity int) int } UserAuthToken struct { @@ -721,14 +962,23 @@ type ComplexityRoot struct { } UserInfo struct { + AuthRole func(childComplexity int) int AuthTokens func(childComplexity int) int ConfigurationParameters func(childComplexity int) int DisplayName func(childComplexity int) int + IsAnonymous func(childComplexity int) int LinkedAuthProviders func(childComplexity int) int MetaParameters func(childComplexity int) int + Teams func(childComplexity int) int UserID func(childComplexity int) int } + UserTeamInfo struct { + TeamID func(childComplexity int) int + TeamName func(childComplexity int) int + TeamRole func(childComplexity int) int + } + WebFeatureSet struct { Description func(childComplexity int) int Enabled func(childComplexity int) int @@ -736,220 +986,256 @@ type ComplexityRoot struct { Icon func(childComplexity int) int Label func(childComplexity int) int } - - WebServiceConfig struct { - BundleVersion func(childComplexity int) int - Description func(childComplexity int) int - ID func(childComplexity int) int - Name func(childComplexity int) int - } } type MutationResolver interface { - SetUserConfigurationParameter(ctx context.Context, name string, value interface{}) (bool, error) + AdminUpdateProductConfiguration(ctx context.Context, configuration any) (bool, error) + SetUserConfigurationParameter(ctx context.Context, name string, value any) (bool, error) + SetUserPreferences(ctx context.Context, preferences any) (*model.UserInfo, error) + FederatedLogin(ctx context.Context, provider string, configuration *string, linkUser *bool, forceSessionsLogout *bool) (*model.FederatedAuthInfo, error) OpenSession(ctx context.Context, defaultLocale *string) (*model.SessionInfo, error) CloseSession(ctx context.Context) (*bool, error) TouchSession(ctx context.Context) (*bool, error) + UpdateSession(ctx context.Context) (*model.SessionInfo, error) RefreshSessionConnections(ctx context.Context) (*bool, error) ChangeSessionLanguage(ctx context.Context, locale *string) (*bool, error) - CreateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - UpdateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - DeleteConnection(ctx context.Context, id string) (bool, error) - CreateConnectionFromTemplate(ctx context.Context, templateID string, connectionName *string) (*model.ConnectionInfo, error) - CreateConnectionFolder(ctx context.Context, parentFolderPath *string, folderName string) (*model.ConnectionFolderInfo, error) - DeleteConnectionFolder(ctx context.Context, folderPath string) (bool, error) - CopyConnectionFromNode(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) - TestConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) + CreateConnection(ctx context.Context, config model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) + UpdateConnection(ctx context.Context, config model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) + DeleteConnection(ctx context.Context, id string, projectID *string) (bool, error) + CreateConnectionFolder(ctx context.Context, parentFolderPath *string, folderName string, projectID *string) (*model.ConnectionFolderInfo, error) + DeleteConnectionFolder(ctx context.Context, folderPath string, projectID *string) (bool, error) + CopyConnectionFromNode(ctx context.Context, nodePath string, config *model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) + TestConnection(ctx context.Context, config model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) TestNetworkHandler(ctx context.Context, config model.NetworkHandlerConfigInput) (*model.NetworkEndpointInfo, error) - InitConnection(ctx context.Context, id string, credentials interface{}, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool) (*model.ConnectionInfo, error) - CloseConnection(ctx context.Context, id string) (*model.ConnectionInfo, error) - SetConnectionNavigatorSettings(ctx context.Context, id string, settings model.NavigatorSettingsInput) (*model.ConnectionInfo, error) + InitConnection(ctx context.Context, id string, projectID *string, credentials any, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool, sharedCredentials *bool, selectedSecretID *string) (*model.ConnectionInfo, error) + CloseConnection(ctx context.Context, id string, projectID *string) (*model.ConnectionInfo, error) + SetConnectionNavigatorSettings(ctx context.Context, id string, projectID *string, settings model.NavigatorSettingsInput) (*model.ConnectionInfo, error) AsyncTaskCancel(ctx context.Context, id string) (*bool, error) AsyncTaskInfo(ctx context.Context, id string, removeOnFinish bool) (*model.AsyncTaskInfo, error) - OpenConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - AsyncTaskStatus(ctx context.Context, id string) (*model.AsyncTaskInfo, error) + NavReloadNode(ctx context.Context, nodePath string) (*model.NavigatorNodeInfo, error) NavRenameNode(ctx context.Context, nodePath string, newName string) (*string, error) NavDeleteNodes(ctx context.Context, nodePaths []string) (*int, error) - NavMoveNodesToFolder(ctx context.Context, nodePaths []string, folderPath string) (*bool, error) + NavMoveNodesToFolder(ctx context.Context, nodePaths []string, folderPath string) (bool, error) + NavSetFolderFilter(ctx context.Context, nodePath string, include []string, exclude []string) (bool, error) RmCreateResource(ctx context.Context, projectID string, resourcePath string, isFolder bool) (string, error) RmMoveResource(ctx context.Context, projectID string, oldResourcePath string, newResourcePath *string) (string, error) RmDeleteResource(ctx context.Context, projectID string, resourcePath string, recursive bool) (*bool, error) - RmWriteResourceStringContent(ctx context.Context, projectID string, resourcePath string, data string) (string, error) - SQLContextCreate(ctx context.Context, connectionID string, defaultCatalog *string, defaultSchema *string) (*model.SQLContextInfo, error) - SQLContextSetDefaults(ctx context.Context, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) (bool, error) - SQLContextDestroy(ctx context.Context, connectionID string, contextID string) (bool, error) - AsyncSQLExecuteQuery(ctx context.Context, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) - AsyncReadDataFromContainer(ctx context.Context, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) - SQLResultClose(ctx context.Context, connectionID string, contextID string, resultID string) (bool, error) - UpdateResultsDataBatch(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.SQLExecuteInfo, error) - UpdateResultsDataBatchScript(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (string, error) - ReadLobValue(ctx context.Context, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) (string, error) + RmWriteResourceStringContent(ctx context.Context, projectID string, resourcePath string, data string, forceOverwrite bool) (string, error) + RmCreateProject(ctx context.Context, projectID *string, projectName string, description *string) (*model.RMProject, error) + RmDeleteProject(ctx context.Context, projectID string) (bool, error) + RmSetProjectPermissions(ctx context.Context, projectID string, permissions []*model.RMSubjectProjectPermissions) (bool, error) + RmSetSubjectProjectPermissions(ctx context.Context, subjectID string, permissions []*model.RMProjectPermissions) (bool, error) + RmAddProjectsPermissions(ctx context.Context, projectIds []string, subjectIds []string, permissions []string) (*bool, error) + RmDeleteProjectsPermissions(ctx context.Context, projectIds []string, subjectIds []string, permissions []string) (*bool, error) + RmSetResourceProperty(ctx context.Context, projectID string, resourcePath string, name string, value *string) (bool, error) + SQLContextCreate(ctx context.Context, projectID *string, connectionID string, defaultCatalog *string, defaultSchema *string) (*model.SQLContextInfo, error) + SQLContextSetDefaults(ctx context.Context, projectID *string, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) (bool, error) + SQLContextDestroy(ctx context.Context, projectID *string, connectionID string, contextID string) (bool, error) + AsyncSQLExecuteQuery(ctx context.Context, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) (*model.AsyncTaskInfo, error) + AsyncReadDataFromContainer(ctx context.Context, projectID *string, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) + GetTransactionLogInfo(ctx context.Context, projectID string, connectionID string, contextID string) (*model.TransactionLogInfos, error) + SQLResultClose(ctx context.Context, projectID *string, connectionID string, contextID string, resultID string) (bool, error) + AsyncUpdateResultsDataBatch(ctx context.Context, projectID string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.AsyncTaskInfo, error) + UpdateResultsDataBatch(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.SQLExecuteInfo, error) + UpdateResultsDataBatchScript(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (string, error) + ReadLobValue(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) (string, error) + SQLReadLobValue(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, lobColumnIndex int, row model.SQLResultRow) (string, error) + SQLReadStringValue(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, columnIndex int, row model.SQLResultRow) (string, error) AsyncSQLExecuteResults(ctx context.Context, taskID string) (*model.SQLExecuteInfo, error) - AsyncSQLExplainExecutionPlan(ctx context.Context, connectionID string, contextID string, query string, configuration interface{}) (*model.AsyncTaskInfo, error) + AsyncSQLExplainExecutionPlan(ctx context.Context, projectID *string, connectionID string, contextID string, query string, configuration any) (*model.AsyncTaskInfo, error) AsyncSQLExplainExecutionPlanResult(ctx context.Context, taskID string) (*model.SQLExecutionPlan, error) + AsyncSQLRowDataCount(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string) (*model.AsyncTaskInfo, error) + AsyncSQLRowDataCountResult(ctx context.Context, taskID string) (int, error) + SQLGetDynamicTrace(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string) ([]*model.DynamicTraceProperty, error) + AsyncSQLSetAutoCommit(ctx context.Context, projectID string, connectionID string, contextID string, autoCommit bool) (*model.AsyncTaskInfo, error) + AsyncSQLCommitTransaction(ctx context.Context, projectID string, connectionID string, contextID string) (*model.AsyncTaskInfo, error) + AsyncSQLRollbackTransaction(ctx context.Context, projectID string, connectionID string, contextID string) (*model.AsyncTaskInfo, error) } type QueryResolver interface { - ListUsers(ctx context.Context, userID *string) ([]*model.AdminUserInfo, error) - ListRoles(ctx context.Context, roleID *string) ([]*model.AdminRoleInfo, error) + AdminUserInfo(ctx context.Context, userID string) (*model.AdminUserInfo, error) + ListUsers(ctx context.Context, page model.PageInput, filter model.AdminUserFilterInput) ([]*model.AdminUserInfo, error) + ListTeams(ctx context.Context, teamID *string) ([]*model.AdminTeamInfo, error) ListPermissions(ctx context.Context) ([]*model.AdminPermissionInfo, error) - CreateUser(ctx context.Context, userID string) (*model.AdminUserInfo, error) + ListAuthRoles(ctx context.Context) ([]string, error) + ListTeamRoles(ctx context.Context) ([]string, error) + ListTeamMetaParameters(ctx context.Context) ([]*model.ObjectPropertyInfo, error) + CreateUser(ctx context.Context, userID string, enabled bool, authRole *string) (*model.AdminUserInfo, error) DeleteUser(ctx context.Context, userID string) (*bool, error) - CreateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) - UpdateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) - DeleteRole(ctx context.Context, roleID string) (*bool, error) - GrantUserRole(ctx context.Context, userID string, roleID string) (*bool, error) - RevokeUserRole(ctx context.Context, userID string, roleID string) (*bool, error) - SetSubjectPermissions(ctx context.Context, roleID string, permissions []string) ([]*model.AdminPermissionInfo, error) - SetUserCredentials(ctx context.Context, userID string, providerID string, credentials interface{}) (*bool, error) + CreateTeam(ctx context.Context, teamID string, teamName *string, description *string) (*model.AdminTeamInfo, error) + UpdateTeam(ctx context.Context, teamID string, teamName *string, description *string) (*model.AdminTeamInfo, error) + DeleteTeam(ctx context.Context, teamID string, force *bool) (*bool, error) + GrantUserTeam(ctx context.Context, userID string, teamID string) (*bool, error) + RevokeUserTeam(ctx context.Context, userID string, teamID string) (*bool, error) + SetSubjectPermissions(ctx context.Context, subjectID string, permissions []string) ([]*model.AdminPermissionInfo, error) + SetUserCredentials(ctx context.Context, userID string, providerID string, credentials any) (*bool, error) + DeleteUserCredentials(ctx context.Context, userID string, providerID string) (*bool, error) EnableUser(ctx context.Context, userID string, enabled bool) (*bool, error) - AllConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) + SetUserAuthRole(ctx context.Context, userID string, authRole *string) (*bool, error) + SetUserTeamRole(ctx context.Context, userID string, teamID string, teamRole *string) (*bool, error) SearchConnections(ctx context.Context, hostNames []string) ([]*model.AdminConnectionSearchInfo, error) - CreateConnectionConfiguration(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) - CopyConnectionConfiguration(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) - UpdateConnectionConfiguration(ctx context.Context, id string, config model.ConnectionConfig) (*model.ConnectionInfo, error) - DeleteConnectionConfiguration(ctx context.Context, id string) (*bool, error) - GetConnectionSubjectAccess(ctx context.Context, connectionID *string) ([]*model.AdminConnectionGrantInfo, error) - SetConnectionSubjectAccess(ctx context.Context, connectionID string, subjects []string) (*bool, error) - GetSubjectConnectionAccess(ctx context.Context, subjectID *string) ([]*model.AdminConnectionGrantInfo, error) + GetConnectionSubjectAccess(ctx context.Context, projectID string, connectionID *string) ([]*model.AdminConnectionGrantInfo, error) + SetConnectionSubjectAccess(ctx context.Context, projectID string, connectionID string, subjects []string) (*bool, error) + AddConnectionsAccess(ctx context.Context, projectID string, connectionIds []string, subjects []string) (*bool, error) + DeleteConnectionsAccess(ctx context.Context, projectID string, connectionIds []string, subjects []string) (*bool, error) + GetSubjectConnectionAccess(ctx context.Context, subjectID string) ([]*model.AdminConnectionGrantInfo, error) SetSubjectConnectionAccess(ctx context.Context, subjectID string, connections []string) (*bool, error) ListFeatureSets(ctx context.Context) ([]*model.WebFeatureSet, error) ListAuthProviderConfigurationParameters(ctx context.Context, providerID string) ([]*model.ObjectPropertyInfo, error) ListAuthProviderConfigurations(ctx context.Context, providerID *string) ([]*model.AdminAuthProviderConfiguration, error) - SaveAuthProviderConfiguration(ctx context.Context, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters interface{}) (*model.AdminAuthProviderConfiguration, error) + SaveAuthProviderConfiguration(ctx context.Context, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters any) (*model.AdminAuthProviderConfiguration, error) DeleteAuthProviderConfiguration(ctx context.Context, id string) (bool, error) SaveUserMetaParameter(ctx context.Context, id string, displayName string, description *string, required bool) (*model.ObjectPropertyInfo, error) DeleteUserMetaParameter(ctx context.Context, id string) (bool, error) - SetUserMetaParameterValues(ctx context.Context, userID string, parameters interface{}) (bool, error) + SetUserMetaParameterValues(ctx context.Context, userID string, parameters any) (bool, error) + SetTeamMetaParameterValues(ctx context.Context, teamID string, parameters any) (bool, error) ConfigureServer(ctx context.Context, configuration model.ServerConfigInput) (bool, error) SetDefaultNavigatorSettings(ctx context.Context, settings model.NavigatorSettingsInput) (bool, error) - AuthLogin(ctx context.Context, provider string, configuration *string, credentials interface{}, linkUser *bool) (*model.AuthInfo, error) + AuthLogin(ctx context.Context, provider string, configuration *string, credentials any, linkUser *bool, forceSessionsLogout *bool) (*model.AuthInfo, error) + FederatedAuthTaskResult(ctx context.Context, taskID string) (*model.FederatedAuthResult, error) AuthUpdateStatus(ctx context.Context, authID string, linkUser *bool) (*model.AuthInfo, error) AuthLogout(ctx context.Context, provider *string, configuration *string) (*bool, error) + AuthLogoutExtended(ctx context.Context, provider *string, configuration *string) (*model.LogoutInfo, error) ActiveUser(ctx context.Context) (*model.UserInfo, error) AuthProviders(ctx context.Context) ([]*model.AuthProviderInfo, error) AuthChangeLocalPassword(ctx context.Context, oldPassword string, newPassword string) (bool, error) ListUserProfileProperties(ctx context.Context) ([]*model.ObjectPropertyInfo, error) ServerConfig(ctx context.Context) (*model.ServerConfig, error) + SystemInfo(ctx context.Context) ([]*model.ObjectPropertyInfo, error) + ProductSettings(ctx context.Context) (*model.ProductSettings, error) SessionState(ctx context.Context) (*model.SessionInfo, error) SessionPermissions(ctx context.Context) ([]*string, error) DriverList(ctx context.Context, id *string) ([]*model.DriverInfo, error) AuthModels(ctx context.Context) ([]*model.DatabaseAuthModel, error) NetworkHandlers(ctx context.Context) ([]*model.NetworkHandlerDescriptor, error) - UserConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) - TemplateConnections(ctx context.Context) ([]*model.ConnectionInfo, error) - ConnectionFolders(ctx context.Context, path *string) ([]*model.ConnectionFolderInfo, error) - ConnectionState(ctx context.Context, id string) (*model.ConnectionInfo, error) - ConnectionInfo(ctx context.Context, id string) (*model.ConnectionInfo, error) + UserConnections(ctx context.Context, projectID *string, id *string, projectIds []string) ([]*model.ConnectionInfo, error) + ConnectionFolders(ctx context.Context, projectID *string, path *string) ([]*model.ConnectionFolderInfo, error) + ConnectionInfo(ctx context.Context, projectID string, id string) (*model.ConnectionInfo, error) + ListProjects(ctx context.Context) ([]*model.ProjectInfo, error) ReadSessionLog(ctx context.Context, maxEntries *int, clearEntries *bool) ([]*model.LogEntry, error) DataTransferAvailableStreamProcessors(ctx context.Context) ([]*model.DataTransferProcessorInfo, error) - DataTransferExportDataFromContainer(ctx context.Context, connectionID string, containerNodePath string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) - DataTransferExportDataFromResults(ctx context.Context, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) + DataTransferAvailableImportStreamProcessors(ctx context.Context) ([]*model.DataTransferProcessorInfo, error) + DataTransferDefaultExportSettings(ctx context.Context) (*model.DataTransferDefaultExportSettings, error) + DataTransferExportDataFromContainer(ctx context.Context, projectID *string, connectionID string, containerNodePath string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) + DataTransferExportDataFromResults(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) DataTransferRemoveDataFile(ctx context.Context, dataFileID string) (*bool, error) - MetadataGetNodeDdl(ctx context.Context, nodeID string, options interface{}) (*string, error) + MetadataGetNodeDdl(ctx context.Context, nodeID string, options any) (*string, error) + MetadataGetNodeExtendedDdl(ctx context.Context, nodeID string) (*string, error) NavNodeChildren(ctx context.Context, parentPath string, offset *int, limit *int, onlyFolders *bool) ([]*model.NavigatorNodeInfo, error) NavNodeParents(ctx context.Context, nodePath string) ([]*model.NavigatorNodeInfo, error) NavNodeInfo(ctx context.Context, nodePath string) (*model.NavigatorNodeInfo, error) NavRefreshNode(ctx context.Context, nodePath string) (*bool, error) - NavGetStructContainers(ctx context.Context, connectionID string, contextID *string, catalog *string) (*model.DatabaseStructContainers, error) + NavGetStructContainers(ctx context.Context, projectID *string, connectionID string, contextID *string, catalog *string) (*model.DatabaseStructContainers, error) RmListProjects(ctx context.Context) ([]*model.RMProject, error) + RmListSharedProjects(ctx context.Context) ([]*model.RMProject, error) + RmProject(ctx context.Context, projectID string) (*model.RMProject, error) + RmListProjectPermissions(ctx context.Context) ([]*model.AdminPermissionInfo, error) + RmListProjectGrantedPermissions(ctx context.Context, projectID string) ([]*model.AdminObjectGrantInfo, error) + RmListSubjectProjectsPermissionGrants(ctx context.Context, subjectID string) ([]*model.AdminObjectGrantInfo, error) RmListResources(ctx context.Context, projectID string, folder *string, nameMask *string, readProperties *bool, readHistory *bool) ([]*model.RMResource, error) RmReadResourceAsString(ctx context.Context, projectID string, resourcePath string) (string, error) - SQLDialectInfo(ctx context.Context, connectionID string) (*model.SQLDialectInfo, error) - SQLListContexts(ctx context.Context, connectionID *string, contextID *string) ([]*model.SQLContextInfo, error) - SQLCompletionProposals(ctx context.Context, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) ([]*model.SQLCompletionProposal, error) - SQLFormatQuery(ctx context.Context, connectionID string, contextID string, query string) (string, error) - SQLSupportedOperations(ctx context.Context, connectionID string, contextID string, resultsID string, attributeIndex int) ([]*model.DataTypeLogicalOperation, error) + SQLDialectInfo(ctx context.Context, projectID *string, connectionID string) (*model.SQLDialectInfo, error) + SQLListContexts(ctx context.Context, projectID *string, connectionID *string, contextID *string) ([]*model.SQLContextInfo, error) + SQLCompletionProposals(ctx context.Context, projectID *string, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) ([]*model.SQLCompletionProposal, error) + SQLFormatQuery(ctx context.Context, projectID *string, connectionID string, contextID string, query string) (string, error) + SQLSupportedOperations(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, attributeIndex int) ([]*model.DataTypeLogicalOperation, error) SQLEntityQueryGenerators(ctx context.Context, nodePathList []string) ([]*model.SQLQueryGenerator, error) - SQLGenerateEntityQuery(ctx context.Context, generatorID string, options interface{}, nodePathList []string) (string, error) - SQLParseScript(ctx context.Context, connectionID string, script string) (*model.SQLScriptInfo, error) - SQLParseQuery(ctx context.Context, connectionID string, script string, position int) (*model.SQLScriptQuery, error) + SQLGenerateEntityQuery(ctx context.Context, generatorID string, options any, nodePathList []string) (string, error) + SQLParseScript(ctx context.Context, projectID *string, connectionID string, script string) (*model.SQLScriptInfo, error) + SQLParseQuery(ctx context.Context, projectID *string, connectionID string, script string, position int) (*model.SQLScriptQuery, error) + SQLGenerateGroupingQuery(ctx context.Context, projectID *string, contextID string, connectionID string, resultsID string, columnNames []string, functions []string, showDuplicatesOnly *bool) (string, error) } type executableSchema struct { + schema *ast.Schema resolvers ResolverRoot directives DirectiveRoot complexity ComplexityRoot } func (e *executableSchema) Schema() *ast.Schema { + if e.schema != nil { + return e.schema + } return parsedSchema } -func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { - ec := executionContext{nil, e} +func (e *executableSchema) Complexity(ctx context.Context, typeName, field string, childComplexity int, rawArgs map[string]any) (int, bool) { + ec := executionContext{nil, e, 0, 0, nil} _ = ec switch typeName + "." + field { + case "AdminAuthProviderConfiguration.acsLink": + if e.complexity.AdminAuthProviderConfiguration.AcsLink == nil { + break + } + + return e.complexity.AdminAuthProviderConfiguration.AcsLink(childComplexity), true case "AdminAuthProviderConfiguration.description": if e.complexity.AdminAuthProviderConfiguration.Description == nil { break } return e.complexity.AdminAuthProviderConfiguration.Description(childComplexity), true - case "AdminAuthProviderConfiguration.disabled": if e.complexity.AdminAuthProviderConfiguration.Disabled == nil { break } return e.complexity.AdminAuthProviderConfiguration.Disabled(childComplexity), true - case "AdminAuthProviderConfiguration.displayName": if e.complexity.AdminAuthProviderConfiguration.DisplayName == nil { break } return e.complexity.AdminAuthProviderConfiguration.DisplayName(childComplexity), true + case "AdminAuthProviderConfiguration.entityIdLink": + if e.complexity.AdminAuthProviderConfiguration.EntityIDLink == nil { + break + } + return e.complexity.AdminAuthProviderConfiguration.EntityIDLink(childComplexity), true case "AdminAuthProviderConfiguration.id": if e.complexity.AdminAuthProviderConfiguration.ID == nil { break } return e.complexity.AdminAuthProviderConfiguration.ID(childComplexity), true - case "AdminAuthProviderConfiguration.iconURL": if e.complexity.AdminAuthProviderConfiguration.IconURL == nil { break } return e.complexity.AdminAuthProviderConfiguration.IconURL(childComplexity), true - case "AdminAuthProviderConfiguration.metadataLink": if e.complexity.AdminAuthProviderConfiguration.MetadataLink == nil { break } return e.complexity.AdminAuthProviderConfiguration.MetadataLink(childComplexity), true - case "AdminAuthProviderConfiguration.parameters": if e.complexity.AdminAuthProviderConfiguration.Parameters == nil { break } return e.complexity.AdminAuthProviderConfiguration.Parameters(childComplexity), true - case "AdminAuthProviderConfiguration.providerId": if e.complexity.AdminAuthProviderConfiguration.ProviderID == nil { break } return e.complexity.AdminAuthProviderConfiguration.ProviderID(childComplexity), true - case "AdminAuthProviderConfiguration.redirectLink": if e.complexity.AdminAuthProviderConfiguration.RedirectLink == nil { break } return e.complexity.AdminAuthProviderConfiguration.RedirectLink(childComplexity), true - case "AdminAuthProviderConfiguration.signInLink": if e.complexity.AdminAuthProviderConfiguration.SignInLink == nil { break } return e.complexity.AdminAuthProviderConfiguration.SignInLink(childComplexity), true - case "AdminAuthProviderConfiguration.signOutLink": if e.complexity.AdminAuthProviderConfiguration.SignOutLink == nil { break @@ -963,21 +1249,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.AdminConnectionGrantInfo.ConnectionID(childComplexity), true - case "AdminConnectionGrantInfo.dataSourceId": if e.complexity.AdminConnectionGrantInfo.DataSourceID == nil { break } return e.complexity.AdminConnectionGrantInfo.DataSourceID(childComplexity), true - case "AdminConnectionGrantInfo.subjectId": if e.complexity.AdminConnectionGrantInfo.SubjectID == nil { break } return e.complexity.AdminConnectionGrantInfo.SubjectID(childComplexity), true - case "AdminConnectionGrantInfo.subjectType": if e.complexity.AdminConnectionGrantInfo.SubjectType == nil { break @@ -991,28 +1274,24 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.AdminConnectionSearchInfo.DefaultDriver(childComplexity), true - case "AdminConnectionSearchInfo.displayName": if e.complexity.AdminConnectionSearchInfo.DisplayName == nil { break } return e.complexity.AdminConnectionSearchInfo.DisplayName(childComplexity), true - case "AdminConnectionSearchInfo.host": if e.complexity.AdminConnectionSearchInfo.Host == nil { break } return e.complexity.AdminConnectionSearchInfo.Host(childComplexity), true - case "AdminConnectionSearchInfo.port": if e.complexity.AdminConnectionSearchInfo.Port == nil { break } return e.complexity.AdminConnectionSearchInfo.Port(childComplexity), true - case "AdminConnectionSearchInfo.possibleDrivers": if e.complexity.AdminConnectionSearchInfo.PossibleDrivers == nil { break @@ -1020,34 +1299,62 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.AdminConnectionSearchInfo.PossibleDrivers(childComplexity), true + case "AdminObjectGrantInfo.objectPermissions": + if e.complexity.AdminObjectGrantInfo.ObjectPermissions == nil { + break + } + + return e.complexity.AdminObjectGrantInfo.ObjectPermissions(childComplexity), true + case "AdminObjectGrantInfo.subjectId": + if e.complexity.AdminObjectGrantInfo.SubjectID == nil { + break + } + + return e.complexity.AdminObjectGrantInfo.SubjectID(childComplexity), true + case "AdminObjectGrantInfo.subjectType": + if e.complexity.AdminObjectGrantInfo.SubjectType == nil { + break + } + + return e.complexity.AdminObjectGrantInfo.SubjectType(childComplexity), true + + case "AdminObjectPermissions.objectId": + if e.complexity.AdminObjectPermissions.ObjectID == nil { + break + } + + return e.complexity.AdminObjectPermissions.ObjectID(childComplexity), true + case "AdminObjectPermissions.permissions": + if e.complexity.AdminObjectPermissions.Permissions == nil { + break + } + + return e.complexity.AdminObjectPermissions.Permissions(childComplexity), true + case "AdminPermissionInfo.category": if e.complexity.AdminPermissionInfo.Category == nil { break } return e.complexity.AdminPermissionInfo.Category(childComplexity), true - case "AdminPermissionInfo.description": if e.complexity.AdminPermissionInfo.Description == nil { break } return e.complexity.AdminPermissionInfo.Description(childComplexity), true - case "AdminPermissionInfo.id": if e.complexity.AdminPermissionInfo.ID == nil { break } return e.complexity.AdminPermissionInfo.ID(childComplexity), true - case "AdminPermissionInfo.label": if e.complexity.AdminPermissionInfo.Label == nil { break } return e.complexity.AdminPermissionInfo.Label(childComplexity), true - case "AdminPermissionInfo.provider": if e.complexity.AdminPermissionInfo.Provider == nil { break @@ -1055,97 +1362,121 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.AdminPermissionInfo.Provider(childComplexity), true - case "AdminRoleInfo.description": - if e.complexity.AdminRoleInfo.Description == nil { + case "AdminTeamInfo.description": + if e.complexity.AdminTeamInfo.Description == nil { break } - return e.complexity.AdminRoleInfo.Description(childComplexity), true - - case "AdminRoleInfo.grantedConnections": - if e.complexity.AdminRoleInfo.GrantedConnections == nil { + return e.complexity.AdminTeamInfo.Description(childComplexity), true + case "AdminTeamInfo.grantedConnections": + if e.complexity.AdminTeamInfo.GrantedConnections == nil { break } - return e.complexity.AdminRoleInfo.GrantedConnections(childComplexity), true + return e.complexity.AdminTeamInfo.GrantedConnections(childComplexity), true + case "AdminTeamInfo.grantedUsers": + if e.complexity.AdminTeamInfo.GrantedUsers == nil { + break + } - case "AdminRoleInfo.grantedUsers": - if e.complexity.AdminRoleInfo.GrantedUsers == nil { + return e.complexity.AdminTeamInfo.GrantedUsers(childComplexity), true + case "AdminTeamInfo.grantedUsersInfo": + if e.complexity.AdminTeamInfo.GrantedUsersInfo == nil { break } - return e.complexity.AdminRoleInfo.GrantedUsers(childComplexity), true + return e.complexity.AdminTeamInfo.GrantedUsersInfo(childComplexity), true + case "AdminTeamInfo.metaParameters": + if e.complexity.AdminTeamInfo.MetaParameters == nil { + break + } - case "AdminRoleInfo.roleId": - if e.complexity.AdminRoleInfo.RoleID == nil { + return e.complexity.AdminTeamInfo.MetaParameters(childComplexity), true + case "AdminTeamInfo.teamId": + if e.complexity.AdminTeamInfo.TeamID == nil { break } - return e.complexity.AdminRoleInfo.RoleID(childComplexity), true + return e.complexity.AdminTeamInfo.TeamID(childComplexity), true + case "AdminTeamInfo.teamName": + if e.complexity.AdminTeamInfo.TeamName == nil { + break + } - case "AdminRoleInfo.roleName": - if e.complexity.AdminRoleInfo.RoleName == nil { + return e.complexity.AdminTeamInfo.TeamName(childComplexity), true + case "AdminTeamInfo.teamPermissions": + if e.complexity.AdminTeamInfo.TeamPermissions == nil { break } - return e.complexity.AdminRoleInfo.RoleName(childComplexity), true + return e.complexity.AdminTeamInfo.TeamPermissions(childComplexity), true - case "AdminRoleInfo.rolePermissions": - if e.complexity.AdminRoleInfo.RolePermissions == nil { + case "AdminUserInfo.authRole": + if e.complexity.AdminUserInfo.AuthRole == nil { break } - return e.complexity.AdminRoleInfo.RolePermissions(childComplexity), true - + return e.complexity.AdminUserInfo.AuthRole(childComplexity), true case "AdminUserInfo.configurationParameters": if e.complexity.AdminUserInfo.ConfigurationParameters == nil { break } return e.complexity.AdminUserInfo.ConfigurationParameters(childComplexity), true + case "AdminUserInfo.disableDate": + if e.complexity.AdminUserInfo.DisableDate == nil { + break + } + + return e.complexity.AdminUserInfo.DisableDate(childComplexity), true + case "AdminUserInfo.disableReason": + if e.complexity.AdminUserInfo.DisableReason == nil { + break + } + return e.complexity.AdminUserInfo.DisableReason(childComplexity), true + case "AdminUserInfo.disabledBy": + if e.complexity.AdminUserInfo.DisabledBy == nil { + break + } + + return e.complexity.AdminUserInfo.DisabledBy(childComplexity), true case "AdminUserInfo.enabled": if e.complexity.AdminUserInfo.Enabled == nil { break } return e.complexity.AdminUserInfo.Enabled(childComplexity), true - case "AdminUserInfo.grantedConnections": if e.complexity.AdminUserInfo.GrantedConnections == nil { break } return e.complexity.AdminUserInfo.GrantedConnections(childComplexity), true - - case "AdminUserInfo.grantedRoles": - if e.complexity.AdminUserInfo.GrantedRoles == nil { + case "AdminUserInfo.grantedTeams": + if e.complexity.AdminUserInfo.GrantedTeams == nil { break } - return e.complexity.AdminUserInfo.GrantedRoles(childComplexity), true - + return e.complexity.AdminUserInfo.GrantedTeams(childComplexity), true case "AdminUserInfo.linkedAuthProviders": if e.complexity.AdminUserInfo.LinkedAuthProviders == nil { break } return e.complexity.AdminUserInfo.LinkedAuthProviders(childComplexity), true - case "AdminUserInfo.metaParameters": if e.complexity.AdminUserInfo.MetaParameters == nil { break } return e.complexity.AdminUserInfo.MetaParameters(childComplexity), true - case "AdminUserInfo.origins": if e.complexity.AdminUserInfo.Origins == nil { break } return e.complexity.AdminUserInfo.Origins(childComplexity), true - case "AdminUserInfo.userId": if e.complexity.AdminUserInfo.UserID == nil { break @@ -1153,48 +1484,49 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.AdminUserInfo.UserID(childComplexity), true + case "AdminUserTeamGrantInfo.teamRole": + if e.complexity.AdminUserTeamGrantInfo.TeamRole == nil { + break + } + + return e.complexity.AdminUserTeamGrantInfo.TeamRole(childComplexity), true + case "AdminUserTeamGrantInfo.userId": + if e.complexity.AdminUserTeamGrantInfo.UserID == nil { + break + } + + return e.complexity.AdminUserTeamGrantInfo.UserID(childComplexity), true + case "AsyncTaskInfo.error": if e.complexity.AsyncTaskInfo.Error == nil { break } return e.complexity.AsyncTaskInfo.Error(childComplexity), true - case "AsyncTaskInfo.id": if e.complexity.AsyncTaskInfo.ID == nil { break } return e.complexity.AsyncTaskInfo.ID(childComplexity), true - case "AsyncTaskInfo.name": if e.complexity.AsyncTaskInfo.Name == nil { break } return e.complexity.AsyncTaskInfo.Name(childComplexity), true - - case "AsyncTaskInfo.result": - if e.complexity.AsyncTaskInfo.Result == nil { - break - } - - return e.complexity.AsyncTaskInfo.Result(childComplexity), true - case "AsyncTaskInfo.running": if e.complexity.AsyncTaskInfo.Running == nil { break } return e.complexity.AsyncTaskInfo.Running(childComplexity), true - case "AsyncTaskInfo.status": if e.complexity.AsyncTaskInfo.Status == nil { break } return e.complexity.AsyncTaskInfo.Status(childComplexity), true - case "AsyncTaskInfo.taskResult": if e.complexity.AsyncTaskInfo.TaskResult == nil { break @@ -1208,49 +1540,42 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.AuthCredentialInfo.Admin(childComplexity), true - case "AuthCredentialInfo.description": if e.complexity.AuthCredentialInfo.Description == nil { break } return e.complexity.AuthCredentialInfo.Description(childComplexity), true - case "AuthCredentialInfo.displayName": if e.complexity.AuthCredentialInfo.DisplayName == nil { break } return e.complexity.AuthCredentialInfo.DisplayName(childComplexity), true - case "AuthCredentialInfo.encryption": if e.complexity.AuthCredentialInfo.Encryption == nil { break } return e.complexity.AuthCredentialInfo.Encryption(childComplexity), true - case "AuthCredentialInfo.id": if e.complexity.AuthCredentialInfo.ID == nil { break } return e.complexity.AuthCredentialInfo.ID(childComplexity), true - case "AuthCredentialInfo.identifying": if e.complexity.AuthCredentialInfo.Identifying == nil { break } return e.complexity.AuthCredentialInfo.Identifying(childComplexity), true - case "AuthCredentialInfo.possibleValues": if e.complexity.AuthCredentialInfo.PossibleValues == nil { break } return e.complexity.AuthCredentialInfo.PossibleValues(childComplexity), true - case "AuthCredentialInfo.user": if e.complexity.AuthCredentialInfo.User == nil { break @@ -1264,21 +1589,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.AuthInfo.AuthID(childComplexity), true - case "AuthInfo.authStatus": if e.complexity.AuthInfo.AuthStatus == nil { break } return e.complexity.AuthInfo.AuthStatus(childComplexity), true - case "AuthInfo.redirectLink": if e.complexity.AuthInfo.RedirectLink == nil { break } return e.complexity.AuthInfo.RedirectLink(childComplexity), true - case "AuthInfo.userTokens": if e.complexity.AuthInfo.UserTokens == nil { break @@ -1286,55 +1608,72 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.AuthInfo.UserTokens(childComplexity), true + case "AuthProviderConfiguration.acsLink": + if e.complexity.AuthProviderConfiguration.AcsLink == nil { + break + } + + return e.complexity.AuthProviderConfiguration.AcsLink(childComplexity), true + case "AuthProviderConfiguration.authRoleProvided": + if e.complexity.AuthProviderConfiguration.AuthRoleProvided == nil { + break + } + + return e.complexity.AuthProviderConfiguration.AuthRoleProvided(childComplexity), true case "AuthProviderConfiguration.description": if e.complexity.AuthProviderConfiguration.Description == nil { break } return e.complexity.AuthProviderConfiguration.Description(childComplexity), true - case "AuthProviderConfiguration.disabled": if e.complexity.AuthProviderConfiguration.Disabled == nil { break } return e.complexity.AuthProviderConfiguration.Disabled(childComplexity), true - case "AuthProviderConfiguration.displayName": if e.complexity.AuthProviderConfiguration.DisplayName == nil { break } return e.complexity.AuthProviderConfiguration.DisplayName(childComplexity), true + case "AuthProviderConfiguration.entityIdLink": + if e.complexity.AuthProviderConfiguration.EntityIDLink == nil { + break + } + return e.complexity.AuthProviderConfiguration.EntityIDLink(childComplexity), true case "AuthProviderConfiguration.id": if e.complexity.AuthProviderConfiguration.ID == nil { break } return e.complexity.AuthProviderConfiguration.ID(childComplexity), true - case "AuthProviderConfiguration.iconURL": if e.complexity.AuthProviderConfiguration.IconURL == nil { break } return e.complexity.AuthProviderConfiguration.IconURL(childComplexity), true - case "AuthProviderConfiguration.metadataLink": if e.complexity.AuthProviderConfiguration.MetadataLink == nil { break } return e.complexity.AuthProviderConfiguration.MetadataLink(childComplexity), true + case "AuthProviderConfiguration.redirectLink": + if e.complexity.AuthProviderConfiguration.RedirectLink == nil { + break + } + return e.complexity.AuthProviderConfiguration.RedirectLink(childComplexity), true case "AuthProviderConfiguration.signInLink": if e.complexity.AuthProviderConfiguration.SignInLink == nil { break } return e.complexity.AuthProviderConfiguration.SignInLink(childComplexity), true - case "AuthProviderConfiguration.signOutLink": if e.complexity.AuthProviderConfiguration.SignOutLink == nil { break @@ -1348,21 +1687,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.AuthProviderCredentialsProfile.CredentialParameters(childComplexity), true - case "AuthProviderCredentialsProfile.description": if e.complexity.AuthProviderCredentialsProfile.Description == nil { break } return e.complexity.AuthProviderCredentialsProfile.Description(childComplexity), true - case "AuthProviderCredentialsProfile.id": if e.complexity.AuthProviderCredentialsProfile.ID == nil { break } return e.complexity.AuthProviderCredentialsProfile.ID(childComplexity), true - case "AuthProviderCredentialsProfile.label": if e.complexity.AuthProviderCredentialsProfile.Label == nil { break @@ -1370,68 +1706,115 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.AuthProviderCredentialsProfile.Label(childComplexity), true + case "AuthProviderInfo.authHidden": + if e.complexity.AuthProviderInfo.AuthHidden == nil { + break + } + + return e.complexity.AuthProviderInfo.AuthHidden(childComplexity), true case "AuthProviderInfo.configurable": if e.complexity.AuthProviderInfo.Configurable == nil { break } return e.complexity.AuthProviderInfo.Configurable(childComplexity), true - case "AuthProviderInfo.configurations": if e.complexity.AuthProviderInfo.Configurations == nil { break } return e.complexity.AuthProviderInfo.Configurations(childComplexity), true - case "AuthProviderInfo.credentialProfiles": if e.complexity.AuthProviderInfo.CredentialProfiles == nil { break } return e.complexity.AuthProviderInfo.CredentialProfiles(childComplexity), true - case "AuthProviderInfo.defaultProvider": if e.complexity.AuthProviderInfo.DefaultProvider == nil { break } return e.complexity.AuthProviderInfo.DefaultProvider(childComplexity), true - case "AuthProviderInfo.description": if e.complexity.AuthProviderInfo.Description == nil { break } return e.complexity.AuthProviderInfo.Description(childComplexity), true + case "AuthProviderInfo.federated": + if e.complexity.AuthProviderInfo.Federated == nil { + break + } + return e.complexity.AuthProviderInfo.Federated(childComplexity), true case "AuthProviderInfo.id": if e.complexity.AuthProviderInfo.ID == nil { break } return e.complexity.AuthProviderInfo.ID(childComplexity), true - case "AuthProviderInfo.icon": if e.complexity.AuthProviderInfo.Icon == nil { break } return e.complexity.AuthProviderInfo.Icon(childComplexity), true - case "AuthProviderInfo.label": if e.complexity.AuthProviderInfo.Label == nil { break } return e.complexity.AuthProviderInfo.Label(childComplexity), true + case "AuthProviderInfo.private": + if e.complexity.AuthProviderInfo.Private == nil { + break + } + + return e.complexity.AuthProviderInfo.Private(childComplexity), true + case "AuthProviderInfo.required": + if e.complexity.AuthProviderInfo.Required == nil { + break + } + return e.complexity.AuthProviderInfo.Required(childComplexity), true case "AuthProviderInfo.requiredFeatures": if e.complexity.AuthProviderInfo.RequiredFeatures == nil { break } return e.complexity.AuthProviderInfo.RequiredFeatures(childComplexity), true + case "AuthProviderInfo.supportProvisioning": + if e.complexity.AuthProviderInfo.SupportProvisioning == nil { + break + } + + return e.complexity.AuthProviderInfo.SupportProvisioning(childComplexity), true + case "AuthProviderInfo.templateConfiguration": + if e.complexity.AuthProviderInfo.TemplateConfiguration == nil { + break + } + + return e.complexity.AuthProviderInfo.TemplateConfiguration(childComplexity), true + case "AuthProviderInfo.trusted": + if e.complexity.AuthProviderInfo.Trusted == nil { + break + } + + return e.complexity.AuthProviderInfo.Trusted(childComplexity), true + + case "Condition.conditionType": + if e.complexity.Condition.ConditionType == nil { + break + } + + return e.complexity.Condition.ConditionType(childComplexity), true + case "Condition.expression": + if e.complexity.Condition.Expression == nil { + break + } + + return e.complexity.Condition.Expression(childComplexity), true case "ConnectionFolderInfo.description": if e.complexity.ConnectionFolderInfo.Description == nil { @@ -1439,13 +1822,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ConnectionFolderInfo.Description(childComplexity), true - case "ConnectionFolderInfo.id": if e.complexity.ConnectionFolderInfo.ID == nil { break } return e.complexity.ConnectionFolderInfo.ID(childComplexity), true + case "ConnectionFolderInfo.projectId": + if e.complexity.ConnectionFolderInfo.ProjectID == nil { + break + } + + return e.complexity.ConnectionFolderInfo.ProjectID(childComplexity), true case "ConnectionInfo.authModel": if e.complexity.ConnectionInfo.AuthModel == nil { @@ -1453,210 +1841,270 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ConnectionInfo.AuthModel(childComplexity), true - case "ConnectionInfo.authNeeded": if e.complexity.ConnectionInfo.AuthNeeded == nil { break } return e.complexity.ConnectionInfo.AuthNeeded(childComplexity), true - case "ConnectionInfo.authProperties": if e.complexity.ConnectionInfo.AuthProperties == nil { break } return e.complexity.ConnectionInfo.AuthProperties(childComplexity), true + case "ConnectionInfo.autocommit": + if e.complexity.ConnectionInfo.Autocommit == nil { + break + } + + return e.complexity.ConnectionInfo.Autocommit(childComplexity), true + case "ConnectionInfo.canDelete": + if e.complexity.ConnectionInfo.CanDelete == nil { + break + } + return e.complexity.ConnectionInfo.CanDelete(childComplexity), true + case "ConnectionInfo.canEdit": + if e.complexity.ConnectionInfo.CanEdit == nil { + break + } + + return e.complexity.ConnectionInfo.CanEdit(childComplexity), true + case "ConnectionInfo.canViewSettings": + if e.complexity.ConnectionInfo.CanViewSettings == nil { + break + } + + return e.complexity.ConnectionInfo.CanViewSettings(childComplexity), true case "ConnectionInfo.clientVersion": if e.complexity.ConnectionInfo.ClientVersion == nil { break } return e.complexity.ConnectionInfo.ClientVersion(childComplexity), true + case "ConnectionInfo.configurationType": + if e.complexity.ConnectionInfo.ConfigurationType == nil { + break + } + return e.complexity.ConnectionInfo.ConfigurationType(childComplexity), true case "ConnectionInfo.connectTime": if e.complexity.ConnectionInfo.ConnectTime == nil { break } return e.complexity.ConnectionInfo.ConnectTime(childComplexity), true - case "ConnectionInfo.connected": if e.complexity.ConnectionInfo.Connected == nil { break } return e.complexity.ConnectionInfo.Connected(childComplexity), true - case "ConnectionInfo.connectionError": if e.complexity.ConnectionInfo.ConnectionError == nil { break } return e.complexity.ConnectionInfo.ConnectionError(childComplexity), true + case "ConnectionInfo.credentialsSaved": + if e.complexity.ConnectionInfo.CredentialsSaved == nil { + break + } + return e.complexity.ConnectionInfo.CredentialsSaved(childComplexity), true case "ConnectionInfo.databaseName": if e.complexity.ConnectionInfo.DatabaseName == nil { break } return e.complexity.ConnectionInfo.DatabaseName(childComplexity), true + case "ConnectionInfo.defaultCatalogName": + if e.complexity.ConnectionInfo.DefaultCatalogName == nil { + break + } + + return e.complexity.ConnectionInfo.DefaultCatalogName(childComplexity), true + case "ConnectionInfo.defaultSchemaName": + if e.complexity.ConnectionInfo.DefaultSchemaName == nil { + break + } + return e.complexity.ConnectionInfo.DefaultSchemaName(childComplexity), true case "ConnectionInfo.description": if e.complexity.ConnectionInfo.Description == nil { break } return e.complexity.ConnectionInfo.Description(childComplexity), true - case "ConnectionInfo.driverId": if e.complexity.ConnectionInfo.DriverID == nil { break } return e.complexity.ConnectionInfo.DriverID(childComplexity), true + case "ConnectionInfo.expertSettingsValues": + if e.complexity.ConnectionInfo.ExpertSettingsValues == nil { + break + } + return e.complexity.ConnectionInfo.ExpertSettingsValues(childComplexity), true case "ConnectionInfo.features": if e.complexity.ConnectionInfo.Features == nil { break } return e.complexity.ConnectionInfo.Features(childComplexity), true - case "ConnectionInfo.folder": if e.complexity.ConnectionInfo.Folder == nil { break } return e.complexity.ConnectionInfo.Folder(childComplexity), true - case "ConnectionInfo.host": if e.complexity.ConnectionInfo.Host == nil { break } return e.complexity.ConnectionInfo.Host(childComplexity), true - case "ConnectionInfo.id": if e.complexity.ConnectionInfo.ID == nil { break } return e.complexity.ConnectionInfo.ID(childComplexity), true + case "ConnectionInfo.keepAliveInterval": + if e.complexity.ConnectionInfo.KeepAliveInterval == nil { + break + } + + return e.complexity.ConnectionInfo.KeepAliveInterval(childComplexity), true + case "ConnectionInfo.mainPropertyValues": + if e.complexity.ConnectionInfo.MainPropertyValues == nil { + break + } + return e.complexity.ConnectionInfo.MainPropertyValues(childComplexity), true case "ConnectionInfo.name": if e.complexity.ConnectionInfo.Name == nil { break } return e.complexity.ConnectionInfo.Name(childComplexity), true - case "ConnectionInfo.navigatorSettings": if e.complexity.ConnectionInfo.NavigatorSettings == nil { break } return e.complexity.ConnectionInfo.NavigatorSettings(childComplexity), true - case "ConnectionInfo.networkHandlersConfig": if e.complexity.ConnectionInfo.NetworkHandlersConfig == nil { break } return e.complexity.ConnectionInfo.NetworkHandlersConfig(childComplexity), true - case "ConnectionInfo.nodePath": if e.complexity.ConnectionInfo.NodePath == nil { break } return e.complexity.ConnectionInfo.NodePath(childComplexity), true - case "ConnectionInfo.origin": if e.complexity.ConnectionInfo.Origin == nil { break } return e.complexity.ConnectionInfo.Origin(childComplexity), true - case "ConnectionInfo.port": if e.complexity.ConnectionInfo.Port == nil { break } return e.complexity.ConnectionInfo.Port(childComplexity), true + case "ConnectionInfo.projectId": + if e.complexity.ConnectionInfo.ProjectID == nil { + break + } + return e.complexity.ConnectionInfo.ProjectID(childComplexity), true case "ConnectionInfo.properties": if e.complexity.ConnectionInfo.Properties == nil { break } return e.complexity.ConnectionInfo.Properties(childComplexity), true - case "ConnectionInfo.provided": if e.complexity.ConnectionInfo.Provided == nil { break } return e.complexity.ConnectionInfo.Provided(childComplexity), true - case "ConnectionInfo.providerProperties": if e.complexity.ConnectionInfo.ProviderProperties == nil { break } return e.complexity.ConnectionInfo.ProviderProperties(childComplexity), true - case "ConnectionInfo.readOnly": if e.complexity.ConnectionInfo.ReadOnly == nil { break } return e.complexity.ConnectionInfo.ReadOnly(childComplexity), true + case "ConnectionInfo.requiredAuth": + if e.complexity.ConnectionInfo.RequiredAuth == nil { + break + } + return e.complexity.ConnectionInfo.RequiredAuth(childComplexity), true case "ConnectionInfo.saveCredentials": if e.complexity.ConnectionInfo.SaveCredentials == nil { break } return e.complexity.ConnectionInfo.SaveCredentials(childComplexity), true - case "ConnectionInfo.serverName": if e.complexity.ConnectionInfo.ServerName == nil { break } return e.complexity.ConnectionInfo.ServerName(childComplexity), true - case "ConnectionInfo.serverVersion": if e.complexity.ConnectionInfo.ServerVersion == nil { break } return e.complexity.ConnectionInfo.ServerVersion(childComplexity), true + case "ConnectionInfo.sharedCredentials": + if e.complexity.ConnectionInfo.SharedCredentials == nil { + break + } + return e.complexity.ConnectionInfo.SharedCredentials(childComplexity), true + case "ConnectionInfo.sharedSecrets": + if e.complexity.ConnectionInfo.SharedSecrets == nil { + break + } + + return e.complexity.ConnectionInfo.SharedSecrets(childComplexity), true case "ConnectionInfo.supportedDataFormats": if e.complexity.ConnectionInfo.SupportedDataFormats == nil { break } return e.complexity.ConnectionInfo.SupportedDataFormats(childComplexity), true - - case "ConnectionInfo.template": - if e.complexity.ConnectionInfo.Template == nil { + case "ConnectionInfo.tools": + if e.complexity.ConnectionInfo.Tools == nil { break } - return e.complexity.ConnectionInfo.Template(childComplexity), true - + return e.complexity.ConnectionInfo.Tools(childComplexity), true case "ConnectionInfo.url": if e.complexity.ConnectionInfo.URL == nil { break } return e.complexity.ConnectionInfo.URL(childComplexity), true - case "ConnectionInfo.useUrl": if e.complexity.ConnectionInfo.UseURL == nil { break @@ -1664,76 +2112,104 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.ConnectionInfo.UseURL(childComplexity), true + case "DataTransferDefaultExportSettings.outputSettings": + if e.complexity.DataTransferDefaultExportSettings.OutputSettings == nil { + break + } + + return e.complexity.DataTransferDefaultExportSettings.OutputSettings(childComplexity), true + case "DataTransferDefaultExportSettings.supportedEncodings": + if e.complexity.DataTransferDefaultExportSettings.SupportedEncodings == nil { + break + } + + return e.complexity.DataTransferDefaultExportSettings.SupportedEncodings(childComplexity), true + + case "DataTransferOutputSettings.compress": + if e.complexity.DataTransferOutputSettings.Compress == nil { + break + } + + return e.complexity.DataTransferOutputSettings.Compress(childComplexity), true + case "DataTransferOutputSettings.encoding": + if e.complexity.DataTransferOutputSettings.Encoding == nil { + break + } + + return e.complexity.DataTransferOutputSettings.Encoding(childComplexity), true + case "DataTransferOutputSettings.insertBom": + if e.complexity.DataTransferOutputSettings.InsertBom == nil { + break + } + + return e.complexity.DataTransferOutputSettings.InsertBom(childComplexity), true + case "DataTransferOutputSettings.timestampPattern": + if e.complexity.DataTransferOutputSettings.TimestampPattern == nil { + break + } + + return e.complexity.DataTransferOutputSettings.TimestampPattern(childComplexity), true + case "DataTransferProcessorInfo.appFileExtension": if e.complexity.DataTransferProcessorInfo.AppFileExtension == nil { break } return e.complexity.DataTransferProcessorInfo.AppFileExtension(childComplexity), true - case "DataTransferProcessorInfo.appName": if e.complexity.DataTransferProcessorInfo.AppName == nil { break } return e.complexity.DataTransferProcessorInfo.AppName(childComplexity), true - case "DataTransferProcessorInfo.description": if e.complexity.DataTransferProcessorInfo.Description == nil { break } return e.complexity.DataTransferProcessorInfo.Description(childComplexity), true - case "DataTransferProcessorInfo.fileExtension": if e.complexity.DataTransferProcessorInfo.FileExtension == nil { break } return e.complexity.DataTransferProcessorInfo.FileExtension(childComplexity), true - case "DataTransferProcessorInfo.id": if e.complexity.DataTransferProcessorInfo.ID == nil { break } return e.complexity.DataTransferProcessorInfo.ID(childComplexity), true - case "DataTransferProcessorInfo.icon": if e.complexity.DataTransferProcessorInfo.Icon == nil { break } return e.complexity.DataTransferProcessorInfo.Icon(childComplexity), true - case "DataTransferProcessorInfo.isBinary": if e.complexity.DataTransferProcessorInfo.IsBinary == nil { break } return e.complexity.DataTransferProcessorInfo.IsBinary(childComplexity), true - case "DataTransferProcessorInfo.isHTML": if e.complexity.DataTransferProcessorInfo.IsHTML == nil { break } return e.complexity.DataTransferProcessorInfo.IsHTML(childComplexity), true - case "DataTransferProcessorInfo.name": if e.complexity.DataTransferProcessorInfo.Name == nil { break } return e.complexity.DataTransferProcessorInfo.Name(childComplexity), true - case "DataTransferProcessorInfo.order": if e.complexity.DataTransferProcessorInfo.Order == nil { break } return e.complexity.DataTransferProcessorInfo.Order(childComplexity), true - case "DataTransferProcessorInfo.properties": if e.complexity.DataTransferProcessorInfo.Properties == nil { break @@ -1747,14 +2223,12 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.DataTypeLogicalOperation.ArgumentCount(childComplexity), true - case "DataTypeLogicalOperation.expression": if e.complexity.DataTypeLogicalOperation.Expression == nil { break } return e.complexity.DataTypeLogicalOperation.Expression(childComplexity), true - case "DataTypeLogicalOperation.id": if e.complexity.DataTypeLogicalOperation.ID == nil { break @@ -1768,35 +2242,36 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.DatabaseAuthModel.Description(childComplexity), true - case "DatabaseAuthModel.displayName": if e.complexity.DatabaseAuthModel.DisplayName == nil { break } return e.complexity.DatabaseAuthModel.DisplayName(childComplexity), true - case "DatabaseAuthModel.id": if e.complexity.DatabaseAuthModel.ID == nil { break } return e.complexity.DatabaseAuthModel.ID(childComplexity), true - case "DatabaseAuthModel.icon": if e.complexity.DatabaseAuthModel.Icon == nil { break } return e.complexity.DatabaseAuthModel.Icon(childComplexity), true - case "DatabaseAuthModel.properties": if e.complexity.DatabaseAuthModel.Properties == nil { break } return e.complexity.DatabaseAuthModel.Properties(childComplexity), true + case "DatabaseAuthModel.requiredAuth": + if e.complexity.DatabaseAuthModel.RequiredAuth == nil { + break + } + return e.complexity.DatabaseAuthModel.RequiredAuth(childComplexity), true case "DatabaseAuthModel.requiresLocalConfiguration": if e.complexity.DatabaseAuthModel.RequiresLocalConfiguration == nil { break @@ -1810,7 +2285,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.DatabaseCatalog.Catalog(childComplexity), true - case "DatabaseCatalog.schemaList": if e.complexity.DatabaseCatalog.SchemaList == nil { break @@ -1824,21 +2298,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.DatabaseDocument.ContentType(childComplexity), true - case "DatabaseDocument.data": if e.complexity.DatabaseDocument.Data == nil { break } return e.complexity.DatabaseDocument.Data(childComplexity), true - case "DatabaseDocument.id": if e.complexity.DatabaseDocument.ID == nil { break } return e.complexity.DatabaseDocument.ID(childComplexity), true - case "DatabaseDocument.properties": if e.complexity.DatabaseDocument.Properties == nil { break @@ -1852,75 +2323,65 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.DatabaseObjectInfo.Description(childComplexity), true - case "DatabaseObjectInfo.editors": if e.complexity.DatabaseObjectInfo.Editors == nil { break } return e.complexity.DatabaseObjectInfo.Editors(childComplexity), true - case "DatabaseObjectInfo.features": if e.complexity.DatabaseObjectInfo.Features == nil { break } return e.complexity.DatabaseObjectInfo.Features(childComplexity), true - case "DatabaseObjectInfo.fullyQualifiedName": if e.complexity.DatabaseObjectInfo.FullyQualifiedName == nil { break } return e.complexity.DatabaseObjectInfo.FullyQualifiedName(childComplexity), true - case "DatabaseObjectInfo.name": if e.complexity.DatabaseObjectInfo.Name == nil { break } return e.complexity.DatabaseObjectInfo.Name(childComplexity), true - case "DatabaseObjectInfo.ordinalPosition": if e.complexity.DatabaseObjectInfo.OrdinalPosition == nil { break } return e.complexity.DatabaseObjectInfo.OrdinalPosition(childComplexity), true - case "DatabaseObjectInfo.overloadedName": if e.complexity.DatabaseObjectInfo.OverloadedName == nil { break } return e.complexity.DatabaseObjectInfo.OverloadedName(childComplexity), true - case "DatabaseObjectInfo.properties": if e.complexity.DatabaseObjectInfo.Properties == nil { break } - args, err := ec.field_DatabaseObjectInfo_properties_args(context.TODO(), rawArgs) + args, err := ec.field_DatabaseObjectInfo_properties_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.DatabaseObjectInfo.Properties(childComplexity, args["filter"].(*model.ObjectPropertyFilter)), true - case "DatabaseObjectInfo.state": if e.complexity.DatabaseObjectInfo.State == nil { break } return e.complexity.DatabaseObjectInfo.State(childComplexity), true - case "DatabaseObjectInfo.type": if e.complexity.DatabaseObjectInfo.Type == nil { break } return e.complexity.DatabaseObjectInfo.Type(childComplexity), true - case "DatabaseObjectInfo.uniqueName": if e.complexity.DatabaseObjectInfo.UniqueName == nil { break @@ -1934,21 +2395,24 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.DatabaseStructContainers.CatalogList(childComplexity), true + case "DatabaseStructContainers.parentNode": + if e.complexity.DatabaseStructContainers.ParentNode == nil { + break + } + return e.complexity.DatabaseStructContainers.ParentNode(childComplexity), true case "DatabaseStructContainers.schemaList": if e.complexity.DatabaseStructContainers.SchemaList == nil { break } return e.complexity.DatabaseStructContainers.SchemaList(childComplexity), true - case "DatabaseStructContainers.supportsCatalogChange": if e.complexity.DatabaseStructContainers.SupportsCatalogChange == nil { break } return e.complexity.DatabaseStructContainers.SupportsCatalogChange(childComplexity), true - case "DatabaseStructContainers.supportsSchemaChange": if e.complexity.DatabaseStructContainers.SupportsSchemaChange == nil { break @@ -1956,12 +2420,24 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.DatabaseStructContainers.SupportsSchemaChange(childComplexity), true - case "DriverInfo.allowsEmptyPassword": - if e.complexity.DriverInfo.AllowsEmptyPassword == nil { + case "DriverFileInfo.fileName": + if e.complexity.DriverFileInfo.FileName == nil { + break + } + + return e.complexity.DriverFileInfo.FileName(childComplexity), true + case "DriverFileInfo.id": + if e.complexity.DriverFileInfo.ID == nil { + break + } + + return e.complexity.DriverFileInfo.ID(childComplexity), true + case "DriverFileInfo.icon": + if e.complexity.DriverFileInfo.Icon == nil { break } - return e.complexity.DriverInfo.AllowsEmptyPassword(childComplexity), true + return e.complexity.DriverFileInfo.Icon(childComplexity), true case "DriverInfo.anonymousAccess": if e.complexity.DriverInfo.AnonymousAccess == nil { @@ -1969,202 +2445,298 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.DriverInfo.AnonymousAccess(childComplexity), true - case "DriverInfo.applicableAuthModels": if e.complexity.DriverInfo.ApplicableAuthModels == nil { break } return e.complexity.DriverInfo.ApplicableAuthModels(childComplexity), true - case "DriverInfo.applicableNetworkHandlers": if e.complexity.DriverInfo.ApplicableNetworkHandlers == nil { break } return e.complexity.DriverInfo.ApplicableNetworkHandlers(childComplexity), true + case "DriverInfo.configurationTypes": + if e.complexity.DriverInfo.ConfigurationTypes == nil { + break + } + return e.complexity.DriverInfo.ConfigurationTypes(childComplexity), true case "DriverInfo.custom": if e.complexity.DriverInfo.Custom == nil { break } return e.complexity.DriverInfo.Custom(childComplexity), true - case "DriverInfo.defaultAuthModel": if e.complexity.DriverInfo.DefaultAuthModel == nil { break } return e.complexity.DriverInfo.DefaultAuthModel(childComplexity), true - case "DriverInfo.defaultDatabase": if e.complexity.DriverInfo.DefaultDatabase == nil { break } return e.complexity.DriverInfo.DefaultDatabase(childComplexity), true - case "DriverInfo.defaultHost": if e.complexity.DriverInfo.DefaultHost == nil { break } return e.complexity.DriverInfo.DefaultHost(childComplexity), true - case "DriverInfo.defaultPort": if e.complexity.DriverInfo.DefaultPort == nil { break } return e.complexity.DriverInfo.DefaultPort(childComplexity), true - case "DriverInfo.defaultServer": if e.complexity.DriverInfo.DefaultServer == nil { break } return e.complexity.DriverInfo.DefaultServer(childComplexity), true - case "DriverInfo.defaultUser": if e.complexity.DriverInfo.DefaultUser == nil { break } return e.complexity.DriverInfo.DefaultUser(childComplexity), true - case "DriverInfo.description": if e.complexity.DriverInfo.Description == nil { break } return e.complexity.DriverInfo.Description(childComplexity), true + case "DriverInfo.downloadable": + if e.complexity.DriverInfo.Downloadable == nil { + break + } + return e.complexity.DriverInfo.Downloadable(childComplexity), true case "DriverInfo.driverClassName": if e.complexity.DriverInfo.DriverClassName == nil { break } return e.complexity.DriverInfo.DriverClassName(childComplexity), true + case "DriverInfo.driverId": + if e.complexity.DriverInfo.DriverID == nil { + break + } + return e.complexity.DriverInfo.DriverID(childComplexity), true case "DriverInfo.driverInfoURL": if e.complexity.DriverInfo.DriverInfoURL == nil { break } return e.complexity.DriverInfo.DriverInfoURL(childComplexity), true + case "DriverInfo.driverInstalled": + if e.complexity.DriverInfo.DriverInstalled == nil { + break + } + + return e.complexity.DriverInfo.DriverInstalled(childComplexity), true + case "DriverInfo.driverLibraries": + if e.complexity.DriverInfo.DriverLibraries == nil { + break + } + return e.complexity.DriverInfo.DriverLibraries(childComplexity), true case "DriverInfo.driverParameters": if e.complexity.DriverInfo.DriverParameters == nil { break } return e.complexity.DriverInfo.DriverParameters(childComplexity), true - case "DriverInfo.driverProperties": if e.complexity.DriverInfo.DriverProperties == nil { break } return e.complexity.DriverInfo.DriverProperties(childComplexity), true - case "DriverInfo.driverPropertiesURL": if e.complexity.DriverInfo.DriverPropertiesURL == nil { break } return e.complexity.DriverInfo.DriverPropertiesURL(childComplexity), true - case "DriverInfo.embedded": if e.complexity.DriverInfo.Embedded == nil { break } return e.complexity.DriverInfo.Embedded(childComplexity), true - case "DriverInfo.enabled": if e.complexity.DriverInfo.Enabled == nil { break } return e.complexity.DriverInfo.Enabled(childComplexity), true + case "DriverInfo.expertSettingsProperties": + if e.complexity.DriverInfo.ExpertSettingsProperties == nil { + break + } + return e.complexity.DriverInfo.ExpertSettingsProperties(childComplexity), true case "DriverInfo.id": if e.complexity.DriverInfo.ID == nil { break } return e.complexity.DriverInfo.ID(childComplexity), true - case "DriverInfo.icon": if e.complexity.DriverInfo.Icon == nil { break } return e.complexity.DriverInfo.Icon(childComplexity), true - case "DriverInfo.iconBig": if e.complexity.DriverInfo.IconBig == nil { break } return e.complexity.DriverInfo.IconBig(childComplexity), true - case "DriverInfo.license": if e.complexity.DriverInfo.License == nil { break } return e.complexity.DriverInfo.License(childComplexity), true - case "DriverInfo.licenseRequired": if e.complexity.DriverInfo.LicenseRequired == nil { break } return e.complexity.DriverInfo.LicenseRequired(childComplexity), true + case "DriverInfo.mainProperties": + if e.complexity.DriverInfo.MainProperties == nil { + break + } + return e.complexity.DriverInfo.MainProperties(childComplexity), true case "DriverInfo.name": if e.complexity.DriverInfo.Name == nil { break } return e.complexity.DriverInfo.Name(childComplexity), true - case "DriverInfo.promotedScore": if e.complexity.DriverInfo.PromotedScore == nil { break } return e.complexity.DriverInfo.PromotedScore(childComplexity), true - case "DriverInfo.providerId": if e.complexity.DriverInfo.ProviderID == nil { break } return e.complexity.DriverInfo.ProviderID(childComplexity), true - case "DriverInfo.providerProperties": if e.complexity.DriverInfo.ProviderProperties == nil { break } return e.complexity.DriverInfo.ProviderProperties(childComplexity), true + case "DriverInfo.requiresDatabaseName": + if e.complexity.DriverInfo.RequiresDatabaseName == nil { + break + } + return e.complexity.DriverInfo.RequiresDatabaseName(childComplexity), true case "DriverInfo.requiresServerName": if e.complexity.DriverInfo.RequiresServerName == nil { break } return e.complexity.DriverInfo.RequiresServerName(childComplexity), true + case "DriverInfo.safeEmbeddedDriver": + if e.complexity.DriverInfo.SafeEmbeddedDriver == nil { + break + } + return e.complexity.DriverInfo.SafeEmbeddedDriver(childComplexity), true case "DriverInfo.sampleURL": if e.complexity.DriverInfo.SampleURL == nil { break } return e.complexity.DriverInfo.SampleURL(childComplexity), true + case "DriverInfo.useCustomPage": + if e.complexity.DriverInfo.UseCustomPage == nil { + break + } + + return e.complexity.DriverInfo.UseCustomPage(childComplexity), true + + case "DriverLibraryInfo.id": + if e.complexity.DriverLibraryInfo.ID == nil { + break + } + + return e.complexity.DriverLibraryInfo.ID(childComplexity), true + case "DriverLibraryInfo.icon": + if e.complexity.DriverLibraryInfo.Icon == nil { + break + } + + return e.complexity.DriverLibraryInfo.Icon(childComplexity), true + case "DriverLibraryInfo.libraryFiles": + if e.complexity.DriverLibraryInfo.LibraryFiles == nil { + break + } + + return e.complexity.DriverLibraryInfo.LibraryFiles(childComplexity), true + case "DriverLibraryInfo.name": + if e.complexity.DriverLibraryInfo.Name == nil { + break + } + + return e.complexity.DriverLibraryInfo.Name(childComplexity), true + + case "DynamicTraceProperty.description": + if e.complexity.DynamicTraceProperty.Description == nil { + break + } + + return e.complexity.DynamicTraceProperty.Description(childComplexity), true + case "DynamicTraceProperty.name": + if e.complexity.DynamicTraceProperty.Name == nil { + break + } + + return e.complexity.DynamicTraceProperty.Name(childComplexity), true + case "DynamicTraceProperty.value": + if e.complexity.DynamicTraceProperty.Value == nil { + break + } + + return e.complexity.DynamicTraceProperty.Value(childComplexity), true + + case "FederatedAuthInfo.redirectLink": + if e.complexity.FederatedAuthInfo.RedirectLink == nil { + break + } + + return e.complexity.FederatedAuthInfo.RedirectLink(childComplexity), true + case "FederatedAuthInfo.taskInfo": + if e.complexity.FederatedAuthInfo.TaskInfo == nil { + break + } + + return e.complexity.FederatedAuthInfo.TaskInfo(childComplexity), true + + case "FederatedAuthResult.userTokens": + if e.complexity.FederatedAuthResult.UserTokens == nil { + break + } + + return e.complexity.FederatedAuthResult.UserTokens(childComplexity), true case "LogEntry.message": if e.complexity.LogEntry.Message == nil { @@ -2172,21 +2744,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.LogEntry.Message(childComplexity), true - case "LogEntry.stackTrace": if e.complexity.LogEntry.StackTrace == nil { break } return e.complexity.LogEntry.StackTrace(childComplexity), true - case "LogEntry.time": if e.complexity.LogEntry.Time == nil { break } return e.complexity.LogEntry.Time(childComplexity), true - case "LogEntry.type": if e.complexity.LogEntry.Type == nil { break @@ -2194,482 +2763,677 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.LogEntry.Type(childComplexity), true + case "LogoutInfo.redirectLinks": + if e.complexity.LogoutInfo.RedirectLinks == nil { + break + } + + return e.complexity.LogoutInfo.RedirectLinks(childComplexity), true + + case "Mutation.adminUpdateProductConfiguration": + if e.complexity.Mutation.AdminUpdateProductConfiguration == nil { + break + } + + args, err := ec.field_Mutation_adminUpdateProductConfiguration_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.AdminUpdateProductConfiguration(childComplexity, args["configuration"].(any)), true case "Mutation.asyncReadDataFromContainer": if e.complexity.Mutation.AsyncReadDataFromContainer == nil { break } - args, err := ec.field_Mutation_asyncReadDataFromContainer_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncReadDataFromContainer_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.AsyncReadDataFromContainer(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["containerNodePath"].(string), args["resultId"].(*string), args["filter"].(*model.SQLDataFilter), args["dataFormat"].(*model.ResultDataFormat)), true + return e.complexity.Mutation.AsyncReadDataFromContainer(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["containerNodePath"].(string), args["resultId"].(*string), args["filter"].(*model.SQLDataFilter), args["dataFormat"].(*model.ResultDataFormat)), true + case "Mutation.asyncSqlCommitTransaction": + if e.complexity.Mutation.AsyncSQLCommitTransaction == nil { + break + } + + args, err := ec.field_Mutation_asyncSqlCommitTransaction_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.AsyncSQLCommitTransaction(childComplexity, args["projectId"].(string), args["connectionId"].(string), args["contextId"].(string)), true case "Mutation.asyncSqlExecuteQuery": if e.complexity.Mutation.AsyncSQLExecuteQuery == nil { break } - args, err := ec.field_Mutation_asyncSqlExecuteQuery_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncSqlExecuteQuery_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.AsyncSQLExecuteQuery(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["sql"].(string), args["resultId"].(*string), args["filter"].(*model.SQLDataFilter), args["dataFormat"].(*model.ResultDataFormat)), true - + return e.complexity.Mutation.AsyncSQLExecuteQuery(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["sql"].(string), args["resultId"].(*string), args["filter"].(*model.SQLDataFilter), args["dataFormat"].(*model.ResultDataFormat), args["readLogs"].(*bool)), true case "Mutation.asyncSqlExecuteResults": if e.complexity.Mutation.AsyncSQLExecuteResults == nil { break } - args, err := ec.field_Mutation_asyncSqlExecuteResults_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncSqlExecuteResults_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.AsyncSQLExecuteResults(childComplexity, args["taskId"].(string)), true - case "Mutation.asyncSqlExplainExecutionPlan": if e.complexity.Mutation.AsyncSQLExplainExecutionPlan == nil { break } - args, err := ec.field_Mutation_asyncSqlExplainExecutionPlan_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncSqlExplainExecutionPlan_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.AsyncSQLExplainExecutionPlan(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["query"].(string), args["configuration"].(interface{})), true - + return e.complexity.Mutation.AsyncSQLExplainExecutionPlan(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["query"].(string), args["configuration"].(any)), true case "Mutation.asyncSqlExplainExecutionPlanResult": if e.complexity.Mutation.AsyncSQLExplainExecutionPlanResult == nil { break } - args, err := ec.field_Mutation_asyncSqlExplainExecutionPlanResult_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncSqlExplainExecutionPlanResult_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.AsyncSQLExplainExecutionPlanResult(childComplexity, args["taskId"].(string)), true + case "Mutation.asyncSqlRollbackTransaction": + if e.complexity.Mutation.AsyncSQLRollbackTransaction == nil { + break + } + + args, err := ec.field_Mutation_asyncSqlRollbackTransaction_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.AsyncSQLRollbackTransaction(childComplexity, args["projectId"].(string), args["connectionId"].(string), args["contextId"].(string)), true + case "Mutation.asyncSqlRowDataCount": + if e.complexity.Mutation.AsyncSQLRowDataCount == nil { + break + } + + args, err := ec.field_Mutation_asyncSqlRowDataCount_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.AsyncSQLRowDataCount(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string)), true + case "Mutation.asyncSqlRowDataCountResult": + if e.complexity.Mutation.AsyncSQLRowDataCountResult == nil { + break + } + + args, err := ec.field_Mutation_asyncSqlRowDataCountResult_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.AsyncSQLRowDataCountResult(childComplexity, args["taskId"].(string)), true + case "Mutation.asyncSqlSetAutoCommit": + if e.complexity.Mutation.AsyncSQLSetAutoCommit == nil { + break + } + + args, err := ec.field_Mutation_asyncSqlSetAutoCommit_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.AsyncSQLSetAutoCommit(childComplexity, args["projectId"].(string), args["connectionId"].(string), args["contextId"].(string), args["autoCommit"].(bool)), true case "Mutation.asyncTaskCancel": if e.complexity.Mutation.AsyncTaskCancel == nil { break } - args, err := ec.field_Mutation_asyncTaskCancel_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncTaskCancel_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.AsyncTaskCancel(childComplexity, args["id"].(string)), true - case "Mutation.asyncTaskInfo": if e.complexity.Mutation.AsyncTaskInfo == nil { break } - args, err := ec.field_Mutation_asyncTaskInfo_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncTaskInfo_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.AsyncTaskInfo(childComplexity, args["id"].(string), args["removeOnFinish"].(bool)), true - - case "Mutation.asyncTaskStatus": - if e.complexity.Mutation.AsyncTaskStatus == nil { + case "Mutation.asyncUpdateResultsDataBatch": + if e.complexity.Mutation.AsyncUpdateResultsDataBatch == nil { break } - args, err := ec.field_Mutation_asyncTaskStatus_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_asyncUpdateResultsDataBatch_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.AsyncTaskStatus(childComplexity, args["id"].(string)), true - + return e.complexity.Mutation.AsyncUpdateResultsDataBatch(childComplexity, args["projectId"].(string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["updatedRows"].([]*model.SQLResultRow), args["deletedRows"].([]*model.SQLResultRow), args["addedRows"].([]*model.SQLResultRow)), true case "Mutation.changeSessionLanguage": if e.complexity.Mutation.ChangeSessionLanguage == nil { break } - args, err := ec.field_Mutation_changeSessionLanguage_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_changeSessionLanguage_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.ChangeSessionLanguage(childComplexity, args["locale"].(*string)), true - case "Mutation.closeConnection": if e.complexity.Mutation.CloseConnection == nil { break } - args, err := ec.field_Mutation_closeConnection_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_closeConnection_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.CloseConnection(childComplexity, args["id"].(string)), true - + return e.complexity.Mutation.CloseConnection(childComplexity, args["id"].(string), args["projectId"].(*string)), true case "Mutation.closeSession": if e.complexity.Mutation.CloseSession == nil { break } return e.complexity.Mutation.CloseSession(childComplexity), true - case "Mutation.copyConnectionFromNode": if e.complexity.Mutation.CopyConnectionFromNode == nil { break } - args, err := ec.field_Mutation_copyConnectionFromNode_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_copyConnectionFromNode_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.CopyConnectionFromNode(childComplexity, args["nodePath"].(string), args["config"].(*model.ConnectionConfig)), true - + return e.complexity.Mutation.CopyConnectionFromNode(childComplexity, args["nodePath"].(string), args["config"].(*model.ConnectionConfig), args["projectId"].(*string)), true case "Mutation.createConnection": if e.complexity.Mutation.CreateConnection == nil { break } - args, err := ec.field_Mutation_createConnection_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_createConnection_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.CreateConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - + return e.complexity.Mutation.CreateConnection(childComplexity, args["config"].(model.ConnectionConfig), args["projectId"].(*string)), true case "Mutation.createConnectionFolder": if e.complexity.Mutation.CreateConnectionFolder == nil { break } - args, err := ec.field_Mutation_createConnectionFolder_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_createConnectionFolder_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.CreateConnectionFolder(childComplexity, args["parentFolderPath"].(*string), args["folderName"].(string)), true - - case "Mutation.createConnectionFromTemplate": - if e.complexity.Mutation.CreateConnectionFromTemplate == nil { + return e.complexity.Mutation.CreateConnectionFolder(childComplexity, args["parentFolderPath"].(*string), args["folderName"].(string), args["projectId"].(*string)), true + case "Mutation.deleteConnection": + if e.complexity.Mutation.DeleteConnection == nil { break } - args, err := ec.field_Mutation_createConnectionFromTemplate_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_deleteConnection_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.CreateConnectionFromTemplate(childComplexity, args["templateId"].(string), args["connectionName"].(*string)), true - - case "Mutation.deleteConnection": - if e.complexity.Mutation.DeleteConnection == nil { + return e.complexity.Mutation.DeleteConnection(childComplexity, args["id"].(string), args["projectId"].(*string)), true + case "Mutation.deleteConnectionFolder": + if e.complexity.Mutation.DeleteConnectionFolder == nil { break } - args, err := ec.field_Mutation_deleteConnection_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_deleteConnectionFolder_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.DeleteConnection(childComplexity, args["id"].(string)), true - - case "Mutation.deleteConnectionFolder": - if e.complexity.Mutation.DeleteConnectionFolder == nil { + return e.complexity.Mutation.DeleteConnectionFolder(childComplexity, args["folderPath"].(string), args["projectId"].(*string)), true + case "Mutation.federatedLogin": + if e.complexity.Mutation.FederatedLogin == nil { break } - args, err := ec.field_Mutation_deleteConnectionFolder_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_federatedLogin_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.DeleteConnectionFolder(childComplexity, args["folderPath"].(string)), true + return e.complexity.Mutation.FederatedLogin(childComplexity, args["provider"].(string), args["configuration"].(*string), args["linkUser"].(*bool), args["forceSessionsLogout"].(*bool)), true + case "Mutation.getTransactionLogInfo": + if e.complexity.Mutation.GetTransactionLogInfo == nil { + break + } + + args, err := ec.field_Mutation_getTransactionLogInfo_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.GetTransactionLogInfo(childComplexity, args["projectId"].(string), args["connectionId"].(string), args["contextId"].(string)), true case "Mutation.initConnection": if e.complexity.Mutation.InitConnection == nil { break } - args, err := ec.field_Mutation_initConnection_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_initConnection_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.InitConnection(childComplexity, args["id"].(string), args["credentials"].(interface{}), args["networkCredentials"].([]*model.NetworkHandlerConfigInput), args["saveCredentials"].(*bool)), true - + return e.complexity.Mutation.InitConnection(childComplexity, args["id"].(string), args["projectId"].(*string), args["credentials"].(any), args["networkCredentials"].([]*model.NetworkHandlerConfigInput), args["saveCredentials"].(*bool), args["sharedCredentials"].(*bool), args["selectedSecretId"].(*string)), true case "Mutation.navDeleteNodes": if e.complexity.Mutation.NavDeleteNodes == nil { break } - args, err := ec.field_Mutation_navDeleteNodes_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_navDeleteNodes_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.NavDeleteNodes(childComplexity, args["nodePaths"].([]string)), true - case "Mutation.navMoveNodesToFolder": if e.complexity.Mutation.NavMoveNodesToFolder == nil { break } - args, err := ec.field_Mutation_navMoveNodesToFolder_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_navMoveNodesToFolder_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.NavMoveNodesToFolder(childComplexity, args["nodePaths"].([]string), args["folderPath"].(string)), true + case "Mutation.navReloadNode": + if e.complexity.Mutation.NavReloadNode == nil { + break + } + + args, err := ec.field_Mutation_navReloadNode_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.NavReloadNode(childComplexity, args["nodePath"].(string)), true case "Mutation.navRenameNode": if e.complexity.Mutation.NavRenameNode == nil { break } - args, err := ec.field_Mutation_navRenameNode_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_navRenameNode_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.NavRenameNode(childComplexity, args["nodePath"].(string), args["newName"].(string)), true - - case "Mutation.openConnection": - if e.complexity.Mutation.OpenConnection == nil { + case "Mutation.navSetFolderFilter": + if e.complexity.Mutation.NavSetFolderFilter == nil { break } - args, err := ec.field_Mutation_openConnection_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_navSetFolderFilter_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.OpenConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - + return e.complexity.Mutation.NavSetFolderFilter(childComplexity, args["nodePath"].(string), args["include"].([]string), args["exclude"].([]string)), true case "Mutation.openSession": if e.complexity.Mutation.OpenSession == nil { break } - args, err := ec.field_Mutation_openSession_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_openSession_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.OpenSession(childComplexity, args["defaultLocale"].(*string)), true - case "Mutation.readLobValue": if e.complexity.Mutation.ReadLobValue == nil { break } - args, err := ec.field_Mutation_readLobValue_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_readLobValue_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.ReadLobValue(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["lobColumnIndex"].(int), args["row"].([]*model.SQLResultRow)), true - + return e.complexity.Mutation.ReadLobValue(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["lobColumnIndex"].(int), args["row"].([]*model.SQLResultRow)), true case "Mutation.refreshSessionConnections": if e.complexity.Mutation.RefreshSessionConnections == nil { break } return e.complexity.Mutation.RefreshSessionConnections(childComplexity), true + case "Mutation.rmAddProjectsPermissions": + if e.complexity.Mutation.RmAddProjectsPermissions == nil { + break + } + + args, err := ec.field_Mutation_rmAddProjectsPermissions_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.RmAddProjectsPermissions(childComplexity, args["projectIds"].([]string), args["subjectIds"].([]string), args["permissions"].([]string)), true + case "Mutation.rmCreateProject": + if e.complexity.Mutation.RmCreateProject == nil { + break + } + + args, err := ec.field_Mutation_rmCreateProject_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.RmCreateProject(childComplexity, args["projectId"].(*string), args["projectName"].(string), args["description"].(*string)), true case "Mutation.rmCreateResource": if e.complexity.Mutation.RmCreateResource == nil { break } - args, err := ec.field_Mutation_rmCreateResource_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_rmCreateResource_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.RmCreateResource(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["isFolder"].(bool)), true + case "Mutation.rmDeleteProject": + if e.complexity.Mutation.RmDeleteProject == nil { + break + } + + args, err := ec.field_Mutation_rmDeleteProject_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.RmDeleteProject(childComplexity, args["projectId"].(string)), true + case "Mutation.rmDeleteProjectsPermissions": + if e.complexity.Mutation.RmDeleteProjectsPermissions == nil { + break + } + + args, err := ec.field_Mutation_rmDeleteProjectsPermissions_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.RmDeleteProjectsPermissions(childComplexity, args["projectIds"].([]string), args["subjectIds"].([]string), args["permissions"].([]string)), true case "Mutation.rmDeleteResource": if e.complexity.Mutation.RmDeleteResource == nil { break } - args, err := ec.field_Mutation_rmDeleteResource_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_rmDeleteResource_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.RmDeleteResource(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["recursive"].(bool)), true - case "Mutation.rmMoveResource": if e.complexity.Mutation.RmMoveResource == nil { break } - args, err := ec.field_Mutation_rmMoveResource_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_rmMoveResource_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.RmMoveResource(childComplexity, args["projectId"].(string), args["oldResourcePath"].(string), args["newResourcePath"].(*string)), true + case "Mutation.rmSetProjectPermissions": + if e.complexity.Mutation.RmSetProjectPermissions == nil { + break + } + + args, err := ec.field_Mutation_rmSetProjectPermissions_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.RmSetProjectPermissions(childComplexity, args["projectId"].(string), args["permissions"].([]*model.RMSubjectProjectPermissions)), true + case "Mutation.rmSetResourceProperty": + if e.complexity.Mutation.RmSetResourceProperty == nil { + break + } + + args, err := ec.field_Mutation_rmSetResourceProperty_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.RmSetResourceProperty(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["name"].(string), args["value"].(*string)), true + case "Mutation.rmSetSubjectProjectPermissions": + if e.complexity.Mutation.RmSetSubjectProjectPermissions == nil { + break + } + + args, err := ec.field_Mutation_rmSetSubjectProjectPermissions_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.RmSetSubjectProjectPermissions(childComplexity, args["subjectId"].(string), args["permissions"].([]*model.RMProjectPermissions)), true case "Mutation.rmWriteResourceStringContent": if e.complexity.Mutation.RmWriteResourceStringContent == nil { break } - args, err := ec.field_Mutation_rmWriteResourceStringContent_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_rmWriteResourceStringContent_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.RmWriteResourceStringContent(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["data"].(string)), true - + return e.complexity.Mutation.RmWriteResourceStringContent(childComplexity, args["projectId"].(string), args["resourcePath"].(string), args["data"].(string), args["forceOverwrite"].(bool)), true case "Mutation.sqlContextCreate": if e.complexity.Mutation.SQLContextCreate == nil { break } - args, err := ec.field_Mutation_sqlContextCreate_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_sqlContextCreate_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.SQLContextCreate(childComplexity, args["connectionId"].(string), args["defaultCatalog"].(*string), args["defaultSchema"].(*string)), true - + return e.complexity.Mutation.SQLContextCreate(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["defaultCatalog"].(*string), args["defaultSchema"].(*string)), true case "Mutation.sqlContextDestroy": if e.complexity.Mutation.SQLContextDestroy == nil { break } - args, err := ec.field_Mutation_sqlContextDestroy_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_sqlContextDestroy_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.SQLContextDestroy(childComplexity, args["connectionId"].(string), args["contextId"].(string)), true - + return e.complexity.Mutation.SQLContextDestroy(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string)), true case "Mutation.sqlContextSetDefaults": if e.complexity.Mutation.SQLContextSetDefaults == nil { break } - args, err := ec.field_Mutation_sqlContextSetDefaults_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_sqlContextSetDefaults_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.SQLContextSetDefaults(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["defaultCatalog"].(*string), args["defaultSchema"].(*string)), true + case "Mutation.sqlGetDynamicTrace": + if e.complexity.Mutation.SQLGetDynamicTrace == nil { + break + } + + args, err := ec.field_Mutation_sqlGetDynamicTrace_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.SQLGetDynamicTrace(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string)), true + case "Mutation.sqlReadLobValue": + if e.complexity.Mutation.SQLReadLobValue == nil { + break + } + + args, err := ec.field_Mutation_sqlReadLobValue_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.SQLContextSetDefaults(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["defaultCatalog"].(*string), args["defaultSchema"].(*string)), true + return e.complexity.Mutation.SQLReadLobValue(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["lobColumnIndex"].(int), args["row"].(model.SQLResultRow)), true + case "Mutation.sqlReadStringValue": + if e.complexity.Mutation.SQLReadStringValue == nil { + break + } + + args, err := ec.field_Mutation_sqlReadStringValue_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.SQLReadStringValue(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["columnIndex"].(int), args["row"].(model.SQLResultRow)), true case "Mutation.sqlResultClose": if e.complexity.Mutation.SQLResultClose == nil { break } - args, err := ec.field_Mutation_sqlResultClose_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_sqlResultClose_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.SQLResultClose(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultId"].(string)), true - + return e.complexity.Mutation.SQLResultClose(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultId"].(string)), true case "Mutation.setConnectionNavigatorSettings": if e.complexity.Mutation.SetConnectionNavigatorSettings == nil { break } - args, err := ec.field_Mutation_setConnectionNavigatorSettings_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_setConnectionNavigatorSettings_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.SetConnectionNavigatorSettings(childComplexity, args["id"].(string), args["settings"].(model.NavigatorSettingsInput)), true - + return e.complexity.Mutation.SetConnectionNavigatorSettings(childComplexity, args["id"].(string), args["projectId"].(*string), args["settings"].(model.NavigatorSettingsInput)), true case "Mutation.setUserConfigurationParameter": if e.complexity.Mutation.SetUserConfigurationParameter == nil { break } - args, err := ec.field_Mutation_setUserConfigurationParameter_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_setUserConfigurationParameter_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.SetUserConfigurationParameter(childComplexity, args["name"].(string), args["value"].(interface{})), true + return e.complexity.Mutation.SetUserConfigurationParameter(childComplexity, args["name"].(string), args["value"].(any)), true + case "Mutation.setUserPreferences": + if e.complexity.Mutation.SetUserPreferences == nil { + break + } + + args, err := ec.field_Mutation_setUserPreferences_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Mutation.SetUserPreferences(childComplexity, args["preferences"].(any)), true case "Mutation.testConnection": if e.complexity.Mutation.TestConnection == nil { break } - args, err := ec.field_Mutation_testConnection_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_testConnection_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.TestConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - + return e.complexity.Mutation.TestConnection(childComplexity, args["config"].(model.ConnectionConfig), args["projectId"].(*string)), true case "Mutation.testNetworkHandler": if e.complexity.Mutation.TestNetworkHandler == nil { break } - args, err := ec.field_Mutation_testNetworkHandler_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_testNetworkHandler_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Mutation.TestNetworkHandler(childComplexity, args["config"].(model.NetworkHandlerConfigInput)), true - case "Mutation.touchSession": if e.complexity.Mutation.TouchSession == nil { break } return e.complexity.Mutation.TouchSession(childComplexity), true - case "Mutation.updateConnection": if e.complexity.Mutation.UpdateConnection == nil { break } - args, err := ec.field_Mutation_updateConnection_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_updateConnection_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.UpdateConnection(childComplexity, args["config"].(model.ConnectionConfig)), true - + return e.complexity.Mutation.UpdateConnection(childComplexity, args["config"].(model.ConnectionConfig), args["projectId"].(*string)), true case "Mutation.updateResultsDataBatch": if e.complexity.Mutation.UpdateResultsDataBatch == nil { break } - args, err := ec.field_Mutation_updateResultsDataBatch_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_updateResultsDataBatch_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.UpdateResultsDataBatch(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["updatedRows"].([]*model.SQLResultRow), args["deletedRows"].([]*model.SQLResultRow), args["addedRows"].([]*model.SQLResultRow)), true - + return e.complexity.Mutation.UpdateResultsDataBatch(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["updatedRows"].([]*model.SQLResultRow), args["deletedRows"].([]*model.SQLResultRow), args["addedRows"].([]*model.SQLResultRow)), true case "Mutation.updateResultsDataBatchScript": if e.complexity.Mutation.UpdateResultsDataBatchScript == nil { break } - args, err := ec.field_Mutation_updateResultsDataBatchScript_args(context.TODO(), rawArgs) + args, err := ec.field_Mutation_updateResultsDataBatchScript_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Mutation.UpdateResultsDataBatchScript(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["updatedRows"].([]*model.SQLResultRow), args["deletedRows"].([]*model.SQLResultRow), args["addedRows"].([]*model.SQLResultRow)), true + return e.complexity.Mutation.UpdateResultsDataBatchScript(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["updatedRows"].([]*model.SQLResultRow), args["deletedRows"].([]*model.SQLResultRow), args["addedRows"].([]*model.SQLResultRow)), true + case "Mutation.updateSession": + if e.complexity.Mutation.UpdateSession == nil { + break + } + + return e.complexity.Mutation.UpdateSession(childComplexity), true + + case "NavigatorNodeFilter.exclude": + if e.complexity.NavigatorNodeFilter.Exclude == nil { + break + } + + return e.complexity.NavigatorNodeFilter.Exclude(childComplexity), true + case "NavigatorNodeFilter.include": + if e.complexity.NavigatorNodeFilter.Include == nil { + break + } + + return e.complexity.NavigatorNodeFilter.Include(childComplexity), true case "NavigatorNodeInfo.description": if e.complexity.NavigatorNodeInfo.Description == nil { @@ -2677,90 +3441,114 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.NavigatorNodeInfo.Description(childComplexity), true - case "NavigatorNodeInfo.features": if e.complexity.NavigatorNodeInfo.Features == nil { break } return e.complexity.NavigatorNodeInfo.Features(childComplexity), true + case "NavigatorNodeInfo.filter": + if e.complexity.NavigatorNodeInfo.Filter == nil { + break + } + + return e.complexity.NavigatorNodeInfo.Filter(childComplexity), true + case "NavigatorNodeInfo.filtered": + if e.complexity.NavigatorNodeInfo.Filtered == nil { + break + } + return e.complexity.NavigatorNodeInfo.Filtered(childComplexity), true case "NavigatorNodeInfo.folder": if e.complexity.NavigatorNodeInfo.Folder == nil { break } return e.complexity.NavigatorNodeInfo.Folder(childComplexity), true - case "NavigatorNodeInfo.fullName": if e.complexity.NavigatorNodeInfo.FullName == nil { break } return e.complexity.NavigatorNodeInfo.FullName(childComplexity), true - case "NavigatorNodeInfo.hasChildren": if e.complexity.NavigatorNodeInfo.HasChildren == nil { break } return e.complexity.NavigatorNodeInfo.HasChildren(childComplexity), true - case "NavigatorNodeInfo.id": if e.complexity.NavigatorNodeInfo.ID == nil { break } return e.complexity.NavigatorNodeInfo.ID(childComplexity), true - case "NavigatorNodeInfo.icon": if e.complexity.NavigatorNodeInfo.Icon == nil { break } return e.complexity.NavigatorNodeInfo.Icon(childComplexity), true - case "NavigatorNodeInfo.inline": if e.complexity.NavigatorNodeInfo.Inline == nil { break } return e.complexity.NavigatorNodeInfo.Inline(childComplexity), true - case "NavigatorNodeInfo.name": if e.complexity.NavigatorNodeInfo.Name == nil { break } return e.complexity.NavigatorNodeInfo.Name(childComplexity), true - case "NavigatorNodeInfo.navigable": if e.complexity.NavigatorNodeInfo.Navigable == nil { break } return e.complexity.NavigatorNodeInfo.Navigable(childComplexity), true - case "NavigatorNodeInfo.nodeDetails": if e.complexity.NavigatorNodeInfo.NodeDetails == nil { break } return e.complexity.NavigatorNodeInfo.NodeDetails(childComplexity), true - case "NavigatorNodeInfo.nodeType": if e.complexity.NavigatorNodeInfo.NodeType == nil { break } return e.complexity.NavigatorNodeInfo.NodeType(childComplexity), true - case "NavigatorNodeInfo.object": if e.complexity.NavigatorNodeInfo.Object == nil { break } return e.complexity.NavigatorNodeInfo.Object(childComplexity), true + case "NavigatorNodeInfo.objectId": + if e.complexity.NavigatorNodeInfo.ObjectID == nil { + break + } + + return e.complexity.NavigatorNodeInfo.ObjectID(childComplexity), true + case "NavigatorNodeInfo.plainName": + if e.complexity.NavigatorNodeInfo.PlainName == nil { + break + } + + return e.complexity.NavigatorNodeInfo.PlainName(childComplexity), true + case "NavigatorNodeInfo.projectId": + if e.complexity.NavigatorNodeInfo.ProjectID == nil { + break + } + + return e.complexity.NavigatorNodeInfo.ProjectID(childComplexity), true + case "NavigatorNodeInfo.uri": + if e.complexity.NavigatorNodeInfo.URI == nil { + break + } + + return e.complexity.NavigatorNodeInfo.URI(childComplexity), true case "NavigatorSettings.hideFolders": if e.complexity.NavigatorSettings.HideFolders == nil { @@ -2768,42 +3556,36 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.NavigatorSettings.HideFolders(childComplexity), true - case "NavigatorSettings.hideSchemas": if e.complexity.NavigatorSettings.HideSchemas == nil { break } return e.complexity.NavigatorSettings.HideSchemas(childComplexity), true - case "NavigatorSettings.hideVirtualModel": if e.complexity.NavigatorSettings.HideVirtualModel == nil { break } return e.complexity.NavigatorSettings.HideVirtualModel(childComplexity), true - case "NavigatorSettings.mergeEntities": if e.complexity.NavigatorSettings.MergeEntities == nil { break } return e.complexity.NavigatorSettings.MergeEntities(childComplexity), true - case "NavigatorSettings.showOnlyEntities": if e.complexity.NavigatorSettings.ShowOnlyEntities == nil { break } return e.complexity.NavigatorSettings.ShowOnlyEntities(childComplexity), true - case "NavigatorSettings.showSystemObjects": if e.complexity.NavigatorSettings.ShowSystemObjects == nil { break } return e.complexity.NavigatorSettings.ShowSystemObjects(childComplexity), true - case "NavigatorSettings.showUtilityObjects": if e.complexity.NavigatorSettings.ShowUtilityObjects == nil { break @@ -2817,14 +3599,12 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.NetworkEndpointInfo.ClientVersion(childComplexity), true - case "NetworkEndpointInfo.message": if e.complexity.NetworkEndpointInfo.Message == nil { break } return e.complexity.NetworkEndpointInfo.Message(childComplexity), true - case "NetworkEndpointInfo.serverVersion": if e.complexity.NetworkEndpointInfo.ServerVersion == nil { break @@ -2838,49 +3618,48 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.NetworkHandlerConfig.AuthType(childComplexity), true - case "NetworkHandlerConfig.enabled": if e.complexity.NetworkHandlerConfig.Enabled == nil { break } return e.complexity.NetworkHandlerConfig.Enabled(childComplexity), true - case "NetworkHandlerConfig.id": if e.complexity.NetworkHandlerConfig.ID == nil { break } return e.complexity.NetworkHandlerConfig.ID(childComplexity), true - case "NetworkHandlerConfig.key": if e.complexity.NetworkHandlerConfig.Key == nil { break } return e.complexity.NetworkHandlerConfig.Key(childComplexity), true - case "NetworkHandlerConfig.password": if e.complexity.NetworkHandlerConfig.Password == nil { break } return e.complexity.NetworkHandlerConfig.Password(childComplexity), true - case "NetworkHandlerConfig.properties": if e.complexity.NetworkHandlerConfig.Properties == nil { break } return e.complexity.NetworkHandlerConfig.Properties(childComplexity), true - case "NetworkHandlerConfig.savePassword": if e.complexity.NetworkHandlerConfig.SavePassword == nil { break } return e.complexity.NetworkHandlerConfig.SavePassword(childComplexity), true + case "NetworkHandlerConfig.secureProperties": + if e.complexity.NetworkHandlerConfig.SecureProperties == nil { + break + } + return e.complexity.NetworkHandlerConfig.SecureProperties(childComplexity), true case "NetworkHandlerConfig.userName": if e.complexity.NetworkHandlerConfig.UserName == nil { break @@ -2894,42 +3673,36 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.NetworkHandlerDescriptor.CodeName(childComplexity), true - case "NetworkHandlerDescriptor.description": if e.complexity.NetworkHandlerDescriptor.Description == nil { break } return e.complexity.NetworkHandlerDescriptor.Description(childComplexity), true - case "NetworkHandlerDescriptor.id": if e.complexity.NetworkHandlerDescriptor.ID == nil { break } return e.complexity.NetworkHandlerDescriptor.ID(childComplexity), true - case "NetworkHandlerDescriptor.label": if e.complexity.NetworkHandlerDescriptor.Label == nil { break } return e.complexity.NetworkHandlerDescriptor.Label(childComplexity), true - case "NetworkHandlerDescriptor.properties": if e.complexity.NetworkHandlerDescriptor.Properties == nil { break } return e.complexity.NetworkHandlerDescriptor.Properties(childComplexity), true - case "NetworkHandlerDescriptor.secured": if e.complexity.NetworkHandlerDescriptor.Secured == nil { break } return e.complexity.NetworkHandlerDescriptor.Secured(childComplexity), true - case "NetworkHandlerDescriptor.type": if e.complexity.NetworkHandlerDescriptor.Type == nil { break @@ -2943,35 +3716,30 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ObjectDescriptor.Description(childComplexity), true - case "ObjectDescriptor.displayName": if e.complexity.ObjectDescriptor.DisplayName == nil { break } return e.complexity.ObjectDescriptor.DisplayName(childComplexity), true - case "ObjectDescriptor.fullName": if e.complexity.ObjectDescriptor.FullName == nil { break } return e.complexity.ObjectDescriptor.FullName(childComplexity), true - case "ObjectDescriptor.id": if e.complexity.ObjectDescriptor.ID == nil { break } return e.complexity.ObjectDescriptor.ID(childComplexity), true - case "ObjectDescriptor.uniqueName": if e.complexity.ObjectDescriptor.UniqueName == nil { break } return e.complexity.ObjectDescriptor.UniqueName(childComplexity), true - case "ObjectDescriptor.value": if e.complexity.ObjectDescriptor.Value == nil { break @@ -2985,21 +3753,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ObjectDetails.Description(childComplexity), true - case "ObjectDetails.displayName": if e.complexity.ObjectDetails.DisplayName == nil { break } return e.complexity.ObjectDetails.DisplayName(childComplexity), true - case "ObjectDetails.id": if e.complexity.ObjectDetails.ID == nil { break } return e.complexity.ObjectDetails.ID(childComplexity), true - case "ObjectDetails.value": if e.complexity.ObjectDetails.Value == nil { break @@ -3013,35 +3778,30 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ObjectOrigin.Configuration(childComplexity), true - case "ObjectOrigin.details": if e.complexity.ObjectOrigin.Details == nil { break } return e.complexity.ObjectOrigin.Details(childComplexity), true - case "ObjectOrigin.displayName": if e.complexity.ObjectOrigin.DisplayName == nil { break } return e.complexity.ObjectOrigin.DisplayName(childComplexity), true - case "ObjectOrigin.icon": if e.complexity.ObjectOrigin.Icon == nil { break } return e.complexity.ObjectOrigin.Icon(childComplexity), true - case "ObjectOrigin.subType": if e.complexity.ObjectOrigin.SubType == nil { break } return e.complexity.ObjectOrigin.SubType(childComplexity), true - case "ObjectOrigin.type": if e.complexity.ObjectOrigin.Type == nil { break @@ -3055,70 +3815,90 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ObjectPropertyInfo.Category(childComplexity), true + case "ObjectPropertyInfo.conditions": + if e.complexity.ObjectPropertyInfo.Conditions == nil { + break + } + return e.complexity.ObjectPropertyInfo.Conditions(childComplexity), true case "ObjectPropertyInfo.dataType": if e.complexity.ObjectPropertyInfo.DataType == nil { break } return e.complexity.ObjectPropertyInfo.DataType(childComplexity), true - case "ObjectPropertyInfo.defaultValue": if e.complexity.ObjectPropertyInfo.DefaultValue == nil { break } return e.complexity.ObjectPropertyInfo.DefaultValue(childComplexity), true - case "ObjectPropertyInfo.description": if e.complexity.ObjectPropertyInfo.Description == nil { break } return e.complexity.ObjectPropertyInfo.Description(childComplexity), true - case "ObjectPropertyInfo.displayName": if e.complexity.ObjectPropertyInfo.DisplayName == nil { break } return e.complexity.ObjectPropertyInfo.DisplayName(childComplexity), true - case "ObjectPropertyInfo.features": if e.complexity.ObjectPropertyInfo.Features == nil { break } return e.complexity.ObjectPropertyInfo.Features(childComplexity), true + case "ObjectPropertyInfo.hint": + if e.complexity.ObjectPropertyInfo.Hint == nil { + break + } + return e.complexity.ObjectPropertyInfo.Hint(childComplexity), true case "ObjectPropertyInfo.id": if e.complexity.ObjectPropertyInfo.ID == nil { break } return e.complexity.ObjectPropertyInfo.ID(childComplexity), true - case "ObjectPropertyInfo.length": if e.complexity.ObjectPropertyInfo.Length == nil { break } return e.complexity.ObjectPropertyInfo.Length(childComplexity), true - case "ObjectPropertyInfo.order": if e.complexity.ObjectPropertyInfo.Order == nil { break } return e.complexity.ObjectPropertyInfo.Order(childComplexity), true + case "ObjectPropertyInfo.required": + if e.complexity.ObjectPropertyInfo.Required == nil { + break + } + + return e.complexity.ObjectPropertyInfo.Required(childComplexity), true + case "ObjectPropertyInfo.scopes": + if e.complexity.ObjectPropertyInfo.Scopes == nil { + break + } + + return e.complexity.ObjectPropertyInfo.Scopes(childComplexity), true + case "ObjectPropertyInfo.supportedConfigurationTypes": + if e.complexity.ObjectPropertyInfo.SupportedConfigurationTypes == nil { + break + } + return e.complexity.ObjectPropertyInfo.SupportedConfigurationTypes(childComplexity), true case "ObjectPropertyInfo.validValues": if e.complexity.ObjectPropertyInfo.ValidValues == nil { break } return e.complexity.ObjectPropertyInfo.ValidValues(childComplexity), true - case "ObjectPropertyInfo.value": if e.complexity.ObjectPropertyInfo.Value == nil { break @@ -3126,55 +3906,79 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.ObjectPropertyInfo.Value(childComplexity), true + case "PasswordPolicyConfig.minLength": + if e.complexity.PasswordPolicyConfig.MinLength == nil { + break + } + + return e.complexity.PasswordPolicyConfig.MinLength(childComplexity), true + case "PasswordPolicyConfig.minNumberCount": + if e.complexity.PasswordPolicyConfig.MinNumberCount == nil { + break + } + + return e.complexity.PasswordPolicyConfig.MinNumberCount(childComplexity), true + case "PasswordPolicyConfig.minSymbolCount": + if e.complexity.PasswordPolicyConfig.MinSymbolCount == nil { + break + } + + return e.complexity.PasswordPolicyConfig.MinSymbolCount(childComplexity), true + case "PasswordPolicyConfig.requireMixedCase": + if e.complexity.PasswordPolicyConfig.RequireMixedCase == nil { + break + } + + return e.complexity.PasswordPolicyConfig.RequireMixedCase(childComplexity), true + case "ProductInfo.buildTime": if e.complexity.ProductInfo.BuildTime == nil { break } return e.complexity.ProductInfo.BuildTime(childComplexity), true - case "ProductInfo.description": if e.complexity.ProductInfo.Description == nil { break } return e.complexity.ProductInfo.Description(childComplexity), true - case "ProductInfo.id": if e.complexity.ProductInfo.ID == nil { break } return e.complexity.ProductInfo.ID(childComplexity), true - case "ProductInfo.latestVersionInfo": if e.complexity.ProductInfo.LatestVersionInfo == nil { break } return e.complexity.ProductInfo.LatestVersionInfo(childComplexity), true - case "ProductInfo.licenseInfo": if e.complexity.ProductInfo.LicenseInfo == nil { break } return e.complexity.ProductInfo.LicenseInfo(childComplexity), true - case "ProductInfo.name": if e.complexity.ProductInfo.Name == nil { break } return e.complexity.ProductInfo.Name(childComplexity), true + case "ProductInfo.productPurchaseURL": + if e.complexity.ProductInfo.ProductPurchaseURL == nil { + break + } + return e.complexity.ProductInfo.ProductPurchaseURL(childComplexity), true case "ProductInfo.releaseTime": if e.complexity.ProductInfo.ReleaseTime == nil { break } return e.complexity.ProductInfo.ReleaseTime(childComplexity), true - case "ProductInfo.version": if e.complexity.ProductInfo.Version == nil { break @@ -3182,828 +3986,984 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.ProductInfo.Version(childComplexity), true + case "ProductSettings.groups": + if e.complexity.ProductSettings.Groups == nil { + break + } + + return e.complexity.ProductSettings.Groups(childComplexity), true + case "ProductSettings.settings": + if e.complexity.ProductSettings.Settings == nil { + break + } + + return e.complexity.ProductSettings.Settings(childComplexity), true + + case "ProductSettingsGroup.displayName": + if e.complexity.ProductSettingsGroup.DisplayName == nil { + break + } + + return e.complexity.ProductSettingsGroup.DisplayName(childComplexity), true + case "ProductSettingsGroup.id": + if e.complexity.ProductSettingsGroup.ID == nil { + break + } + + return e.complexity.ProductSettingsGroup.ID(childComplexity), true + + case "ProjectInfo.canEditDataSources": + if e.complexity.ProjectInfo.CanEditDataSources == nil { + break + } + + return e.complexity.ProjectInfo.CanEditDataSources(childComplexity), true + case "ProjectInfo.canEditResources": + if e.complexity.ProjectInfo.CanEditResources == nil { + break + } + + return e.complexity.ProjectInfo.CanEditResources(childComplexity), true + case "ProjectInfo.canViewDataSources": + if e.complexity.ProjectInfo.CanViewDataSources == nil { + break + } + + return e.complexity.ProjectInfo.CanViewDataSources(childComplexity), true + case "ProjectInfo.canViewResources": + if e.complexity.ProjectInfo.CanViewResources == nil { + break + } + + return e.complexity.ProjectInfo.CanViewResources(childComplexity), true + case "ProjectInfo.description": + if e.complexity.ProjectInfo.Description == nil { + break + } + + return e.complexity.ProjectInfo.Description(childComplexity), true + case "ProjectInfo.global": + if e.complexity.ProjectInfo.Global == nil { + break + } + + return e.complexity.ProjectInfo.Global(childComplexity), true + case "ProjectInfo.id": + if e.complexity.ProjectInfo.ID == nil { + break + } + + return e.complexity.ProjectInfo.ID(childComplexity), true + case "ProjectInfo.name": + if e.complexity.ProjectInfo.Name == nil { + break + } + + return e.complexity.ProjectInfo.Name(childComplexity), true + case "ProjectInfo.resourceTypes": + if e.complexity.ProjectInfo.ResourceTypes == nil { + break + } + + return e.complexity.ProjectInfo.ResourceTypes(childComplexity), true + case "ProjectInfo.shared": + if e.complexity.ProjectInfo.Shared == nil { + break + } + + return e.complexity.ProjectInfo.Shared(childComplexity), true + case "Query.activeUser": if e.complexity.Query.ActiveUser == nil { break } return e.complexity.Query.ActiveUser(childComplexity), true - - case "Query.allConnections": - if e.complexity.Query.AllConnections == nil { + case "Query.addConnectionsAccess": + if e.complexity.Query.AddConnectionsAccess == nil { break } - args, err := ec.field_Query_allConnections_args(context.TODO(), rawArgs) + args, err := ec.field_Query_addConnectionsAccess_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.AllConnections(childComplexity, args["id"].(*string)), true + return e.complexity.Query.AddConnectionsAccess(childComplexity, args["projectId"].(string), args["connectionIds"].([]string), args["subjects"].([]string)), true + case "Query.adminUserInfo": + if e.complexity.Query.AdminUserInfo == nil { + break + } + + args, err := ec.field_Query_adminUserInfo_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Query.AdminUserInfo(childComplexity, args["userId"].(string)), true case "Query.authChangeLocalPassword": if e.complexity.Query.AuthChangeLocalPassword == nil { break } - args, err := ec.field_Query_authChangeLocalPassword_args(context.TODO(), rawArgs) + args, err := ec.field_Query_authChangeLocalPassword_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.AuthChangeLocalPassword(childComplexity, args["oldPassword"].(string), args["newPassword"].(string)), true - case "Query.authLogin": if e.complexity.Query.AuthLogin == nil { break } - args, err := ec.field_Query_authLogin_args(context.TODO(), rawArgs) + args, err := ec.field_Query_authLogin_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.AuthLogin(childComplexity, args["provider"].(string), args["configuration"].(*string), args["credentials"].(interface{}), args["linkUser"].(*bool)), true - + return e.complexity.Query.AuthLogin(childComplexity, args["provider"].(string), args["configuration"].(*string), args["credentials"].(any), args["linkUser"].(*bool), args["forceSessionsLogout"].(*bool)), true case "Query.authLogout": if e.complexity.Query.AuthLogout == nil { break } - args, err := ec.field_Query_authLogout_args(context.TODO(), rawArgs) + args, err := ec.field_Query_authLogout_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.AuthLogout(childComplexity, args["provider"].(*string), args["configuration"].(*string)), true + case "Query.authLogoutExtended": + if e.complexity.Query.AuthLogoutExtended == nil { + break + } + + args, err := ec.field_Query_authLogoutExtended_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Query.AuthLogoutExtended(childComplexity, args["provider"].(*string), args["configuration"].(*string)), true case "Query.authModels": if e.complexity.Query.AuthModels == nil { break } return e.complexity.Query.AuthModels(childComplexity), true - case "Query.authProviders": if e.complexity.Query.AuthProviders == nil { break } return e.complexity.Query.AuthProviders(childComplexity), true - case "Query.authUpdateStatus": if e.complexity.Query.AuthUpdateStatus == nil { break } - args, err := ec.field_Query_authUpdateStatus_args(context.TODO(), rawArgs) + args, err := ec.field_Query_authUpdateStatus_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.AuthUpdateStatus(childComplexity, args["authId"].(string), args["linkUser"].(*bool)), true - case "Query.configureServer": if e.complexity.Query.ConfigureServer == nil { break } - args, err := ec.field_Query_configureServer_args(context.TODO(), rawArgs) + args, err := ec.field_Query_configureServer_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.ConfigureServer(childComplexity, args["configuration"].(model.ServerConfigInput)), true - case "Query.connectionFolders": if e.complexity.Query.ConnectionFolders == nil { break } - args, err := ec.field_Query_connectionFolders_args(context.TODO(), rawArgs) + args, err := ec.field_Query_connectionFolders_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.ConnectionFolders(childComplexity, args["path"].(*string)), true - + return e.complexity.Query.ConnectionFolders(childComplexity, args["projectId"].(*string), args["path"].(*string)), true case "Query.connectionInfo": if e.complexity.Query.ConnectionInfo == nil { break } - args, err := ec.field_Query_connectionInfo_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ConnectionInfo(childComplexity, args["id"].(string)), true - - case "Query.connectionState": - if e.complexity.Query.ConnectionState == nil { - break - } - - args, err := ec.field_Query_connectionState_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.ConnectionState(childComplexity, args["id"].(string)), true - - case "Query.copyConnectionConfiguration": - if e.complexity.Query.CopyConnectionConfiguration == nil { - break - } - - args, err := ec.field_Query_copyConnectionConfiguration_args(context.TODO(), rawArgs) + args, err := ec.field_Query_connectionInfo_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.CopyConnectionConfiguration(childComplexity, args["nodePath"].(string), args["config"].(*model.ConnectionConfig)), true - - case "Query.createConnectionConfiguration": - if e.complexity.Query.CreateConnectionConfiguration == nil { - break - } - - args, err := ec.field_Query_createConnectionConfiguration_args(context.TODO(), rawArgs) - if err != nil { - return 0, false - } - - return e.complexity.Query.CreateConnectionConfiguration(childComplexity, args["config"].(model.ConnectionConfig)), true - - case "Query.createRole": - if e.complexity.Query.CreateRole == nil { + return e.complexity.Query.ConnectionInfo(childComplexity, args["projectId"].(string), args["id"].(string)), true + case "Query.createTeam": + if e.complexity.Query.CreateTeam == nil { break } - args, err := ec.field_Query_createRole_args(context.TODO(), rawArgs) + args, err := ec.field_Query_createTeam_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.CreateRole(childComplexity, args["roleId"].(string), args["roleName"].(*string), args["description"].(*string)), true - + return e.complexity.Query.CreateTeam(childComplexity, args["teamId"].(string), args["teamName"].(*string), args["description"].(*string)), true case "Query.createUser": if e.complexity.Query.CreateUser == nil { break } - args, err := ec.field_Query_createUser_args(context.TODO(), rawArgs) + args, err := ec.field_Query_createUser_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.CreateUser(childComplexity, args["userId"].(string)), true + return e.complexity.Query.CreateUser(childComplexity, args["userId"].(string), args["enabled"].(bool), args["authRole"].(*string)), true + case "Query.dataTransferAvailableImportStreamProcessors": + if e.complexity.Query.DataTransferAvailableImportStreamProcessors == nil { + break + } + return e.complexity.Query.DataTransferAvailableImportStreamProcessors(childComplexity), true case "Query.dataTransferAvailableStreamProcessors": if e.complexity.Query.DataTransferAvailableStreamProcessors == nil { break } return e.complexity.Query.DataTransferAvailableStreamProcessors(childComplexity), true + case "Query.dataTransferDefaultExportSettings": + if e.complexity.Query.DataTransferDefaultExportSettings == nil { + break + } + return e.complexity.Query.DataTransferDefaultExportSettings(childComplexity), true case "Query.dataTransferExportDataFromContainer": if e.complexity.Query.DataTransferExportDataFromContainer == nil { break } - args, err := ec.field_Query_dataTransferExportDataFromContainer_args(context.TODO(), rawArgs) + args, err := ec.field_Query_dataTransferExportDataFromContainer_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.DataTransferExportDataFromContainer(childComplexity, args["connectionId"].(string), args["containerNodePath"].(string), args["parameters"].(model.DataTransferParameters)), true - + return e.complexity.Query.DataTransferExportDataFromContainer(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["containerNodePath"].(string), args["parameters"].(model.DataTransferParameters)), true case "Query.dataTransferExportDataFromResults": if e.complexity.Query.DataTransferExportDataFromResults == nil { break } - args, err := ec.field_Query_dataTransferExportDataFromResults_args(context.TODO(), rawArgs) + args, err := ec.field_Query_dataTransferExportDataFromResults_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.DataTransferExportDataFromResults(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["parameters"].(model.DataTransferParameters)), true - + return e.complexity.Query.DataTransferExportDataFromResults(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["parameters"].(model.DataTransferParameters)), true case "Query.dataTransferRemoveDataFile": if e.complexity.Query.DataTransferRemoveDataFile == nil { break } - args, err := ec.field_Query_dataTransferRemoveDataFile_args(context.TODO(), rawArgs) + args, err := ec.field_Query_dataTransferRemoveDataFile_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.DataTransferRemoveDataFile(childComplexity, args["dataFileId"].(string)), true - case "Query.deleteAuthProviderConfiguration": if e.complexity.Query.DeleteAuthProviderConfiguration == nil { break } - args, err := ec.field_Query_deleteAuthProviderConfiguration_args(context.TODO(), rawArgs) + args, err := ec.field_Query_deleteAuthProviderConfiguration_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.DeleteAuthProviderConfiguration(childComplexity, args["id"].(string)), true - - case "Query.deleteConnectionConfiguration": - if e.complexity.Query.DeleteConnectionConfiguration == nil { + case "Query.deleteConnectionsAccess": + if e.complexity.Query.DeleteConnectionsAccess == nil { break } - args, err := ec.field_Query_deleteConnectionConfiguration_args(context.TODO(), rawArgs) + args, err := ec.field_Query_deleteConnectionsAccess_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.DeleteConnectionConfiguration(childComplexity, args["id"].(string)), true - - case "Query.deleteRole": - if e.complexity.Query.DeleteRole == nil { + return e.complexity.Query.DeleteConnectionsAccess(childComplexity, args["projectId"].(string), args["connectionIds"].([]string), args["subjects"].([]string)), true + case "Query.deleteTeam": + if e.complexity.Query.DeleteTeam == nil { break } - args, err := ec.field_Query_deleteRole_args(context.TODO(), rawArgs) + args, err := ec.field_Query_deleteTeam_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.DeleteRole(childComplexity, args["roleId"].(string)), true - + return e.complexity.Query.DeleteTeam(childComplexity, args["teamId"].(string), args["force"].(*bool)), true case "Query.deleteUser": if e.complexity.Query.DeleteUser == nil { break } - args, err := ec.field_Query_deleteUser_args(context.TODO(), rawArgs) + args, err := ec.field_Query_deleteUser_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.DeleteUser(childComplexity, args["userId"].(string)), true + case "Query.deleteUserCredentials": + if e.complexity.Query.DeleteUserCredentials == nil { + break + } + + args, err := ec.field_Query_deleteUserCredentials_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Query.DeleteUserCredentials(childComplexity, args["userId"].(string), args["providerId"].(string)), true case "Query.deleteUserMetaParameter": if e.complexity.Query.DeleteUserMetaParameter == nil { break } - args, err := ec.field_Query_deleteUserMetaParameter_args(context.TODO(), rawArgs) + args, err := ec.field_Query_deleteUserMetaParameter_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.DeleteUserMetaParameter(childComplexity, args["id"].(string)), true - case "Query.driverList": if e.complexity.Query.DriverList == nil { break } - args, err := ec.field_Query_driverList_args(context.TODO(), rawArgs) + args, err := ec.field_Query_driverList_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.DriverList(childComplexity, args["id"].(*string)), true - case "Query.enableUser": if e.complexity.Query.EnableUser == nil { break } - args, err := ec.field_Query_enableUser_args(context.TODO(), rawArgs) + args, err := ec.field_Query_enableUser_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.EnableUser(childComplexity, args["userId"].(string), args["enabled"].(bool)), true + case "Query.federatedAuthTaskResult": + if e.complexity.Query.FederatedAuthTaskResult == nil { + break + } + + args, err := ec.field_Query_federatedAuthTaskResult_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Query.FederatedAuthTaskResult(childComplexity, args["taskId"].(string)), true case "Query.getConnectionSubjectAccess": if e.complexity.Query.GetConnectionSubjectAccess == nil { break } - args, err := ec.field_Query_getConnectionSubjectAccess_args(context.TODO(), rawArgs) + args, err := ec.field_Query_getConnectionSubjectAccess_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.GetConnectionSubjectAccess(childComplexity, args["connectionId"].(*string)), true - + return e.complexity.Query.GetConnectionSubjectAccess(childComplexity, args["projectId"].(string), args["connectionId"].(*string)), true case "Query.getSubjectConnectionAccess": if e.complexity.Query.GetSubjectConnectionAccess == nil { break } - args, err := ec.field_Query_getSubjectConnectionAccess_args(context.TODO(), rawArgs) + args, err := ec.field_Query_getSubjectConnectionAccess_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.GetSubjectConnectionAccess(childComplexity, args["subjectId"].(*string)), true - - case "Query.grantUserRole": - if e.complexity.Query.GrantUserRole == nil { + return e.complexity.Query.GetSubjectConnectionAccess(childComplexity, args["subjectId"].(string)), true + case "Query.grantUserTeam": + if e.complexity.Query.GrantUserTeam == nil { break } - args, err := ec.field_Query_grantUserRole_args(context.TODO(), rawArgs) + args, err := ec.field_Query_grantUserTeam_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.GrantUserRole(childComplexity, args["userId"].(string), args["roleId"].(string)), true - + return e.complexity.Query.GrantUserTeam(childComplexity, args["userId"].(string), args["teamId"].(string)), true case "Query.listAuthProviderConfigurationParameters": if e.complexity.Query.ListAuthProviderConfigurationParameters == nil { break } - args, err := ec.field_Query_listAuthProviderConfigurationParameters_args(context.TODO(), rawArgs) + args, err := ec.field_Query_listAuthProviderConfigurationParameters_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.ListAuthProviderConfigurationParameters(childComplexity, args["providerId"].(string)), true - case "Query.listAuthProviderConfigurations": if e.complexity.Query.ListAuthProviderConfigurations == nil { break } - args, err := ec.field_Query_listAuthProviderConfigurations_args(context.TODO(), rawArgs) + args, err := ec.field_Query_listAuthProviderConfigurations_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.ListAuthProviderConfigurations(childComplexity, args["providerId"].(*string)), true + case "Query.listAuthRoles": + if e.complexity.Query.ListAuthRoles == nil { + break + } + return e.complexity.Query.ListAuthRoles(childComplexity), true case "Query.listFeatureSets": if e.complexity.Query.ListFeatureSets == nil { break } return e.complexity.Query.ListFeatureSets(childComplexity), true - case "Query.listPermissions": if e.complexity.Query.ListPermissions == nil { break } return e.complexity.Query.ListPermissions(childComplexity), true + case "Query.listProjects": + if e.complexity.Query.ListProjects == nil { + break + } + + return e.complexity.Query.ListProjects(childComplexity), true + case "Query.listTeamMetaParameters": + if e.complexity.Query.ListTeamMetaParameters == nil { + break + } + + return e.complexity.Query.ListTeamMetaParameters(childComplexity), true + case "Query.listTeamRoles": + if e.complexity.Query.ListTeamRoles == nil { + break + } - case "Query.listRoles": - if e.complexity.Query.ListRoles == nil { + return e.complexity.Query.ListTeamRoles(childComplexity), true + case "Query.listTeams": + if e.complexity.Query.ListTeams == nil { break } - args, err := ec.field_Query_listRoles_args(context.TODO(), rawArgs) + args, err := ec.field_Query_listTeams_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.ListRoles(childComplexity, args["roleId"].(*string)), true - + return e.complexity.Query.ListTeams(childComplexity, args["teamId"].(*string)), true case "Query.listUserProfileProperties": if e.complexity.Query.ListUserProfileProperties == nil { break } return e.complexity.Query.ListUserProfileProperties(childComplexity), true - case "Query.listUsers": if e.complexity.Query.ListUsers == nil { break } - args, err := ec.field_Query_listUsers_args(context.TODO(), rawArgs) + args, err := ec.field_Query_listUsers_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.ListUsers(childComplexity, args["userId"].(*string)), true - + return e.complexity.Query.ListUsers(childComplexity, args["page"].(model.PageInput), args["filter"].(model.AdminUserFilterInput)), true case "Query.metadataGetNodeDDL": if e.complexity.Query.MetadataGetNodeDdl == nil { break } - args, err := ec.field_Query_metadataGetNodeDDL_args(context.TODO(), rawArgs) + args, err := ec.field_Query_metadataGetNodeDDL_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.MetadataGetNodeDdl(childComplexity, args["nodeId"].(string), args["options"].(interface{})), true + return e.complexity.Query.MetadataGetNodeDdl(childComplexity, args["nodeId"].(string), args["options"].(any)), true + case "Query.metadataGetNodeExtendedDDL": + if e.complexity.Query.MetadataGetNodeExtendedDdl == nil { + break + } + + args, err := ec.field_Query_metadataGetNodeExtendedDDL_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Query.MetadataGetNodeExtendedDdl(childComplexity, args["nodeId"].(string)), true case "Query.navGetStructContainers": if e.complexity.Query.NavGetStructContainers == nil { break } - args, err := ec.field_Query_navGetStructContainers_args(context.TODO(), rawArgs) + args, err := ec.field_Query_navGetStructContainers_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.NavGetStructContainers(childComplexity, args["connectionId"].(string), args["contextId"].(*string), args["catalog"].(*string)), true - + return e.complexity.Query.NavGetStructContainers(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(*string), args["catalog"].(*string)), true case "Query.navNodeChildren": if e.complexity.Query.NavNodeChildren == nil { break } - args, err := ec.field_Query_navNodeChildren_args(context.TODO(), rawArgs) + args, err := ec.field_Query_navNodeChildren_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.NavNodeChildren(childComplexity, args["parentPath"].(string), args["offset"].(*int), args["limit"].(*int), args["onlyFolders"].(*bool)), true - case "Query.navNodeInfo": if e.complexity.Query.NavNodeInfo == nil { break } - args, err := ec.field_Query_navNodeInfo_args(context.TODO(), rawArgs) + args, err := ec.field_Query_navNodeInfo_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.NavNodeInfo(childComplexity, args["nodePath"].(string)), true - case "Query.navNodeParents": if e.complexity.Query.NavNodeParents == nil { break } - args, err := ec.field_Query_navNodeParents_args(context.TODO(), rawArgs) + args, err := ec.field_Query_navNodeParents_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.NavNodeParents(childComplexity, args["nodePath"].(string)), true - case "Query.navRefreshNode": if e.complexity.Query.NavRefreshNode == nil { break } - args, err := ec.field_Query_navRefreshNode_args(context.TODO(), rawArgs) + args, err := ec.field_Query_navRefreshNode_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.NavRefreshNode(childComplexity, args["nodePath"].(string)), true - case "Query.networkHandlers": if e.complexity.Query.NetworkHandlers == nil { break } return e.complexity.Query.NetworkHandlers(childComplexity), true + case "Query.productSettings": + if e.complexity.Query.ProductSettings == nil { + break + } + return e.complexity.Query.ProductSettings(childComplexity), true case "Query.readSessionLog": if e.complexity.Query.ReadSessionLog == nil { break } - args, err := ec.field_Query_readSessionLog_args(context.TODO(), rawArgs) + args, err := ec.field_Query_readSessionLog_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.ReadSessionLog(childComplexity, args["maxEntries"].(*int), args["clearEntries"].(*bool)), true + case "Query.revokeUserTeam": + if e.complexity.Query.RevokeUserTeam == nil { + break + } + + args, err := ec.field_Query_revokeUserTeam_args(ctx, rawArgs) + if err != nil { + return 0, false + } - case "Query.revokeUserRole": - if e.complexity.Query.RevokeUserRole == nil { + return e.complexity.Query.RevokeUserTeam(childComplexity, args["userId"].(string), args["teamId"].(string)), true + case "Query.rmListProjectGrantedPermissions": + if e.complexity.Query.RmListProjectGrantedPermissions == nil { break } - args, err := ec.field_Query_revokeUserRole_args(context.TODO(), rawArgs) + args, err := ec.field_Query_rmListProjectGrantedPermissions_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.RevokeUserRole(childComplexity, args["userId"].(string), args["roleId"].(string)), true + return e.complexity.Query.RmListProjectGrantedPermissions(childComplexity, args["projectId"].(string)), true + case "Query.rmListProjectPermissions": + if e.complexity.Query.RmListProjectPermissions == nil { + break + } + return e.complexity.Query.RmListProjectPermissions(childComplexity), true case "Query.rmListProjects": if e.complexity.Query.RmListProjects == nil { break } return e.complexity.Query.RmListProjects(childComplexity), true - case "Query.rmListResources": if e.complexity.Query.RmListResources == nil { break } - args, err := ec.field_Query_rmListResources_args(context.TODO(), rawArgs) + args, err := ec.field_Query_rmListResources_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.RmListResources(childComplexity, args["projectId"].(string), args["folder"].(*string), args["nameMask"].(*string), args["readProperties"].(*bool), args["readHistory"].(*bool)), true + case "Query.rmListSharedProjects": + if e.complexity.Query.RmListSharedProjects == nil { + break + } + + return e.complexity.Query.RmListSharedProjects(childComplexity), true + case "Query.rmListSubjectProjectsPermissionGrants": + if e.complexity.Query.RmListSubjectProjectsPermissionGrants == nil { + break + } + + args, err := ec.field_Query_rmListSubjectProjectsPermissionGrants_args(ctx, rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.RmListSubjectProjectsPermissionGrants(childComplexity, args["subjectId"].(string)), true + case "Query.rmProject": + if e.complexity.Query.RmProject == nil { + break + } + + args, err := ec.field_Query_rmProject_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Query.RmProject(childComplexity, args["projectId"].(string)), true case "Query.rmReadResourceAsString": if e.complexity.Query.RmReadResourceAsString == nil { break } - args, err := ec.field_Query_rmReadResourceAsString_args(context.TODO(), rawArgs) + args, err := ec.field_Query_rmReadResourceAsString_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.RmReadResourceAsString(childComplexity, args["projectId"].(string), args["resourcePath"].(string)), true - case "Query.sqlCompletionProposals": if e.complexity.Query.SQLCompletionProposals == nil { break } - args, err := ec.field_Query_sqlCompletionProposals_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlCompletionProposals_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLCompletionProposals(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["query"].(string), args["position"].(int), args["maxResults"].(*int), args["simpleMode"].(*bool)), true - + return e.complexity.Query.SQLCompletionProposals(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["query"].(string), args["position"].(int), args["maxResults"].(*int), args["simpleMode"].(*bool)), true case "Query.sqlDialectInfo": if e.complexity.Query.SQLDialectInfo == nil { break } - args, err := ec.field_Query_sqlDialectInfo_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlDialectInfo_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLDialectInfo(childComplexity, args["connectionId"].(string)), true - + return e.complexity.Query.SQLDialectInfo(childComplexity, args["projectId"].(*string), args["connectionId"].(string)), true case "Query.sqlEntityQueryGenerators": if e.complexity.Query.SQLEntityQueryGenerators == nil { break } - args, err := ec.field_Query_sqlEntityQueryGenerators_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlEntityQueryGenerators_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.SQLEntityQueryGenerators(childComplexity, args["nodePathList"].([]string)), true - case "Query.sqlFormatQuery": if e.complexity.Query.SQLFormatQuery == nil { break } - args, err := ec.field_Query_sqlFormatQuery_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlFormatQuery_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLFormatQuery(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["query"].(string)), true - + return e.complexity.Query.SQLFormatQuery(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["query"].(string)), true case "Query.sqlGenerateEntityQuery": if e.complexity.Query.SQLGenerateEntityQuery == nil { break } - args, err := ec.field_Query_sqlGenerateEntityQuery_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlGenerateEntityQuery_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLGenerateEntityQuery(childComplexity, args["generatorId"].(string), args["options"].(interface{}), args["nodePathList"].([]string)), true + return e.complexity.Query.SQLGenerateEntityQuery(childComplexity, args["generatorId"].(string), args["options"].(any), args["nodePathList"].([]string)), true + case "Query.sqlGenerateGroupingQuery": + if e.complexity.Query.SQLGenerateGroupingQuery == nil { + break + } + + args, err := ec.field_Query_sqlGenerateGroupingQuery_args(ctx, rawArgs) + if err != nil { + return 0, false + } + return e.complexity.Query.SQLGenerateGroupingQuery(childComplexity, args["projectId"].(*string), args["contextId"].(string), args["connectionId"].(string), args["resultsId"].(string), args["columnNames"].([]string), args["functions"].([]string), args["showDuplicatesOnly"].(*bool)), true case "Query.sqlListContexts": if e.complexity.Query.SQLListContexts == nil { break } - args, err := ec.field_Query_sqlListContexts_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlListContexts_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLListContexts(childComplexity, args["connectionId"].(*string), args["contextId"].(*string)), true - + return e.complexity.Query.SQLListContexts(childComplexity, args["projectId"].(*string), args["connectionId"].(*string), args["contextId"].(*string)), true case "Query.sqlParseQuery": if e.complexity.Query.SQLParseQuery == nil { break } - args, err := ec.field_Query_sqlParseQuery_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlParseQuery_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLParseQuery(childComplexity, args["connectionId"].(string), args["script"].(string), args["position"].(int)), true - + return e.complexity.Query.SQLParseQuery(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["script"].(string), args["position"].(int)), true case "Query.sqlParseScript": if e.complexity.Query.SQLParseScript == nil { break } - args, err := ec.field_Query_sqlParseScript_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlParseScript_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLParseScript(childComplexity, args["connectionId"].(string), args["script"].(string)), true - + return e.complexity.Query.SQLParseScript(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["script"].(string)), true case "Query.sqlSupportedOperations": if e.complexity.Query.SQLSupportedOperations == nil { break } - args, err := ec.field_Query_sqlSupportedOperations_args(context.TODO(), rawArgs) + args, err := ec.field_Query_sqlSupportedOperations_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SQLSupportedOperations(childComplexity, args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["attributeIndex"].(int)), true - + return e.complexity.Query.SQLSupportedOperations(childComplexity, args["projectId"].(*string), args["connectionId"].(string), args["contextId"].(string), args["resultsId"].(string), args["attributeIndex"].(int)), true case "Query.saveAuthProviderConfiguration": if e.complexity.Query.SaveAuthProviderConfiguration == nil { break } - args, err := ec.field_Query_saveAuthProviderConfiguration_args(context.TODO(), rawArgs) + args, err := ec.field_Query_saveAuthProviderConfiguration_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SaveAuthProviderConfiguration(childComplexity, args["providerId"].(string), args["id"].(string), args["displayName"].(*string), args["disabled"].(*bool), args["iconURL"].(*string), args["description"].(*string), args["parameters"].(interface{})), true - + return e.complexity.Query.SaveAuthProviderConfiguration(childComplexity, args["providerId"].(string), args["id"].(string), args["displayName"].(*string), args["disabled"].(*bool), args["iconURL"].(*string), args["description"].(*string), args["parameters"].(any)), true case "Query.saveUserMetaParameter": if e.complexity.Query.SaveUserMetaParameter == nil { break } - args, err := ec.field_Query_saveUserMetaParameter_args(context.TODO(), rawArgs) + args, err := ec.field_Query_saveUserMetaParameter_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.SaveUserMetaParameter(childComplexity, args["id"].(string), args["displayName"].(string), args["description"].(*string), args["required"].(bool)), true - case "Query.searchConnections": if e.complexity.Query.SearchConnections == nil { break } - args, err := ec.field_Query_searchConnections_args(context.TODO(), rawArgs) + args, err := ec.field_Query_searchConnections_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.SearchConnections(childComplexity, args["hostNames"].([]string)), true - case "Query.serverConfig": if e.complexity.Query.ServerConfig == nil { break } return e.complexity.Query.ServerConfig(childComplexity), true - case "Query.sessionPermissions": if e.complexity.Query.SessionPermissions == nil { break } return e.complexity.Query.SessionPermissions(childComplexity), true - case "Query.sessionState": if e.complexity.Query.SessionState == nil { break } return e.complexity.Query.SessionState(childComplexity), true - case "Query.setConnectionSubjectAccess": if e.complexity.Query.SetConnectionSubjectAccess == nil { break } - args, err := ec.field_Query_setConnectionSubjectAccess_args(context.TODO(), rawArgs) + args, err := ec.field_Query_setConnectionSubjectAccess_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SetConnectionSubjectAccess(childComplexity, args["connectionId"].(string), args["subjects"].([]string)), true - + return e.complexity.Query.SetConnectionSubjectAccess(childComplexity, args["projectId"].(string), args["connectionId"].(string), args["subjects"].([]string)), true case "Query.setDefaultNavigatorSettings": if e.complexity.Query.SetDefaultNavigatorSettings == nil { break } - args, err := ec.field_Query_setDefaultNavigatorSettings_args(context.TODO(), rawArgs) + args, err := ec.field_Query_setDefaultNavigatorSettings_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.SetDefaultNavigatorSettings(childComplexity, args["settings"].(model.NavigatorSettingsInput)), true - case "Query.setSubjectConnectionAccess": if e.complexity.Query.SetSubjectConnectionAccess == nil { break } - args, err := ec.field_Query_setSubjectConnectionAccess_args(context.TODO(), rawArgs) + args, err := ec.field_Query_setSubjectConnectionAccess_args(ctx, rawArgs) if err != nil { return 0, false } return e.complexity.Query.SetSubjectConnectionAccess(childComplexity, args["subjectId"].(string), args["connections"].([]string)), true - case "Query.setSubjectPermissions": if e.complexity.Query.SetSubjectPermissions == nil { break } - args, err := ec.field_Query_setSubjectPermissions_args(context.TODO(), rawArgs) + args, err := ec.field_Query_setSubjectPermissions_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SetSubjectPermissions(childComplexity, args["roleId"].(string), args["permissions"].([]string)), true - - case "Query.setUserCredentials": - if e.complexity.Query.SetUserCredentials == nil { + return e.complexity.Query.SetSubjectPermissions(childComplexity, args["subjectId"].(string), args["permissions"].([]string)), true + case "Query.setTeamMetaParameterValues": + if e.complexity.Query.SetTeamMetaParameterValues == nil { break } - args, err := ec.field_Query_setUserCredentials_args(context.TODO(), rawArgs) + args, err := ec.field_Query_setTeamMetaParameterValues_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SetUserCredentials(childComplexity, args["userId"].(string), args["providerId"].(string), args["credentials"].(interface{})), true - - case "Query.setUserMetaParameterValues": - if e.complexity.Query.SetUserMetaParameterValues == nil { + return e.complexity.Query.SetTeamMetaParameterValues(childComplexity, args["teamId"].(string), args["parameters"].(any)), true + case "Query.setUserAuthRole": + if e.complexity.Query.SetUserAuthRole == nil { break } - args, err := ec.field_Query_setUserMetaParameterValues_args(context.TODO(), rawArgs) + args, err := ec.field_Query_setUserAuthRole_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.SetUserMetaParameterValues(childComplexity, args["userId"].(string), args["parameters"].(interface{})), true + return e.complexity.Query.SetUserAuthRole(childComplexity, args["userId"].(string), args["authRole"].(*string)), true + case "Query.setUserCredentials": + if e.complexity.Query.SetUserCredentials == nil { + break + } + + args, err := ec.field_Query_setUserCredentials_args(ctx, rawArgs) + if err != nil { + return 0, false + } - case "Query.templateConnections": - if e.complexity.Query.TemplateConnections == nil { + return e.complexity.Query.SetUserCredentials(childComplexity, args["userId"].(string), args["providerId"].(string), args["credentials"].(any)), true + case "Query.setUserMetaParameterValues": + if e.complexity.Query.SetUserMetaParameterValues == nil { break } - return e.complexity.Query.TemplateConnections(childComplexity), true + args, err := ec.field_Query_setUserMetaParameterValues_args(ctx, rawArgs) + if err != nil { + return 0, false + } - case "Query.updateConnectionConfiguration": - if e.complexity.Query.UpdateConnectionConfiguration == nil { + return e.complexity.Query.SetUserMetaParameterValues(childComplexity, args["userId"].(string), args["parameters"].(any)), true + case "Query.setUserTeamRole": + if e.complexity.Query.SetUserTeamRole == nil { break } - args, err := ec.field_Query_updateConnectionConfiguration_args(context.TODO(), rawArgs) + args, err := ec.field_Query_setUserTeamRole_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.UpdateConnectionConfiguration(childComplexity, args["id"].(string), args["config"].(model.ConnectionConfig)), true + return e.complexity.Query.SetUserTeamRole(childComplexity, args["userId"].(string), args["teamId"].(string), args["teamRole"].(*string)), true + case "Query.systemInfo": + if e.complexity.Query.SystemInfo == nil { + break + } - case "Query.updateRole": - if e.complexity.Query.UpdateRole == nil { + return e.complexity.Query.SystemInfo(childComplexity), true + case "Query.updateTeam": + if e.complexity.Query.UpdateTeam == nil { break } - args, err := ec.field_Query_updateRole_args(context.TODO(), rawArgs) + args, err := ec.field_Query_updateTeam_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.UpdateRole(childComplexity, args["roleId"].(string), args["roleName"].(*string), args["description"].(*string)), true - + return e.complexity.Query.UpdateTeam(childComplexity, args["teamId"].(string), args["teamName"].(*string), args["description"].(*string)), true case "Query.userConnections": if e.complexity.Query.UserConnections == nil { break } - args, err := ec.field_Query_userConnections_args(context.TODO(), rawArgs) + args, err := ec.field_Query_userConnections_args(ctx, rawArgs) if err != nil { return 0, false } - return e.complexity.Query.UserConnections(childComplexity, args["id"].(*string)), true + return e.complexity.Query.UserConnections(childComplexity, args["projectId"].(*string), args["id"].(*string), args["projectIds"].([]string)), true case "RMProject.createTime": if e.complexity.RMProject.CreateTime == nil { @@ -4011,35 +4971,48 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.RMProject.CreateTime(childComplexity), true - case "RMProject.creator": if e.complexity.RMProject.Creator == nil { break } return e.complexity.RMProject.Creator(childComplexity), true - case "RMProject.description": if e.complexity.RMProject.Description == nil { break } return e.complexity.RMProject.Description(childComplexity), true + case "RMProject.global": + if e.complexity.RMProject.Global == nil { + break + } + return e.complexity.RMProject.Global(childComplexity), true case "RMProject.id": if e.complexity.RMProject.ID == nil { break } return e.complexity.RMProject.ID(childComplexity), true - case "RMProject.name": if e.complexity.RMProject.Name == nil { break } return e.complexity.RMProject.Name(childComplexity), true + case "RMProject.projectPermissions": + if e.complexity.RMProject.ProjectPermissions == nil { + break + } + + return e.complexity.RMProject.ProjectPermissions(childComplexity), true + case "RMProject.resourceTypes": + if e.complexity.RMProject.ResourceTypes == nil { + break + } + return e.complexity.RMProject.ResourceTypes(childComplexity), true case "RMProject.shared": if e.complexity.RMProject.Shared == nil { break @@ -4053,20 +5026,55 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.RMResource.Folder(childComplexity), true - case "RMResource.length": if e.complexity.RMResource.Length == nil { break } return e.complexity.RMResource.Length(childComplexity), true - case "RMResource.name": if e.complexity.RMResource.Name == nil { break } return e.complexity.RMResource.Name(childComplexity), true + case "RMResource.properties": + if e.complexity.RMResource.Properties == nil { + break + } + + return e.complexity.RMResource.Properties(childComplexity), true + + case "RMResourceType.displayName": + if e.complexity.RMResourceType.DisplayName == nil { + break + } + + return e.complexity.RMResourceType.DisplayName(childComplexity), true + case "RMResourceType.fileExtensions": + if e.complexity.RMResourceType.FileExtensions == nil { + break + } + + return e.complexity.RMResourceType.FileExtensions(childComplexity), true + case "RMResourceType.id": + if e.complexity.RMResourceType.ID == nil { + break + } + + return e.complexity.RMResourceType.ID(childComplexity), true + case "RMResourceType.icon": + if e.complexity.RMResourceType.Icon == nil { + break + } + + return e.complexity.RMResourceType.Icon(childComplexity), true + case "RMResourceType.rootFolder": + if e.complexity.RMResourceType.RootFolder == nil { + break + } + + return e.complexity.RMResourceType.RootFolder(childComplexity), true case "SQLCompletionProposal.cursorPosition": if e.complexity.SQLCompletionProposal.CursorPosition == nil { @@ -4074,56 +5082,48 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLCompletionProposal.CursorPosition(childComplexity), true - case "SQLCompletionProposal.displayString": if e.complexity.SQLCompletionProposal.DisplayString == nil { break } return e.complexity.SQLCompletionProposal.DisplayString(childComplexity), true - case "SQLCompletionProposal.icon": if e.complexity.SQLCompletionProposal.Icon == nil { break } return e.complexity.SQLCompletionProposal.Icon(childComplexity), true - case "SQLCompletionProposal.nodePath": if e.complexity.SQLCompletionProposal.NodePath == nil { break } return e.complexity.SQLCompletionProposal.NodePath(childComplexity), true - case "SQLCompletionProposal.replacementLength": if e.complexity.SQLCompletionProposal.ReplacementLength == nil { break } return e.complexity.SQLCompletionProposal.ReplacementLength(childComplexity), true - case "SQLCompletionProposal.replacementOffset": if e.complexity.SQLCompletionProposal.ReplacementOffset == nil { break } return e.complexity.SQLCompletionProposal.ReplacementOffset(childComplexity), true - case "SQLCompletionProposal.replacementString": if e.complexity.SQLCompletionProposal.ReplacementString == nil { break } return e.complexity.SQLCompletionProposal.ReplacementString(childComplexity), true - case "SQLCompletionProposal.score": if e.complexity.SQLCompletionProposal.Score == nil { break } return e.complexity.SQLCompletionProposal.Score(childComplexity), true - case "SQLCompletionProposal.type": if e.complexity.SQLCompletionProposal.Type == nil { break @@ -4131,33 +5131,42 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.SQLCompletionProposal.Type(childComplexity), true + case "SQLContextInfo.autoCommit": + if e.complexity.SQLContextInfo.AutoCommit == nil { + break + } + + return e.complexity.SQLContextInfo.AutoCommit(childComplexity), true case "SQLContextInfo.connectionId": if e.complexity.SQLContextInfo.ConnectionID == nil { break } return e.complexity.SQLContextInfo.ConnectionID(childComplexity), true - case "SQLContextInfo.defaultCatalog": if e.complexity.SQLContextInfo.DefaultCatalog == nil { break } return e.complexity.SQLContextInfo.DefaultCatalog(childComplexity), true - case "SQLContextInfo.defaultSchema": if e.complexity.SQLContextInfo.DefaultSchema == nil { break } return e.complexity.SQLContextInfo.DefaultSchema(childComplexity), true - case "SQLContextInfo.id": if e.complexity.SQLContextInfo.ID == nil { break } return e.complexity.SQLContextInfo.ID(childComplexity), true + case "SQLContextInfo.projectId": + if e.complexity.SQLContextInfo.ProjectID == nil { + break + } + + return e.complexity.SQLContextInfo.ProjectID(childComplexity), true case "SQLDialectInfo.catalogSeparator": if e.complexity.SQLDialectInfo.CatalogSeparator == nil { @@ -4165,70 +5174,60 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLDialectInfo.CatalogSeparator(childComplexity), true - case "SQLDialectInfo.dataTypes": if e.complexity.SQLDialectInfo.DataTypes == nil { break } return e.complexity.SQLDialectInfo.DataTypes(childComplexity), true - case "SQLDialectInfo.functions": if e.complexity.SQLDialectInfo.Functions == nil { break } return e.complexity.SQLDialectInfo.Functions(childComplexity), true - case "SQLDialectInfo.multiLineComments": if e.complexity.SQLDialectInfo.MultiLineComments == nil { break } return e.complexity.SQLDialectInfo.MultiLineComments(childComplexity), true - case "SQLDialectInfo.name": if e.complexity.SQLDialectInfo.Name == nil { break } return e.complexity.SQLDialectInfo.Name(childComplexity), true - case "SQLDialectInfo.quoteStrings": if e.complexity.SQLDialectInfo.QuoteStrings == nil { break } return e.complexity.SQLDialectInfo.QuoteStrings(childComplexity), true - case "SQLDialectInfo.reservedWords": if e.complexity.SQLDialectInfo.ReservedWords == nil { break } return e.complexity.SQLDialectInfo.ReservedWords(childComplexity), true - case "SQLDialectInfo.scriptDelimiter": if e.complexity.SQLDialectInfo.ScriptDelimiter == nil { break } return e.complexity.SQLDialectInfo.ScriptDelimiter(childComplexity), true - case "SQLDialectInfo.singleLineComments": if e.complexity.SQLDialectInfo.SingleLineComments == nil { break } return e.complexity.SQLDialectInfo.SingleLineComments(childComplexity), true - case "SQLDialectInfo.structSeparator": if e.complexity.SQLDialectInfo.StructSeparator == nil { break } return e.complexity.SQLDialectInfo.StructSeparator(childComplexity), true - case "SQLDialectInfo.supportsExplainExecutionPlan": if e.complexity.SQLDialectInfo.SupportsExplainExecutionPlan == nil { break @@ -4242,21 +5241,24 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLExecuteInfo.Duration(childComplexity), true - case "SQLExecuteInfo.filterText": if e.complexity.SQLExecuteInfo.FilterText == nil { break } return e.complexity.SQLExecuteInfo.FilterText(childComplexity), true + case "SQLExecuteInfo.fullQuery": + if e.complexity.SQLExecuteInfo.FullQuery == nil { + break + } + return e.complexity.SQLExecuteInfo.FullQuery(childComplexity), true case "SQLExecuteInfo.results": if e.complexity.SQLExecuteInfo.Results == nil { break } return e.complexity.SQLExecuteInfo.Results(childComplexity), true - case "SQLExecuteInfo.statusMessage": if e.complexity.SQLExecuteInfo.StatusMessage == nil { break @@ -4270,7 +5272,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLExecutionPlan.Nodes(childComplexity), true - case "SQLExecutionPlan.query": if e.complexity.SQLExecutionPlan.Query == nil { break @@ -4284,49 +5285,42 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLExecutionPlanNode.Condition(childComplexity), true - case "SQLExecutionPlanNode.description": if e.complexity.SQLExecutionPlanNode.Description == nil { break } return e.complexity.SQLExecutionPlanNode.Description(childComplexity), true - case "SQLExecutionPlanNode.id": if e.complexity.SQLExecutionPlanNode.ID == nil { break } return e.complexity.SQLExecutionPlanNode.ID(childComplexity), true - case "SQLExecutionPlanNode.kind": if e.complexity.SQLExecutionPlanNode.Kind == nil { break } return e.complexity.SQLExecutionPlanNode.Kind(childComplexity), true - case "SQLExecutionPlanNode.name": if e.complexity.SQLExecutionPlanNode.Name == nil { break } return e.complexity.SQLExecutionPlanNode.Name(childComplexity), true - case "SQLExecutionPlanNode.parentId": if e.complexity.SQLExecutionPlanNode.ParentID == nil { break } return e.complexity.SQLExecutionPlanNode.ParentID(childComplexity), true - case "SQLExecutionPlanNode.properties": if e.complexity.SQLExecutionPlanNode.Properties == nil { break } return e.complexity.SQLExecutionPlanNode.Properties(childComplexity), true - case "SQLExecutionPlanNode.type": if e.complexity.SQLExecutionPlanNode.Type == nil { break @@ -4340,28 +5334,24 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLQueryGenerator.Description(childComplexity), true - case "SQLQueryGenerator.id": if e.complexity.SQLQueryGenerator.ID == nil { break } return e.complexity.SQLQueryGenerator.ID(childComplexity), true - case "SQLQueryGenerator.label": if e.complexity.SQLQueryGenerator.Label == nil { break } return e.complexity.SQLQueryGenerator.Label(childComplexity), true - case "SQLQueryGenerator.multiObject": if e.complexity.SQLQueryGenerator.MultiObject == nil { break } return e.complexity.SQLQueryGenerator.MultiObject(childComplexity), true - case "SQLQueryGenerator.order": if e.complexity.SQLQueryGenerator.Order == nil { break @@ -4375,28 +5365,24 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLQueryResults.DataFormat(childComplexity), true - case "SQLQueryResults.resultSet": if e.complexity.SQLQueryResults.ResultSet == nil { break } return e.complexity.SQLQueryResults.ResultSet(childComplexity), true - case "SQLQueryResults.sourceQuery": if e.complexity.SQLQueryResults.SourceQuery == nil { break } return e.complexity.SQLQueryResults.SourceQuery(childComplexity), true - case "SQLQueryResults.title": if e.complexity.SQLQueryResults.Title == nil { break } return e.complexity.SQLQueryResults.Title(childComplexity), true - case "SQLQueryResults.updateRowCount": if e.complexity.SQLQueryResults.UpdateRowCount == nil { break @@ -4404,104 +5390,102 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.SQLQueryResults.UpdateRowCount(childComplexity), true + case "SQLResultColumn.autoGenerated": + if e.complexity.SQLResultColumn.AutoGenerated == nil { + break + } + + return e.complexity.SQLResultColumn.AutoGenerated(childComplexity), true case "SQLResultColumn.dataKind": if e.complexity.SQLResultColumn.DataKind == nil { break } return e.complexity.SQLResultColumn.DataKind(childComplexity), true + case "SQLResultColumn.description": + if e.complexity.SQLResultColumn.Description == nil { + break + } + return e.complexity.SQLResultColumn.Description(childComplexity), true case "SQLResultColumn.entityName": if e.complexity.SQLResultColumn.EntityName == nil { break } return e.complexity.SQLResultColumn.EntityName(childComplexity), true - case "SQLResultColumn.fullTypeName": if e.complexity.SQLResultColumn.FullTypeName == nil { break } return e.complexity.SQLResultColumn.FullTypeName(childComplexity), true - case "SQLResultColumn.icon": if e.complexity.SQLResultColumn.Icon == nil { break } return e.complexity.SQLResultColumn.Icon(childComplexity), true - case "SQLResultColumn.label": if e.complexity.SQLResultColumn.Label == nil { break } return e.complexity.SQLResultColumn.Label(childComplexity), true - case "SQLResultColumn.maxLength": if e.complexity.SQLResultColumn.MaxLength == nil { break } return e.complexity.SQLResultColumn.MaxLength(childComplexity), true - case "SQLResultColumn.name": if e.complexity.SQLResultColumn.Name == nil { break } return e.complexity.SQLResultColumn.Name(childComplexity), true - case "SQLResultColumn.position": if e.complexity.SQLResultColumn.Position == nil { break } return e.complexity.SQLResultColumn.Position(childComplexity), true - case "SQLResultColumn.precision": if e.complexity.SQLResultColumn.Precision == nil { break } return e.complexity.SQLResultColumn.Precision(childComplexity), true - case "SQLResultColumn.readOnly": if e.complexity.SQLResultColumn.ReadOnly == nil { break } return e.complexity.SQLResultColumn.ReadOnly(childComplexity), true - case "SQLResultColumn.readOnlyStatus": if e.complexity.SQLResultColumn.ReadOnlyStatus == nil { break } return e.complexity.SQLResultColumn.ReadOnlyStatus(childComplexity), true - case "SQLResultColumn.required": if e.complexity.SQLResultColumn.Required == nil { break } return e.complexity.SQLResultColumn.Required(childComplexity), true - case "SQLResultColumn.scale": if e.complexity.SQLResultColumn.Scale == nil { break } return e.complexity.SQLResultColumn.Scale(childComplexity), true - case "SQLResultColumn.supportedOperations": if e.complexity.SQLResultColumn.SupportedOperations == nil { break } return e.complexity.SQLResultColumn.SupportedOperations(childComplexity), true - case "SQLResultColumn.typeName": if e.complexity.SQLResultColumn.TypeName == nil { break @@ -4509,41 +5493,85 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.SQLResultColumn.TypeName(childComplexity), true + case "SQLResultRowMetaData.data": + if e.complexity.SQLResultRowMetaData.Data == nil { + break + } + + return e.complexity.SQLResultRowMetaData.Data(childComplexity), true + case "SQLResultRowMetaData.metaData": + if e.complexity.SQLResultRowMetaData.MetaData == nil { + break + } + + return e.complexity.SQLResultRowMetaData.MetaData(childComplexity), true + case "SQLResultSet.columns": if e.complexity.SQLResultSet.Columns == nil { break } return e.complexity.SQLResultSet.Columns(childComplexity), true + case "SQLResultSet.hasChildrenCollection": + if e.complexity.SQLResultSet.HasChildrenCollection == nil { + break + } + return e.complexity.SQLResultSet.HasChildrenCollection(childComplexity), true + case "SQLResultSet.hasDynamicTrace": + if e.complexity.SQLResultSet.HasDynamicTrace == nil { + break + } + + return e.complexity.SQLResultSet.HasDynamicTrace(childComplexity), true case "SQLResultSet.hasMoreData": if e.complexity.SQLResultSet.HasMoreData == nil { break } return e.complexity.SQLResultSet.HasMoreData(childComplexity), true - case "SQLResultSet.hasRowIdentifier": if e.complexity.SQLResultSet.HasRowIdentifier == nil { break } return e.complexity.SQLResultSet.HasRowIdentifier(childComplexity), true - case "SQLResultSet.id": if e.complexity.SQLResultSet.ID == nil { break } return e.complexity.SQLResultSet.ID(childComplexity), true + case "SQLResultSet.isSupportsDataFilter": + if e.complexity.SQLResultSet.IsSupportsDataFilter == nil { + break + } + + return e.complexity.SQLResultSet.IsSupportsDataFilter(childComplexity), true + case "SQLResultSet.readOnly": + if e.complexity.SQLResultSet.ReadOnly == nil { + break + } + + return e.complexity.SQLResultSet.ReadOnly(childComplexity), true + case "SQLResultSet.readOnlyStatus": + if e.complexity.SQLResultSet.ReadOnlyStatus == nil { + break + } + return e.complexity.SQLResultSet.ReadOnlyStatus(childComplexity), true case "SQLResultSet.rows": if e.complexity.SQLResultSet.Rows == nil { break } return e.complexity.SQLResultSet.Rows(childComplexity), true + case "SQLResultSet.rowsWithMetaData": + if e.complexity.SQLResultSet.RowsWithMetaData == nil { + break + } + return e.complexity.SQLResultSet.RowsWithMetaData(childComplexity), true case "SQLResultSet.singleEntity": if e.complexity.SQLResultSet.SingleEntity == nil { break @@ -4564,7 +5592,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SQLScriptQuery.End(childComplexity), true - case "SQLScriptQuery.start": if e.complexity.SQLScriptQuery.Start == nil { break @@ -4572,209 +5599,157 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.SQLScriptQuery.Start(childComplexity), true + case "SecretInfo.displayName": + if e.complexity.SecretInfo.DisplayName == nil { + break + } + + return e.complexity.SecretInfo.DisplayName(childComplexity), true + case "SecretInfo.secretId": + if e.complexity.SecretInfo.SecretID == nil { + break + } + + return e.complexity.SecretInfo.SecretID(childComplexity), true + case "ServerConfig.adminCredentialsSaveEnabled": if e.complexity.ServerConfig.AdminCredentialsSaveEnabled == nil { break } return e.complexity.ServerConfig.AdminCredentialsSaveEnabled(childComplexity), true - case "ServerConfig.anonymousAccessEnabled": if e.complexity.ServerConfig.AnonymousAccessEnabled == nil { break } return e.complexity.ServerConfig.AnonymousAccessEnabled(childComplexity), true - - case "ServerConfig.authenticationEnabled": - if e.complexity.ServerConfig.AuthenticationEnabled == nil { - break - } - - return e.complexity.ServerConfig.AuthenticationEnabled(childComplexity), true - case "ServerConfig.configurationMode": if e.complexity.ServerConfig.ConfigurationMode == nil { break } return e.complexity.ServerConfig.ConfigurationMode(childComplexity), true - case "ServerConfig.defaultNavigatorSettings": if e.complexity.ServerConfig.DefaultNavigatorSettings == nil { break } return e.complexity.ServerConfig.DefaultNavigatorSettings(childComplexity), true - case "ServerConfig.developmentMode": if e.complexity.ServerConfig.DevelopmentMode == nil { break } return e.complexity.ServerConfig.DevelopmentMode(childComplexity), true + case "ServerConfig.disabledBetaFeatures": + if e.complexity.ServerConfig.DisabledBetaFeatures == nil { + break + } + return e.complexity.ServerConfig.DisabledBetaFeatures(childComplexity), true case "ServerConfig.disabledDrivers": if e.complexity.ServerConfig.DisabledDrivers == nil { break } return e.complexity.ServerConfig.DisabledDrivers(childComplexity), true - - case "ServerConfig.enabledAuthProviders": - if e.complexity.ServerConfig.EnabledAuthProviders == nil { + case "ServerConfig.distributed": + if e.complexity.ServerConfig.Distributed == nil { break } - return e.complexity.ServerConfig.EnabledAuthProviders(childComplexity), true - + return e.complexity.ServerConfig.Distributed(childComplexity), true case "ServerConfig.enabledFeatures": if e.complexity.ServerConfig.EnabledFeatures == nil { break } return e.complexity.ServerConfig.EnabledFeatures(childComplexity), true - - case "ServerConfig.hostName": - if e.complexity.ServerConfig.HostName == nil { - break - } - - return e.complexity.ServerConfig.HostName(childComplexity), true - case "ServerConfig.licenseRequired": if e.complexity.ServerConfig.LicenseRequired == nil { break } return e.complexity.ServerConfig.LicenseRequired(childComplexity), true + case "ServerConfig.licenseStatus": + if e.complexity.ServerConfig.LicenseStatus == nil { + break + } + return e.complexity.ServerConfig.LicenseStatus(childComplexity), true case "ServerConfig.licenseValid": if e.complexity.ServerConfig.LicenseValid == nil { break } return e.complexity.ServerConfig.LicenseValid(childComplexity), true - - case "ServerConfig.localHostAddress": - if e.complexity.ServerConfig.LocalHostAddress == nil { - break - } - - return e.complexity.ServerConfig.LocalHostAddress(childComplexity), true - case "ServerConfig.name": if e.complexity.ServerConfig.Name == nil { break } return e.complexity.ServerConfig.Name(childComplexity), true - case "ServerConfig.productConfiguration": if e.complexity.ServerConfig.ProductConfiguration == nil { break } return e.complexity.ServerConfig.ProductConfiguration(childComplexity), true - case "ServerConfig.productInfo": if e.complexity.ServerConfig.ProductInfo == nil { break } return e.complexity.ServerConfig.ProductInfo(childComplexity), true - case "ServerConfig.publicCredentialsSaveEnabled": if e.complexity.ServerConfig.PublicCredentialsSaveEnabled == nil { break } return e.complexity.ServerConfig.PublicCredentialsSaveEnabled(childComplexity), true - - case "ServerConfig.redirectOnFederatedAuth": - if e.complexity.ServerConfig.RedirectOnFederatedAuth == nil { - break - } - - return e.complexity.ServerConfig.RedirectOnFederatedAuth(childComplexity), true - case "ServerConfig.resourceManagerEnabled": if e.complexity.ServerConfig.ResourceManagerEnabled == nil { break } return e.complexity.ServerConfig.ResourceManagerEnabled(childComplexity), true - case "ServerConfig.resourceQuotas": if e.complexity.ServerConfig.ResourceQuotas == nil { break } return e.complexity.ServerConfig.ResourceQuotas(childComplexity), true - - case "ServerConfig.rootURI": - if e.complexity.ServerConfig.RootURI == nil { + case "ServerConfig.secretManagerEnabled": + if e.complexity.ServerConfig.SecretManagerEnabled == nil { break } - return e.complexity.ServerConfig.RootURI(childComplexity), true - - case "ServerConfig.serverURL": - if e.complexity.ServerConfig.ServerURL == nil { - break - } - - return e.complexity.ServerConfig.ServerURL(childComplexity), true - - case "ServerConfig.services": - if e.complexity.ServerConfig.Services == nil { - break - } - - return e.complexity.ServerConfig.Services(childComplexity), true - - case "ServerConfig.sessionExpireTime": - if e.complexity.ServerConfig.SessionExpireTime == nil { + return e.complexity.ServerConfig.SecretManagerEnabled(childComplexity), true + case "ServerConfig.serverFeatures": + if e.complexity.ServerConfig.ServerFeatures == nil { break } - return e.complexity.ServerConfig.SessionExpireTime(childComplexity), true - + return e.complexity.ServerConfig.ServerFeatures(childComplexity), true case "ServerConfig.supportedLanguages": if e.complexity.ServerConfig.SupportedLanguages == nil { break } return e.complexity.ServerConfig.SupportedLanguages(childComplexity), true - - case "ServerConfig.supportsConnectionBrowser": - if e.complexity.ServerConfig.SupportsConnectionBrowser == nil { - break - } - - return e.complexity.ServerConfig.SupportsConnectionBrowser(childComplexity), true - case "ServerConfig.supportsCustomConnections": if e.complexity.ServerConfig.SupportsCustomConnections == nil { break } return e.complexity.ServerConfig.SupportsCustomConnections(childComplexity), true - - case "ServerConfig.supportsWorkspaces": - if e.complexity.ServerConfig.SupportsWorkspaces == nil { - break - } - - return e.complexity.ServerConfig.SupportsWorkspaces(childComplexity), true - case "ServerConfig.version": if e.complexity.ServerConfig.Version == nil { break } return e.complexity.ServerConfig.Version(childComplexity), true - case "ServerConfig.workspaceId": if e.complexity.ServerConfig.WorkspaceID == nil { break @@ -4788,28 +5763,24 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ServerError.CausedBy(childComplexity), true - case "ServerError.errorCode": if e.complexity.ServerError.ErrorCode == nil { break } return e.complexity.ServerError.ErrorCode(childComplexity), true - case "ServerError.errorType": if e.complexity.ServerError.ErrorType == nil { break } return e.complexity.ServerError.ErrorType(childComplexity), true - case "ServerError.message": if e.complexity.ServerError.Message == nil { break } return e.complexity.ServerError.Message(childComplexity), true - case "ServerError.stackTrace": if e.complexity.ServerError.StackTrace == nil { break @@ -4823,14 +5794,12 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ServerLanguage.DisplayName(childComplexity), true - case "ServerLanguage.isoCode": if e.complexity.ServerLanguage.IsoCode == nil { break } return e.complexity.ServerLanguage.IsoCode(childComplexity), true - case "ServerLanguage.nativeName": if e.complexity.ServerLanguage.NativeName == nil { break @@ -4844,7 +5813,6 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.ServerMessage.Message(childComplexity), true - case "ServerMessage.time": if e.complexity.ServerMessage.Time == nil { break @@ -4858,48 +5826,104 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.SessionInfo.ActionParameters(childComplexity), true - case "SessionInfo.cacheExpired": if e.complexity.SessionInfo.CacheExpired == nil { break } return e.complexity.SessionInfo.CacheExpired(childComplexity), true - case "SessionInfo.connections": if e.complexity.SessionInfo.Connections == nil { break } return e.complexity.SessionInfo.Connections(childComplexity), true - case "SessionInfo.createTime": if e.complexity.SessionInfo.CreateTime == nil { break } return e.complexity.SessionInfo.CreateTime(childComplexity), true - case "SessionInfo.lastAccessTime": if e.complexity.SessionInfo.LastAccessTime == nil { break } return e.complexity.SessionInfo.LastAccessTime(childComplexity), true - case "SessionInfo.locale": if e.complexity.SessionInfo.Locale == nil { break } return e.complexity.SessionInfo.Locale(childComplexity), true + case "SessionInfo.remainingTime": + if e.complexity.SessionInfo.RemainingTime == nil { + break + } + + return e.complexity.SessionInfo.RemainingTime(childComplexity), true + case "SessionInfo.valid": + if e.complexity.SessionInfo.Valid == nil { + break + } + + return e.complexity.SessionInfo.Valid(childComplexity), true + + case "TransactionLogInfoItem.durationMs": + if e.complexity.TransactionLogInfoItem.DurationMs == nil { + break + } + + return e.complexity.TransactionLogInfoItem.DurationMs(childComplexity), true + case "TransactionLogInfoItem.id": + if e.complexity.TransactionLogInfoItem.ID == nil { + break + } + + return e.complexity.TransactionLogInfoItem.ID(childComplexity), true + case "TransactionLogInfoItem.queryString": + if e.complexity.TransactionLogInfoItem.QueryString == nil { + break + } + + return e.complexity.TransactionLogInfoItem.QueryString(childComplexity), true + case "TransactionLogInfoItem.result": + if e.complexity.TransactionLogInfoItem.Result == nil { + break + } + + return e.complexity.TransactionLogInfoItem.Result(childComplexity), true + case "TransactionLogInfoItem.rows": + if e.complexity.TransactionLogInfoItem.Rows == nil { + break + } + + return e.complexity.TransactionLogInfoItem.Rows(childComplexity), true + case "TransactionLogInfoItem.time": + if e.complexity.TransactionLogInfoItem.Time == nil { + break + } + + return e.complexity.TransactionLogInfoItem.Time(childComplexity), true + case "TransactionLogInfoItem.type": + if e.complexity.TransactionLogInfoItem.Type == nil { + break + } + + return e.complexity.TransactionLogInfoItem.Type(childComplexity), true - case "SessionInfo.serverMessages": - if e.complexity.SessionInfo.ServerMessages == nil { + case "TransactionLogInfos.count": + if e.complexity.TransactionLogInfos.Count == nil { break } - return e.complexity.SessionInfo.ServerMessages(childComplexity), true + return e.complexity.TransactionLogInfos.Count(childComplexity), true + case "TransactionLogInfos.transactionLogInfos": + if e.complexity.TransactionLogInfos.TransactionLogInfos == nil { + break + } + + return e.complexity.TransactionLogInfos.TransactionLogInfos(childComplexity), true case "UserAuthToken.authConfiguration": if e.complexity.UserAuthToken.AuthConfiguration == nil { @@ -4907,42 +5931,36 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in } return e.complexity.UserAuthToken.AuthConfiguration(childComplexity), true - case "UserAuthToken.authProvider": if e.complexity.UserAuthToken.AuthProvider == nil { break } return e.complexity.UserAuthToken.AuthProvider(childComplexity), true - case "UserAuthToken.displayName": if e.complexity.UserAuthToken.DisplayName == nil { break } return e.complexity.UserAuthToken.DisplayName(childComplexity), true - case "UserAuthToken.loginTime": if e.complexity.UserAuthToken.LoginTime == nil { break } return e.complexity.UserAuthToken.LoginTime(childComplexity), true - case "UserAuthToken.message": if e.complexity.UserAuthToken.Message == nil { break } return e.complexity.UserAuthToken.Message(childComplexity), true - case "UserAuthToken.origin": if e.complexity.UserAuthToken.Origin == nil { break } return e.complexity.UserAuthToken.Origin(childComplexity), true - case "UserAuthToken.userId": if e.complexity.UserAuthToken.UserID == nil { break @@ -4950,41 +5968,54 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.UserAuthToken.UserID(childComplexity), true + case "UserInfo.authRole": + if e.complexity.UserInfo.AuthRole == nil { + break + } + + return e.complexity.UserInfo.AuthRole(childComplexity), true case "UserInfo.authTokens": if e.complexity.UserInfo.AuthTokens == nil { break } return e.complexity.UserInfo.AuthTokens(childComplexity), true - case "UserInfo.configurationParameters": if e.complexity.UserInfo.ConfigurationParameters == nil { break } return e.complexity.UserInfo.ConfigurationParameters(childComplexity), true - case "UserInfo.displayName": if e.complexity.UserInfo.DisplayName == nil { break } return e.complexity.UserInfo.DisplayName(childComplexity), true + case "UserInfo.isAnonymous": + if e.complexity.UserInfo.IsAnonymous == nil { + break + } + return e.complexity.UserInfo.IsAnonymous(childComplexity), true case "UserInfo.linkedAuthProviders": if e.complexity.UserInfo.LinkedAuthProviders == nil { break } return e.complexity.UserInfo.LinkedAuthProviders(childComplexity), true - case "UserInfo.metaParameters": if e.complexity.UserInfo.MetaParameters == nil { break } return e.complexity.UserInfo.MetaParameters(childComplexity), true + case "UserInfo.teams": + if e.complexity.UserInfo.Teams == nil { + break + } + return e.complexity.UserInfo.Teams(childComplexity), true case "UserInfo.userId": if e.complexity.UserInfo.UserID == nil { break @@ -4992,34 +6023,49 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.UserInfo.UserID(childComplexity), true + case "UserTeamInfo.teamId": + if e.complexity.UserTeamInfo.TeamID == nil { + break + } + + return e.complexity.UserTeamInfo.TeamID(childComplexity), true + case "UserTeamInfo.teamName": + if e.complexity.UserTeamInfo.TeamName == nil { + break + } + + return e.complexity.UserTeamInfo.TeamName(childComplexity), true + case "UserTeamInfo.teamRole": + if e.complexity.UserTeamInfo.TeamRole == nil { + break + } + + return e.complexity.UserTeamInfo.TeamRole(childComplexity), true + case "WebFeatureSet.description": if e.complexity.WebFeatureSet.Description == nil { break } return e.complexity.WebFeatureSet.Description(childComplexity), true - case "WebFeatureSet.enabled": if e.complexity.WebFeatureSet.Enabled == nil { break } return e.complexity.WebFeatureSet.Enabled(childComplexity), true - case "WebFeatureSet.id": if e.complexity.WebFeatureSet.ID == nil { break } return e.complexity.WebFeatureSet.ID(childComplexity), true - case "WebFeatureSet.icon": if e.complexity.WebFeatureSet.Icon == nil { break } return e.complexity.WebFeatureSet.Icon(childComplexity), true - case "WebFeatureSet.label": if e.complexity.WebFeatureSet.Label == nil { break @@ -5027,69 +6073,64 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.WebFeatureSet.Label(childComplexity), true - case "WebServiceConfig.bundleVersion": - if e.complexity.WebServiceConfig.BundleVersion == nil { - break - } - - return e.complexity.WebServiceConfig.BundleVersion(childComplexity), true - - case "WebServiceConfig.description": - if e.complexity.WebServiceConfig.Description == nil { - break - } - - return e.complexity.WebServiceConfig.Description(childComplexity), true - - case "WebServiceConfig.id": - if e.complexity.WebServiceConfig.ID == nil { - break - } - - return e.complexity.WebServiceConfig.ID(childComplexity), true - - case "WebServiceConfig.name": - if e.complexity.WebServiceConfig.Name == nil { - break - } - - return e.complexity.WebServiceConfig.Name(childComplexity), true - } return 0, false } func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { - rc := graphql.GetOperationContext(ctx) - ec := executionContext{rc, e} + opCtx := graphql.GetOperationContext(ctx) + ec := executionContext{opCtx, e, 0, 0, make(chan graphql.DeferredResult)} inputUnmarshalMap := graphql.BuildUnmarshalerMap( + ec.unmarshalInputAdminUserFilterInput, ec.unmarshalInputConnectionConfig, + ec.unmarshalInputDataTransferOutputSettingsInput, ec.unmarshalInputDataTransferParameters, ec.unmarshalInputNavigatorSettingsInput, ec.unmarshalInputNetworkHandlerConfigInput, ec.unmarshalInputObjectPropertyFilter, + ec.unmarshalInputPageInput, + ec.unmarshalInputRMProjectPermissions, + ec.unmarshalInputRMSubjectProjectPermissions, ec.unmarshalInputSQLDataFilter, ec.unmarshalInputSQLDataFilterConstraint, ec.unmarshalInputSQLResultRow, + ec.unmarshalInputSQLResultRowMetaDataInput, ec.unmarshalInputServerConfigInput, ) first := true - switch rc.Operation.Operation { + switch opCtx.Operation.Operation { case ast.Query: return func(ctx context.Context) *graphql.Response { - if !first { - return nil + var response graphql.Response + var data graphql.Marshaler + if first { + first = false + ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) + data = ec._queryMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error) { + return ec._Query(ctx, opCtx.Operation.SelectionSet), nil + }) + } else { + if atomic.LoadInt32(&ec.pendingDeferred) > 0 { + result := <-ec.deferredResults + atomic.AddInt32(&ec.pendingDeferred, -1) + data = result.Result + response.Path = result.Path + response.Label = result.Label + response.Errors = result.Errors + } else { + return nil + } } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - data := ec._Query(ctx, rc.Operation.SelectionSet) var buf bytes.Buffer data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), + response.Data = buf.Bytes() + if atomic.LoadInt32(&ec.deferred) > 0 { + hasNext := atomic.LoadInt32(&ec.pendingDeferred) > 0 + response.HasNext = &hasNext } + + return &response } case ast.Mutation: return func(ctx context.Context) *graphql.Response { @@ -5098,7 +6139,9 @@ func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { } first = false ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - data := ec._Mutation(ctx, rc.Operation.SelectionSet) + data := ec._mutationMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error) { + return ec._Mutation(ctx, opCtx.Operation.SelectionSet), nil + }) var buf bytes.Buffer data.MarshalGQL(&buf) @@ -5115,20 +6158,42 @@ func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { type executionContext struct { *graphql.OperationContext *executableSchema + deferred int32 + pendingDeferred int32 + deferredResults chan graphql.DeferredResult +} + +func (ec *executionContext) processDeferredGroup(dg graphql.DeferredGroup) { + atomic.AddInt32(&ec.pendingDeferred, 1) + go func() { + ctx := graphql.WithFreshResponseContext(dg.Context) + dg.FieldSet.Dispatch(ctx) + ds := graphql.DeferredResult{ + Path: dg.Path, + Label: dg.Label, + Result: dg.FieldSet, + Errors: graphql.GetErrors(ctx), + } + // null fields should bubble up + if dg.FieldSet.Invalids > 0 { + ds.Result = graphql.Null + } + ec.deferredResults <- ds + }() } func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { if ec.DisableIntrospection { return nil, errors.New("introspection disabled") } - return introspection.WrapSchema(parsedSchema), nil + return introspection.WrapSchema(ec.Schema()), nil } func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { if ec.DisableIntrospection { return nil, errors.New("introspection disabled") } - return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]), nil + return introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil } var sources = []*ast.Source{ @@ -5136,6 +6201,14 @@ var sources = []*ast.Source{ scalar Object # Date/Time scalar DateTime +scalar Date + +input PageInput { + limit: Int + offset: Int +} + +directive @since(version: String!) repeatable on OBJECT|SCALAR|QUERY|MUTATION|FIELD|VARIABLE_DEFINITION|OBJECT|FIELD_DEFINITION|ARGUMENT_DEFINITION|INTERFACE|ENUM|ENUM_VALUE|INPUT_OBJECT|INPUT_FIELD_DEFINITION type Query @@ -5149,7 +6222,7 @@ schema { {Name: "../schema/service.admin.graphqls", Input: ` enum AdminSubjectType { user, - role + team } type AdminConnectionGrantInfo { @@ -5159,6 +6232,22 @@ type AdminConnectionGrantInfo { subjectType: AdminSubjectType! } +type AdminUserTeamGrantInfo @since(version: "24.0.5"){ + userId: ID! + teamRole: String +} + +type AdminObjectPermissions { + objectId: ID! + permissions: [String!]! +} + +type AdminObjectGrantInfo { + subjectId: ID! + subjectType: AdminSubjectType! + objectPermissions: AdminObjectPermissions! +} + type AdminConnectionSearchInfo { displayName: String! host: String! @@ -5172,24 +6261,33 @@ type AdminUserInfo { metaParameters: Object! configurationParameters: Object! - grantedRoles: [ID!]! + grantedTeams: [ID!]! grantedConnections: [AdminConnectionGrantInfo!]! origins: [ObjectOrigin!]! linkedAuthProviders: [String!]! enabled: Boolean! + authRole: String + + disableDate: DateTime @since(version: "25.0.2") + disabledBy: String @since(version: "25.0.2") + disableReason: String @since(version: "25.0.2") + } -type AdminRoleInfo { - roleId: ID! - roleName: String +type AdminTeamInfo { + teamId: ID! + teamName: String description: String + metaParameters: Object! + grantedUsers: [ID!]! + grantedUsersInfo: [AdminUserTeamGrantInfo!]! @since(version: "24.0.5") grantedConnections: [AdminConnectionGrantInfo!]! - rolePermissions: [ID!]! + teamPermissions: [ID!]! } type AdminPermissionInfo { @@ -5216,6 +6314,8 @@ type AdminAuthProviderConfiguration { signOutLink: String redirectLink: String metadataLink: String + acsLink: String + entityIdLink: String @since(version: "24.2.1") } type WebFeatureSet { @@ -5229,7 +6329,7 @@ type WebFeatureSet { input ServerConfigInput { serverName: String - serverURL: String + serverURL: String @deprecated adminName: String adminPassword: String @@ -5240,67 +6340,114 @@ input ServerConfigInput { publicCredentialsSaveEnabled: Boolean adminCredentialsSaveEnabled: Boolean resourceManagerEnabled: Boolean + secretManagerEnabled: Boolean @since(version: "24.3.2") enabledFeatures: [ID!] enabledAuthProviders: [ID!] disabledDrivers: [ID!] sessionExpireTime: Int + forceHttps: Boolean @since(version: "25.1.3") + supportedHosts: [String!] @since(version: "25.1.3") + bindSessionToIp: String @since(version: "25.1.4") } -extend type Query { - - #### Users and roles +input AdminUserFilterInput { + userIdMask: String + enabledState: Boolean +} - listUsers(userId: ID): [AdminUserInfo!]! - listRoles(roleId: ID): [AdminRoleInfo!]! +extend type Query { + #### Users and teams + + "Returns information about user by userId" + adminUserInfo(userId: ID!): AdminUserInfo! + "Returns all users with pagination and filter" + listUsers(page: PageInput!, filter: AdminUserFilterInput!): [AdminUserInfo!]! + "Returns information about team by teamId. If teamId is not provided, returns information about all teams" + listTeams(teamId: ID): [AdminTeamInfo!]! + "Returns all permissions" listPermissions: [AdminPermissionInfo!]! - - createUser(userId: ID!): AdminUserInfo! + "Returns all auth roles based on the license" + listAuthRoles: [String!]! + "Returns all team roles" + listTeamRoles: [String!]! + "Returns teams meta parameters for displaying in the UI" + listTeamMetaParameters: [ObjectPropertyInfo!]! + + "Creates a new user with the specified userId" + createUser(userId: ID!, enabled: Boolean!, authRole: String): AdminUserInfo! + "Deletes user by userId" deleteUser(userId: ID!): Boolean - createRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - updateRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - deleteRole(roleId: ID!): Boolean + "Creates a new team with the specified teamId" + createTeam(teamId: ID!, teamName: String, description: String): AdminTeamInfo! + "Updates team information by teamId" + updateTeam(teamId: ID!, teamName: String, description: String): AdminTeamInfo! + "Deletes team by teamId" + deleteTeam(teamId: ID!, force: Boolean): Boolean - grantUserRole(userId: ID!, roleId: ID!): Boolean - revokeUserRole(userId: ID!, roleId: ID!): Boolean + "Grants user to team with the specified userId and teamId" + grantUserTeam(userId: ID!, teamId: ID!): Boolean + "Revokes user from team with the specified userId and teamId" + revokeUserTeam(userId: ID!, teamId: ID!): Boolean - setSubjectPermissions(roleId: ID!, permissions: [ID!]!): [AdminPermissionInfo!]! + "Sets permissions to the subject (user or team) with the specified subjectId" + setSubjectPermissions(subjectId: ID!, permissions: [ID!]!): [AdminPermissionInfo!]! + "Sets user credentials for the specified userId and providerId" setUserCredentials(userId: ID!, providerId: ID!, credentials: Object!): Boolean + "Deletes user credentials for the specified userId and providerId" + deleteUserCredentials(userId: ID!, providerId: ID!): Boolean + + "Enables or disables user by userId" enableUser(userId: ID!, enabled: Boolean!): Boolean - #### Connection management + "Sets user auth role for the specified userId" + setUserAuthRole(userId: ID!, authRole: String): Boolean - # All connection configurations - allConnections( id: ID ): [ ConnectionInfo! ]! + "Sets user team role for the specified userId and teamId" + setUserTeamRole(userId: ID!, teamId: ID!, teamRole: String): Boolean @since(version: "24.0.5") - searchConnections( hostNames: [String!]! ): [AdminConnectionSearchInfo!]! + #### Connection management - createConnectionConfiguration( config: ConnectionConfig! ): ConnectionInfo! - copyConnectionConfiguration( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! - updateConnectionConfiguration( id: ID!, config: ConnectionConfig! ): ConnectionInfo! - deleteConnectionConfiguration( id: ID! ): Boolean + "Finds available connections by host names" + searchConnections( hostNames: [String!]! ): [AdminConnectionSearchInfo!]! # Permissions - getConnectionSubjectAccess(connectionId: ID): [AdminConnectionGrantInfo!]! - setConnectionSubjectAccess(connectionId: ID!, subjects: [ID!]!): Boolean + "Returns all subjects (users and teams) that have access to the specified connection" + getConnectionSubjectAccess(projectId: ID!, connectionId: ID): [AdminConnectionGrantInfo!]! + + "Sets access to the connection for the specified subjects (users and teams)" + setConnectionSubjectAccess(projectId: ID!, connectionId: ID!, subjects: [ID!]!): Boolean @deprecated(reason: "use addConnectionsAccess (23.2.2)") + + "Sets access to the connections for the specified subjects (users and teams)" + addConnectionsAccess(projectId: ID!, connectionIds: [ID!]!, subjects: [ID!]!): Boolean @since(version: "23.2.2") + + "Deletes access to the connections for the specified subjects (users and teams)" + deleteConnectionsAccess(projectId: ID!, connectionIds: [ID!]!, subjects: [ID!]!): Boolean @since(version: "23.2.2") + + "Returns all connections that the subject (user or team) has access to" + getSubjectConnectionAccess(subjectId: ID!): [AdminConnectionGrantInfo!]! - getSubjectConnectionAccess(subjectId: ID): [AdminConnectionGrantInfo!]! - setSubjectConnectionAccess(subjectId: ID!, connections: [ID!]!): Boolean + "Sets access for a subject (user or team) to the specified connections" + setSubjectConnectionAccess(subjectId: ID!, connections: [ID!]!): Boolean @deprecated(reason: "23.2.2") #### Feature sets + "Returns all available feature sets that can be enabled or disabled" listFeatureSets: [WebFeatureSet!]! #### Auth providers and configurations + "Returns all properties of the auth provider with the specified providerId" listAuthProviderConfigurationParameters(providerId: ID!): [ObjectPropertyInfo!]! + "Returns all auth provider configurations for the specified providerId. If providerId is not provided, returns all configurations" listAuthProviderConfigurations(providerId: ID): [AdminAuthProviderConfiguration!]! + "Saves auth provider configuration with the specified parameters" saveAuthProviderConfiguration( providerId: ID!, id: ID!, @@ -5308,25 +6455,40 @@ extend type Query { disabled: Boolean, iconURL: String description: String - parameters: Object): AdminAuthProviderConfiguration! + parameters: Object + ): AdminAuthProviderConfiguration! + + "Deletes auth provider configuration by id" deleteAuthProviderConfiguration(id: ID!): Boolean! #### User profile + "Not implemented yet" saveUserMetaParameter(id: ID!, displayName: String!, description: String, required: Boolean!): ObjectPropertyInfo! + "Not implemented yet" deleteUserMetaParameter(id: ID!): Boolean! + "Sets user meta parameters values for the specified userId" setUserMetaParameterValues(userId: ID!, parameters: Object!): Boolean! + "Sets team meta parameters values for the specified teamId" + setTeamMetaParameterValues(teamId: ID!, parameters: Object!): Boolean! + #### Global configuration + "Saves server configuration" configureServer(configuration: ServerConfigInput!): Boolean! - # Changes default navigator settings + "Changes default navigator settings" setDefaultNavigatorSettings( settings: NavigatorSettingsInput!): Boolean! } + +extend type Mutation { + "Updates product configuration" + adminUpdateProductConfiguration(configuration: Object!): Boolean! @since(version: "23.3.4") +} `, BuiltIn: false}, {Name: "../schema/service.auth.graphqls", Input: `enum AuthCredentialEncryption { none, @@ -5360,16 +6522,22 @@ type AuthProviderConfiguration { id: ID! displayName: String! disabled: Boolean! + authRoleProvided: Boolean iconURL: String description: String - # URL to external authentication service. - # If specified then it is external auhentication provider (SSO). - # Otherwise authLogin function must be called. + """ + URL to external authentication service. + If specified then it is external authentication provider (SSO). + Otherwise authLogin function must be called. + """ signInLink: String signOutLink: String + redirectLink: String metadataLink: String + acsLink: String + entityIdLink: String @since(version: "24.2.1") } type AuthProviderCredentialsProfile { @@ -5386,96 +6554,156 @@ type AuthProviderInfo { description: String defaultProvider: Boolean! + trusted: Boolean! + private: Boolean! + authHidden: Boolean! @since(version: "24.2.4") + supportProvisioning: Boolean! - # Configurable providers must be configured first. See configurations field. + "Configurable providers must be configured first. See configurations field." configurable: Boolean! + "Federated providers means authorization must occur asynchronously through redirects." + federated: Boolean! - # Provider configurations (applicable only if configurable=true) + "Provider configurations (applicable only if configurable=true)" configurations: [AuthProviderConfiguration!] + templateConfiguration: AuthProviderConfiguration! @since(version: "24.1.2") + credentialProfiles: [AuthProviderCredentialsProfile!]! requiredFeatures: [String!]! + + required: Boolean! } + type AuthInfo { - redirectLink: String + redirectLink: String @deprecated - authId: String + authId: String @deprecated - authStatus: AuthStatus! + authStatus: AuthStatus! @deprecated userTokens: [UserAuthToken!] } +type FederatedAuthInfo @since(version: "25.0.3") { + redirectLink: String! + taskInfo: AsyncTaskInfo! +} + +type FederatedAuthResult @since(version: "25.0.3") { + userTokens: [UserAuthToken!]! @since(version: "25.0.3") +} + +type LogoutInfo @since(version: "23.3.3") { + redirectLinks: [String!]! +} + type UserAuthToken { - # Auth provider used for authorization + "Auth provider used for authorization" authProvider: ID! - # Auth provider configuration ID + "Auth provider configuration ID" authConfiguration: ID - # Authorization time + "Authorization time" loginTime: DateTime! - # User identity (aka user name) specific to auth provider + "User identity (aka user name) specific to auth provider" userId: String! - # User display name specific to auth provider + "User display name specific to auth provider" displayName: String! - # Optional login message + "Optional login message" message: String - # Auth origin + "Auth origin" origin: ObjectOrigin! } type UserInfo { - # User unique identifier + "User unique identifier" userId: ID! - # Human readable display name. It is taken from the first auth provider which was used for user login. + "Human readable display name. It is taken from the first auth provider which was used for user login." displayName: String + "User auth role ID. Optional." + authRole: ID + "All authentication tokens used during current session" authTokens: [UserAuthToken!]! linkedAuthProviders: [String!]! - # User profile properties map + "User profile properties map" metaParameters: Object! - - # USer configuiraiton parameters + "User configuration parameters" configurationParameters: Object! + "User teams" + teams: [UserTeamInfo!]! + + "Indicates whether the user is anonymous (not authenticated)." + isAnonymous: Boolean! @since(version: "24.2.3") +} + +type UserTeamInfo { + teamId: String! + teamName: String! + teamRole: String } extend type Query { - # Authorize user using specified auth provider. If linkUser=true then associates new - authLogin(provider: ID!, configuration: ID, credentials: Object, linkUser: Boolean): AuthInfo! + """ + Authorizes the user using specified auth provider. + Associates new credentials with the active user when linkUser=true. + Kills another user sessions if forceSessionsLogout=true. + """ + authLogin(provider: ID!, configuration: ID, credentials: Object, linkUser: Boolean, forceSessionsLogout: Boolean): AuthInfo! - authUpdateStatus(authId: ID!, linkUser: Boolean): AuthInfo! + "Returns result of federated authentication task" + federatedAuthTaskResult(taskId: String!): FederatedAuthResult! @since(version: "25.0.3") - # Logouts user. If provider not specified then all authorizations are revoked from session. - authLogout(provider: ID, configuration: ID): Boolean + authUpdateStatus(authId: ID!, linkUser: Boolean): AuthInfo! @deprecated - # Active user information. null is no user was authorized within session + "Same as authLogoutExtended but without additional information" + authLogout(provider: ID, configuration: ID): Boolean @deprecated(reason: "use authLogoutExtended instead") + + "Logouts user. If provider not specified then all authorizations are revoked from session. Contains additional information" + authLogoutExtended(provider: ID, configuration: ID): LogoutInfo! @since(version: "23.3.3") + + "Active user information. null is no user was authorized within session" activeUser: UserInfo + "Returns list of all available auth providers" authProviders: [AuthProviderInfo!]! + "Changes the local password of the current user" authChangeLocalPassword(oldPassword: String!, newPassword: String!): Boolean! + "Returns properties that can be shown in user profile" listUserProfileProperties: [ObjectPropertyInfo!]! } + extend type Mutation { - # Set user config parameter. If parameter value is null then removes the parameter + "Set user config parameter. If parameter value is null then removes the parameter" setUserConfigurationParameter(name: String!, value: Object): Boolean! + "Updates user preferences" + setUserPreferences(preferences: Object!): UserInfo! @since(version: "24.0.1") + "Creates async task for federated login. Returns redirect link to the task info page." + federatedLogin( + provider: ID!, + configuration: ID, + linkUser: Boolean, + forceSessionsLogout: Boolean + ): FederatedAuthInfo! @since(version: "25.0.3") } `, BuiltIn: false}, {Name: "../schema/service.core.graphqls", Input: ` @@ -5483,233 +6711,398 @@ extend type Mutation { # General stuff #################################################### -# Property - +""" +Information about the object property used to generate its UI +""" type ObjectPropertyInfo { - # ID + "Unique property identifier" id: String - # Human readable name + "Human-readable name" displayName: String - # Property description + "Property description" description: String - # Property category (may be used if object has a lot of properties) + "Usage hint for the property" + hint: String @since(version: "23.2.3") + "Property category (may be used if object has a lot of properties)" category: String - # Property data type (int, String, etc) + "Property data type (e.g., int, String)" dataType: String - - # Property value. Note: for some properties value reading may take a lot of time (e.g. RowCount for tables) + "Property value (can be resource-intensive for some properties, e.g., RowCount for tables)" value: Object - - # List of values this property can take. Makes sense only for enumerable properties + "List of allowed values (for enumerable properties)" validValues: [ Object ] - # Default property value + "Default property value" defaultValue: Object - - # Property value length + "Property value length" length: ObjectPropertyLength! - - # Supported features (system, hidden, inherited, foreign, expensive, etc) + "List of supported features (e.g., system, hidden, inherited, foreign, expensive)" features: [ String! ]! - # Order position + "Order position" order: Int! + "Supported configuration types (for driver properties)" + supportedConfigurationTypes: [ String! ] + "Is the property required" + required: Boolean! @since(version: "23.3.1") + "List of preference scopes (e.g., global, user)" + scopes: [String!] + "Dynamic conditions for the property (e.g., visibility or read-only)" + conditions: [Condition!] @since(version: "25.0.1") } enum ObjectPropertyLength { - # 1 character + "1 character" TINY, - # 20 characters + "20 characters" SHORT, - # <= 64 characters + "<= 64 characters" MEDIUM, - # Full line length. The default + "Full line length. The default" LONG, - # Multi-line long text + "Multi-line long text" MULTILINE } -# Async types +"Represents a dynamic condition for a property, such as visibility or read-only state" +type Condition @since(version: "25.0.1") { + "The logical expression that defines when the condition applies" + expression: String! + "The type of condition (e.g., HIDE or READ_ONLY)" + conditionType: ConditionType! +} + +enum ConditionType @since(version: "25.0.1") { + "hiding property condition" + HIDE, + "restriction for setting a property value" + READ_ONLY +} +""" +Async types +""" type AsyncTaskInfo { + "Task unique identifier" id: String! + "Async task name" name: String + "Indicates if the task is currently running" running: Boolean! + "Current status of the async task" status: String + "Error information if the task failed" error: ServerError - result: SQLExecuteInfo @deprecated # Deprecated. Use asyncSqlExecuteResults instead - # Task result. - # Can be some kind of identifier to obtain real result using another API function + """ + Task result. + Can be some kind of identifier to obtain real result using another API function + """ taskResult: Object } -# Various server errors descriptor +"Various server errors descriptor" type ServerError { + "Error message text" message: String + "Retrieves the vendor-specific error code" errorCode: String + "Type/category of the error" errorType: String + "Stack trace for debugging" stackTrace: String + "Nested error that caused this error (recursive)" causedBy: ServerError } type ServerMessage { + "The time when the server message was created" time: String + "The content of the message" message: String } -# Languages supported by server - +"Languages supported by server" type ServerLanguage { + "ISO 639-1 or similar language code (e.g., \"en\", \"ru\")" isoCode: String! + "Display name of the language in the current locale (e.g., \"English\")" displayName: String + "Native name of the language (e.g., \"English\", \"Русский\")" nativeName: String } -type WebServiceConfig { - id: String! - name: String! - description: String! - bundleVersion: String! +"Password policy configuration" +type PasswordPolicyConfig @since(version: "23.3.3") { + "Minimum password length" + minLength: Int! + "Minimum number of digits required" + minNumberCount: Int! + "Minimum number of symbols required" + minSymbolCount: Int! + "Require both uppercase and lowercase letters" + requireMixedCase: Boolean! } +"Product information" type ProductInfo { + "ID of the product" id: ID! + "The product version" version: String! + "The product name" name: String! + "The product description" description: String + "The build timestamp of the product" buildTime: String! + "The release timestamp of the product" releaseTime: String! + "Information about the product license" licenseInfo: String + "Information about the latest available version" latestVersionInfo: String + "URL for purchasing the product" + productPurchaseURL: String } +"Server configuration" type ServerConfig { + "Server name" name: String! + "Version of the server" version: String! + "ID of the server workspace" workspaceId: ID! - serverURL: String! - - rootURI: String! + "Defines if the anonymous access is enabled" + anonymousAccessEnabled: Boolean! + "Defines if non-admin users can create connections" + supportsCustomConnections: Boolean! + "Defines if resource manager is enabled" + resourceManagerEnabled: Boolean! - hostName: String! + "Defines if secret manager is enabled" + secretManagerEnabled: Boolean! @since(version: "24.3.2") - anonymousAccessEnabled: Boolean - authenticationEnabled: Boolean @deprecated - supportsCustomConnections: Boolean - supportsConnectionBrowser: Boolean - supportsWorkspaces: Boolean - resourceManagerEnabled: Boolean - - publicCredentialsSaveEnabled: Boolean - adminCredentialsSaveEnabled: Boolean + "Defines is it is possible to save user database credentials" + publicCredentialsSaveEnabled: Boolean! + "Defines is it is possible to save global database credentials" + adminCredentialsSaveEnabled: Boolean! + "Defines if the server requires a license" licenseRequired: Boolean! + "Defines if the server license is valid" licenseValid: Boolean! + "Returns information about the server license status" + licenseStatus: String @since(version: "24.1.5") - sessionExpireTime: Int - localHostAddress: String - - configurationMode: Boolean - developmentMode: Boolean - redirectOnFederatedAuth: Boolean + "Defines if the server is in configuration mode" + configurationMode: Boolean! + "Defines if the server is in development mode" + developmentMode: Boolean! + "Defines if the server is distributed" + distributed: Boolean! + "List of enabled features" enabledFeatures: [ID!]! - enabledAuthProviders: [ID!]! + "List of disabled beta features" + disabledBetaFeatures: [ID!] @since(version: "24.0.5") + "List of server features" + serverFeatures: [ID!] @since(version: "24.3.0") + "List of supported languages" supportedLanguages: [ ServerLanguage! ]! - services: [ WebServiceConfig ] + "Product configuration" productConfiguration: Object! + "Product information" productInfo: ProductInfo! + "Navigator settings for the server" defaultNavigatorSettings: NavigatorSettings! + "List of disabled drivers (IDs of DriverInfo)" disabledDrivers: [ID!]! + "Resource quotas (e.g., max amount of running SQL queries)" resourceQuotas: Object! } +type ProductSettingsGroup @since(version: "24.0.1") { + id: ID! + displayName: String! +} + +type ProductSettings @since(version: "24.0.1") { + groups: [ProductSettingsGroup!]! + "each property is associated with a group by category" + settings: [ObjectPropertyInfo!]! +} + type SessionInfo { + "The time when the session was created" createTime: String! + "The last time the session was accessed" lastAccessTime: String! + "The current locale of the session" locale: String! + "Indicates whether the session cache has expired" cacheExpired: Boolean! - serverMessages: [ ServerMessage ] + "List of active connections in the session" connections: [ ConnectionInfo! ]! + "Action parameters for the session (e.g., opening a connection)" actionParameters: Object + + "Indicates if the session is valid" + valid: Boolean! + "Remaining time before the session expires (in seconds)" + remainingTime: Int! } #################################################### -# Drivers and connections +"Drivers and connections" #################################################### type DatabaseAuthModel { + "Auth model unique ID" id: ID! + "Display name of the auth model" displayName: String! + "Description of the auth model" description: String + "Path to the auth model icon" icon: String - # checks if the auth model needs a configuration on a local file system + "Checks if the auth model needs a configuration on a local file system" requiresLocalConfiguration: Boolean + "Returns id of the required auth provider if the auth model requires it" + requiredAuth: String + "List of properties for the auth model that can be displayed in the UI" properties: [ObjectPropertyInfo!]! } type DriverInfo { + """ + Driver unique full ID. It is ` + "`" + `providerId + "." + driverId` + "`" + `. + It is recommended to use providerId and driverId separately. + """ id: ID! + "Name of the driver" name: String + "Description of the driver" description: String + "Path to the driver icon" icon: String + "Path to the driver icon for big size" iconBig: String - # Driver provider ID - providerId: ID - # Driver Java class name + "Driver ID. It is unique within provider" + driverId: ID! + "Driver provider ID. It is globally unique" + providerId: ID! + "Driver Java class name" driverClassName: String + "Default host for the driver" defaultHost: String + "Default port for the driver" defaultPort: String + "Default database name for the driver" defaultDatabase: String + "Default server name for the driver" defaultServer: String + "Default user name for the driver" defaultUser: String + "Default connection URL for the driver" sampleURL: String + "Returns link to the driver documentation page" driverInfoURL: String + "Returns link to the driver properties page" driverPropertiesURL: String + "Defines if the database for this driver is embedded" embedded: Boolean + "Defines if the driver is enabled" enabled: Boolean! - requiresServerName: Boolean - - # this fields must be removed and be replaced by DriverAuthModel - allowsEmptyPassword: Boolean @deprecated - + "Defines if the driver page requires server name field" + requiresServerName: Boolean @deprecated(reason: "use mainProperties instead") + "Defines if the driver page requires database name field" + requiresDatabaseName: Boolean @deprecated(reason: "use mainProperties instead") + "Defines if host, port, database, server name fields are using a custom page" + useCustomPage: Boolean! @since(version: "24.1.2") + + "Defines if driver license is required" licenseRequired: Boolean + "Driver license information" license: String + "Defines if the driver is a custom driver" custom: Boolean - # Driver score for ordering, biggest first + "Driver score for ordering, biggest first" promotedScore: Int - # Never used? - #connectionProperties: Object - #defaultConnectionProperties: Object - - # Driver properties. - # Note: it is expensive property and it may produce database server roundtrips. - # Call it only when you really need it. - # These properties are for advanced users in usually shouldn't be specified for new connections. + """ + Driver properties. + Note: it is expensive property and it may produce database server roundtrips. + Call it only when you really need it. + These properties are for advanced users in usually shouldn't be specified for new connections. + """ driverProperties: [ObjectPropertyInfo!]! - # Driver parameters (map name->value) + "Driver parameters (map name->value)" driverParameters: Object! - # Additional driver provider properties - # These properties can be configured by user on main connection page - # to provide important connection settings + """ + Main driver properties. + Contains info about main fields (host, port, database, server name) that are used in main connection page + """ + mainProperties: [ObjectPropertyInfo!]! @since(version: "24.1.2") + + """ + Additional driver provider properties. + These properties can be configured by user on main connection page to provide important connection settings + """ providerProperties: [ObjectPropertyInfo!]! - # False for drivers which do not support authentication - anonymousAccess: Boolean + "Expert driver settings properties. Returns properties (like keep-alive interval) that are not often used and can be hidden in UI" + expertSettingsProperties: [ObjectPropertyInfo!]! @since(version: "25.2.1") + "False for drivers which do not support authentication." + anonymousAccess: Boolean + "Default auth model that is used for this driver (see authModels)" defaultAuthModel: ID! + "List of auth models that can be used with this driver (see authModels)" applicableAuthModels: [ID!]! - + "List of network handlers that can be used with this driver (SSH/SSL)" applicableNetworkHandlers: [ID]! + "Configuration types are used in UI to determine how to display connection settings (show host/port/database fields or use URL field)" + configurationTypes: [DriverConfigurationType]! + + "Defines if the driver can be downloaded remotely" + downloadable: Boolean! @since(version: "24.3.3") + "Defines if the driver is installed on the server" + driverInstalled: Boolean! + "List of driver libraries that are used for connecting to the database" + driverLibraries: [DriverLibraryInfo!]! + "Defines if embedded driver is safe to use in the server" + safeEmbeddedDriver: Boolean! @since(version: "25.0.0") +} + +"Driver library information. Used to display driver files in UI" +type DriverLibraryInfo { + "Driver library unique ID" + id: ID! + "Driver library name" + name: String! + "Path to the driver library icon" + icon: String + "List of files that are used by the driver" + libraryFiles: [DriverFileInfo!] +} + +"Driver file information." +type DriverFileInfo @since(version: "24.3.2") { + "Driver file unique ID" + id: ID! + "Driver file name" + fileName: String! + "Path to the driver file icon" + icon: String } enum ResultDataFormat { @@ -5719,6 +7112,13 @@ enum ResultDataFormat { timeseries } +enum DriverConfigurationType { + "Driver uses host, port, database and server name fields" + MANUAL, + "Driver uses URL field" + URL +} + ## Network handler config enum NetworkHandlerType { @@ -5727,12 +7127,17 @@ enum NetworkHandlerType { CONFIG } +"SSH network handler authentication type" enum NetworkHandlerAuthType { PASSWORD, PUBLIC_KEY, AGENT } +""" +Network handler descriptor. +This descriptor is used to describe network handlers (SSH/SSL) that can be used for connections. +""" type NetworkHandlerDescriptor { id: ID! codeName: String! @@ -5740,26 +7145,47 @@ type NetworkHandlerDescriptor { description: String secured: Boolean! type: NetworkHandlerType + "Properties that can be displayed in the UI" properties: [ObjectPropertyInfo!]! } +""" +SSH/SSL network handler config. Name without prefix only for backward compatibility +""" type NetworkHandlerConfig { id: ID! + "Defines if the network handler is enabled" enabled: Boolean! - authType: NetworkHandlerAuthType! + "SSH network handler auth type" + authType: NetworkHandlerAuthType! @deprecated(reason: "use properties") + "SSH network handler user name" userName: String + "SSH network handler user password" password: String - key: String + "SSH network handler private key" + key: String @deprecated(reason: "use secured properties") + "A flag that indicates if the password should be saved in the secure storage" savePassword: Boolean! + "Network handler properties (name/value)" properties: Object! + "Network handler secure properties (name/value). Used for passwords and keys" + secureProperties: Object! } -# Connection instance +type SecretInfo { + displayName: String! + secretId: String! +} + +"Connection instance" type ConnectionInfo { + "Connection unique ID" id: ID! + "ID of the driver that is used for this connection (see DriverInfo)" driverId: ID! - + "Connection name" name: String! + "Connection description" description: String host: String @@ -5768,40 +7194,89 @@ type ConnectionInfo { databaseName: String url: String - properties: Object + "Main connection properties. Contains host, port, database, server name fields" + mainPropertyValues: Object @since(version: "24.1.2") + + "Expert connection settings. Contains expert settings properties (like keep-alive interval or auto-commit) that are not often used" + expertSettingsValues: Object @since(version: "25.2.1") - template: Boolean! + "Connection keep-alive interval in seconds" + keepAliveInterval: Int! + "Defines if the connection is in auto-commit mode" + autocommit: Boolean + + properties: Object + "Indicates if the connection is already connected to the database" connected: Boolean! provided: Boolean! + "Indicates if the connection is read-only (no data modification allowed)" readOnly: Boolean! + "Forces connection URL use, host/port/database parameters will be ignored" useUrl: Boolean! + + "Forces credentials save. This flag doesn't work in shared projects." saveCredentials: Boolean! + "Shared credentials - the same for all users, stored in secure storage." + sharedCredentials: Boolean! + + sharedSecrets: [SecretInfo!]! @since(version: "23.3.5") + """ + Determines that credentials were saved for current user. + This field read is slow, it should be read only when it really needed + """ + credentialsSaved: Boolean! + """ + Determines that additional credentials are needed to connect + This field read is slow, it should be read only when it really needed + """ + authNeeded: Boolean! + "ID of the connection folder where this connection is stored" folder: ID + "Node path of the connection in the navigator" nodePath: String + "Connection time in ISO format" connectTime: String + "Connection error if any" connectionError: ServerError + "Server version that is used for this connection" serverVersion: String + "Client version that is used for this connection" clientVersion: String origin: ObjectOrigin! - authNeeded: Boolean! + "ID of the auth model that is used for this connection (see authModels)" authModel: ID authProperties: [ObjectPropertyInfo!]! providerProperties: Object! networkHandlersConfig: [NetworkHandlerConfig!]! - # Supported features (provided etc) + "Supported features (provided etc)" features: [ String! ]! navigatorSettings: NavigatorSettings! supportedDataFormats: [ ResultDataFormat! ]! + configurationType: DriverConfigurationType + + #Access properties + canViewSettings: Boolean! + canEdit: Boolean! + canDelete: Boolean! + + projectId: ID! + requiredAuth: String + defaultCatalogName: String @since(version: "25.0.5") + defaultSchemaName: String @since(version: "25.0.5") + + "List of tools that can be used with this connection. Returns empty list if no tools are available" + tools: [String!]! @since(version: "24.1.3") } type ConnectionFolderInfo { id: ID! + projectId: ID! description: String } @@ -5830,6 +7305,27 @@ type NavigatorSettings { hideVirtualModel: Boolean! } +type RMResourceType { + id: String! + displayName: String! + icon: String + fileExtensions: [String!]! + rootFolder: String +} + +type ProjectInfo { + id: String! + global: Boolean! + shared: Boolean! + name: String! + description: String + canEditDataSources: Boolean! + canViewDataSources: Boolean! + canEditResources: Boolean! + canViewResources: Boolean! + resourceTypes: [RMResourceType!]! +} + type LogEntry { time: DateTime type: String! @@ -5853,68 +7349,98 @@ input NavigatorSettingsInput { input NetworkHandlerConfigInput { id: ID! + "Defines if the network handler should be enabled" enabled: Boolean - authType: NetworkHandlerAuthType + "Network handler type (TUNNEL, PROXY, CONFIG)" + authType: NetworkHandlerAuthType @deprecated (reason: "use properties") + "Sets user name for the network handler (SSH)" userName: String + "Sets user password for the network handler (SSH)" password: String - key: String + "Sets private key for the network handler (SSH)" + key: String @deprecated(reason: "use secured properties") + "Sets a flag that indicates if the password should be saved in the secure storage" savePassword: Boolean + "Network handler properties (name/value)" properties: Object + "Network handler secure properties (name/value). Used for passwords and keys" + secureProperties: Object } -# Configuration of particular connection. Used for new connection create. Includes auth info +"Configuration of particular connection. Used for new connection create. Includes auth info" input ConnectionConfig { - # used only for testing created connection + "used only for testing created connection" connectionId: String name: String description: String - # ID of template connection - templateId: ID - # ID of database driver + "ID of database driver" driverId: ID # Custom connection parameters (all optional) - host: String port: String serverName: String databaseName: String - # Connection url jdbc:{driver}://{host}[:{port}]/[{database}] + + "Host, port, serverName, databaseName are also stored in mainPropertyValues for custom pages" + mainPropertyValues: Object @since(version: "24.1.2") + + "Keep-alive, auto-commit, read-only and other expert settings are stored in expertSettingsValues" + expertSettingsValues: Object @since(version: "25.2.1") + + "Sets connection URL jdbc:{driver}://{host}[:{port}]/[{database}]" url: String - # Properties + + "Set properties list" properties: Object - # Template connection - template: Boolean - # Read-onyl connection - readOnly: Boolean + "Set keep-alive interval" + keepAliveInterval: Int @deprecated(reason: "25.2.1 use expertPropertyValues instead") + + "Sets auto-commit connection state" + autocommit: Boolean @deprecated(reason: "25.2.1 use expertPropertyValues instead") + + "Sets read-only connection state" + readOnly: Boolean @deprecated(reason: "25.2.1 use expertPropertyValues instead") # User credentials + "Flag for saving credentials in secure storage" saveCredentials: Boolean + "Flag for using shared credentials." + sharedCredentials: Boolean + "Auth model ID that will be used for connection" authModelId: ID + "Secret ID that will be used for connection" + selectedSecretId: ID @since(version: "23.3.5") + "Credentials for the connection (usually user name and password but it may vary for different auth models)" credentials: Object - # Map of provider properties (name/value) - + "Returns map of provider properties (name/value)" providerProperties: Object - # Network handlers. Map of id->property map (name/value). - + "Returns network handlers configuration. Map of id->property map (name/value)." networkHandlersConfig: [NetworkHandlerConfigInput!] #### deprecated fields - # ID of predefined datasource - dataSourceId: ID #@deprecated + "ID of predefined datasource" + dataSourceId: ID @deprecated - # Direct user credentials - userName: String #@deprecated - userPassword: String #@deprecated + "Direct user credentials" + userName: String @deprecated(reason: "use credentials") + userPassword: String @deprecated(reason: "use credentials") - # Folder + "Defines in which connection folder the connection should be created" folder: ID + + "Configuration type (MANUAL, URL)" + configurationType: DriverConfigurationType + "Sets catalog name for the connection" + defaultCatalogName: String @since(version: "25.0.5") @deprecated(reason: "25.2.1 use expertPropertyValues instead") + "Sets schema name for the connection" + defaultSchemaName: String @since(version: "25.0.5") @deprecated(reason: "25.2.1 use expertPropertyValues instead") } #################################################### @@ -5922,100 +7448,109 @@ input ConnectionConfig { #################################################### extend type Query { - # Returns server config + "Returns server config" serverConfig: ServerConfig! + "Returns server system information properties" + systemInfo: [ObjectPropertyInfo!]! @since(version: "24.3.5") + + "Returns product settings" + productSettings: ProductSettings! @since(version: "24.0.1") - # Returns session state ( initialize if not ) + "Returns session state ( initialize if not )" sessionState: SessionInfo! - # Session permissions + "Returns session permissions" sessionPermissions: [ID]! - # Get driver info + "Returns list of available drivers" driverList( id: ID ): [ DriverInfo! ]! + "Returns list of available database auth models" authModels: [DatabaseAuthModel!]! + "Returns list of available network handlers" networkHandlers: [NetworkHandlerDescriptor!]! - # List of user connections. - userConnections( id: ID ): [ ConnectionInfo! ]! - # List of template connections. - templateConnections: [ ConnectionInfo! ]! + "Returns list of user connections" + userConnections( projectId: ID, id: ID, projectIds: [ID!] ): [ ConnectionInfo! ]! - # List of connection folders - connectionFolders( path: ID ): [ ConnectionFolderInfo! ]! + "Returns list of connection folders" + connectionFolders( projectId: ID, path: ID ): [ ConnectionFolderInfo! ]! - # Return connection state - connectionState( id: ID! ): ConnectionInfo! @deprecated + "Returns connection info" + connectionInfo( projectId: ID!, id: ID! ): ConnectionInfo! - # Return connection info - connectionInfo( id: ID! ): ConnectionInfo! + "Returns list of accessible user projects" + listProjects: [ ProjectInfo! ]! + "Reads session log entries" readSessionLog(maxEntries: Int, clearEntries: Boolean): [ LogEntry! ]! } extend type Mutation { - # Initialize session + "Initialize session" openSession(defaultLocale: String): SessionInfo! - # Destroy session + "Destroy session" closeSession: Boolean - # Refreshes session on server and returns its state - touchSession: Boolean + "Refreshes session on server and returns its state" + touchSession: Boolean @deprecated(reason: "use events to update session") + "Refreshes session on server and returns session state" + updateSession: SessionInfo! @since(version: "24.0.0") @deprecated(reason: "use events to update session") - # Refresh session connection list + "Refresh session connection list" refreshSessionConnections: Boolean - # Refreshes session on server and returns its state + "Change session language to specified" changeSessionLanguage(locale: String): Boolean - # Create new custom connection. Custom connections exist only within the current session. - createConnection( config: ConnectionConfig! ): ConnectionInfo! + "Create new custom connection" + createConnection( config: ConnectionConfig!, projectId: ID ): ConnectionInfo! - updateConnection( config: ConnectionConfig! ): ConnectionInfo! + "Update specified connection" + updateConnection( config: ConnectionConfig!, projectId: ID ): ConnectionInfo! - deleteConnection( id: ID! ): Boolean! + "Delete specified connection" + deleteConnection( id: ID!, projectId: ID ): Boolean! - createConnectionFromTemplate( templateId: ID!, connectionName: String ): ConnectionInfo! + "Create new folder for connections" + createConnectionFolder(parentFolderPath: ID, folderName: String!, projectId: ID ): ConnectionFolderInfo! - # Create new folder - createConnectionFolder(parentFolderPath: ID, folderName: String! ): ConnectionFolderInfo! + "Delete specified connection folder" + deleteConnectionFolder( folderPath: ID!, projectId: ID ): Boolean! - deleteConnectionFolder( folderPath: ID! ): Boolean! + "Copies connection configuration from node" + copyConnectionFromNode( nodePath: String!, config: ConnectionConfig, projectId: ID ): ConnectionInfo! - # Copies connection configuration from node - copyConnectionFromNode( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! + "Test connection configuration. Returns remote server version" + testConnection( config: ConnectionConfig!, projectId: ID): ConnectionInfo! - # Test connection configuration. Returns remote server version - testConnection( config: ConnectionConfig! ): ConnectionInfo! - - # Test connection configuration. Returns remote server version + "Test network handler" testNetworkHandler( config: NetworkHandlerConfigInput! ): NetworkEndpointInfo! - # Initiate existing connection - initConnection( id: ID!, credentials: Object, networkCredentials: [NetworkHandlerConfigInput!], saveCredentials: Boolean ): ConnectionInfo! + "Initiate existing connection" + initConnection( + id: ID!, + projectId: ID, + credentials: Object, + networkCredentials: [NetworkHandlerConfigInput!], + saveCredentials:Boolean, + sharedCredentials: Boolean, + selectedSecretId:String + ): ConnectionInfo! - # Disconnect from database - closeConnection( id: ID! ): ConnectionInfo! + "Disconnect from database" + closeConnection( id: ID!, projectId: ID ): ConnectionInfo! - # Changes navigator settings for connection - setConnectionNavigatorSettings( id: ID!, settings: NavigatorSettingsInput!): ConnectionInfo! + "Change navigator settings for connection" + setConnectionNavigatorSettings( id: ID!, projectId: ID, settings: NavigatorSettingsInput!): ConnectionInfo! #### Generic async functions + "Cancel async task by ID" asyncTaskCancel(id: String!): Boolean + "Get async task info by ID" asyncTaskInfo(id: String!, removeOnFinish: Boolean!): AsyncTaskInfo! - - - #### Deprecated API - - # Create connection from template. Use createConnection instead - openConnection( config: ConnectionConfig! ): ConnectionInfo! @deprecated - - # Use asyncTaskInfo instead - asyncTaskStatus(id: String!): AsyncTaskInfo! @deprecated - } `, BuiltIn: false}, @@ -6035,37 +7570,72 @@ type DataTransferProcessorInfo { isHTML: Boolean } +input DataTransferOutputSettingsInput { + insertBom: Boolean + encoding: String + timestampPattern: String + compress: Boolean + fileName: String +} + +type DataTransferOutputSettings { + insertBom: Boolean! + encoding: String! + timestampPattern: String! + compress: Boolean! +} + +type DataTransferDefaultExportSettings { + outputSettings : DataTransferOutputSettings! + supportedEncodings: [String!]! +} + input DataTransferParameters { - # Processor ID + "Processor ID" processorId: ID! - # General settings: - # - openNewConnection: opens new database connection for data transfer task + """ + General settings: + - openNewConnection: opens new database connection for data transfer task + """ settings: Object - # Processor properties. See DataTransferProcessorInfo.properties + "Processor properties. See DataTransferProcessorInfo.properties" processorProperties: Object! - # Data filter settings + "Consumer properties. See StreamConsumerSettings" + outputSettings: DataTransferOutputSettingsInput + "Data filter settings" filter: SQLDataFilter } extend type Query { - # Available transfer processors + "Returns available transfer processors for data transfer export" dataTransferAvailableStreamProcessors: [ DataTransferProcessorInfo! ]! + "Returns available transfer processors for data transfer import" + dataTransferAvailableImportStreamProcessors: [ DataTransferProcessorInfo! ]! + + "Returns default export settings for data transfer" + dataTransferDefaultExportSettings: DataTransferDefaultExportSettings! + + "Creates async task for data transfer export from the container node path" dataTransferExportDataFromContainer( + projectId: ID, connectionId: ID!, containerNodePath: ID!, parameters: DataTransferParameters! ): AsyncTaskInfo! + "Creates async task for data transfer export from results" dataTransferExportDataFromResults( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, parameters: DataTransferParameters! ): AsyncTaskInfo! - dataTransferRemoveDataFile(dataFileId: String!): Boolean + "Deletes data transfer file by ID" + dataTransferRemoveDataFile(dataFileId: String!): Boolean @deprecated(reason: "25.0.1") } `, BuiltIn: false}, @@ -6074,7 +7644,10 @@ extend type Query { extend type Query { # Get child nodes + "Returns node DDL for the specified node ID" metadataGetNodeDDL(nodeId: ID!, options: Object): String + "Returns extended node DDL for the specified node ID (e.g., Oracle or MySQL package)" + metadataGetNodeExtendedDDL(nodeId: ID!): String } `, BuiltIn: false}, @@ -6104,17 +7677,19 @@ type ObjectDetails { } type DatabaseObjectInfo { - # Object name + " Object name" name: String - # Description - optional + " Description - optional" description: String - # Object type. Java class name in most cases + " Object type. Java class name in most cases" type: String - # Read object properties. - # Optional parameter 'ids' filters properties by id. null means all properties. - # Note: property value reading may take a lot of time so don't read all property values always - # Examine property meta (features in particular) before reading them + """ + Read object properties. + Optional parameter 'ids' filters properties by id. null means all properties. + Note: property value reading may take a lot of time so don't read all property values always + Examine property meta (features in particular) before reading them + """ properties(filter: ObjectPropertyFilter): [ ObjectPropertyInfo ] # Optional properties @@ -6125,44 +7700,65 @@ type DatabaseObjectInfo { uniqueName: String state: String - # Features: script, scriptExtended, dataContainer, dataManipulator, - # entity, schema, catalog + "Features: script, scriptExtended, dataContainer, dataManipulator, entity, schema, catalog" features: [ String! ] - # Supported editors: ddl, permissions, sourceDeclaration, sourceDefinition + " Supported editors: ddl, permissions, sourceDeclaration, sourceDefinition" editors: [ String! ] } type NavigatorNodeInfo { - # Node ID - generally a full path to the node from root of tree + "Node ID - generally a full path to the node from root of tree" id: ID! - # Node human readable name + "Node URI - a unique path to a node including all parent nodes" + uri: ID! @since(version: "23.3.1") + "Node human readable name" name: String - #Node full name - fullName: String - # Node icon path + "Node full name" + fullName: String @deprecated(reason: "use name parameter (23.2.0)") + "Node plain name (23.2.0)" + plainName: String + "Node icon path" icon: String - # Node description + "Node description" description: String - # Node type + "Node type" nodeType: String - # Can this property have child nodes? - hasChildren: Boolean + "Can this property have child nodes?" + hasChildren: Boolean! + "Project id of the node" + projectId: String - # Associated object. Maybe null for non-database objects + "Associated object. Maybe null for non-database objects" object: DatabaseObjectInfo - # Supported features: item, container, leaf - # canDelete, canRename + """ + Associated object. Return value depends on the node type - connectionId for connection node, resource path for resource node, etc. + null - if node currently not support this property + """ + objectId: String @since(version: "23.2.4") + + "Supported features: item, container, leaf, canDelete, canRename" features: [ String! ] - # Object detailed info. - # If is different than properties. It doesn't perform any expensive operation and doesn't require authentication. + """ + Object detailed info. + If is different than properties. It doesn't perform any expensive operation and doesn't require authentication. + """ nodeDetails: [ ObjectPropertyInfo! ] - folder: Boolean - inline: Boolean - navigable: Boolean + folder: Boolean! + inline: Boolean! + navigable: Boolean! + filtered: Boolean! + + "Reads node filter. Expensive invocation, read only when it is really needed" + filter: NavigatorNodeFilter +} + +type NavigatorNodeFilter { + include: [String!] + exclude: [String!] } type DatabaseCatalog { @@ -6171,6 +7767,7 @@ type DatabaseCatalog { } type DatabaseStructContainers { + parentNode: NavigatorNodeInfo catalogList: [ DatabaseCatalog! ]! schemaList: [ NavigatorNodeInfo! ]! supportsCatalogChange: Boolean! @@ -6183,96 +7780,173 @@ type DatabaseStructContainers { extend type Query { - # Get child nodes + "Returns child nodes based on parent node path" navNodeChildren( parentPath: ID!, offset: Int, limit: Int, onlyFolders: Boolean): [ NavigatorNodeInfo! ]! - # Get child nodes - navNodeParents(nodePath: ID!): [ NavigatorNodeInfo! ]! + "Returns parent nodes for the specified node path" + navNodeParents( nodePath: ID! ): [ NavigatorNodeInfo! ]! + "Returns node info for the specified node path" navNodeInfo( nodePath: ID! ): NavigatorNodeInfo! - navRefreshNode( nodePath: ID! ): Boolean + "Refreshes node based on the node path" + navRefreshNode( nodePath: ID! ): Boolean @deprecated # Use navReloadNode method from Mutation (24.2.4) # contextId currently not using - navGetStructContainers( connectionId: ID!, contextId: ID, catalog: ID ): DatabaseStructContainers! + navGetStructContainers( projectId: ID, connectionId: ID!, contextId: ID, catalog: ID ): DatabaseStructContainers! } extend type Mutation { - # Rename node and returns new node name + "Reloads node and returns updated node info" + navReloadNode( nodePath: ID! ): NavigatorNodeInfo! + + "Renames node and returns new node name" navRenameNode( nodePath: ID!, newName: String! ): String - # Deletes nodes with specified IDs and returns number of deleted nodes + "Deletes nodes with specified IDs and returns number of deleted nodes" navDeleteNodes( nodePaths: [ID!]! ): Int - # Moves nodes with specified IDs to the connection folder - navMoveNodesToFolder(nodePaths: [ID!]!, folderPath: ID!): Boolean + "Moves nodes with specified IDs to the connection folder" + navMoveNodesToFolder( nodePaths: [ID!]!, folderPath: ID!): Boolean! + + """ + Sets filter for the folder node. If both include and exclude are null then filter is removed. + Node must be refreshed after applying filters. Node children can be changed + """ + navSetFolderFilter( nodePath: ID!, include: [String!], exclude: [String!]): Boolean! }`, BuiltIn: false}, {Name: "../schema/service.rm.graphqls", Input: `# Metadata queries type RMProject { - id: String! + id: ID! name: String! description: String shared: Boolean! + global: Boolean! createTime: DateTime! creator: String! + projectPermissions: [String!]! + resourceTypes: [RMResourceType!]! } type RMResource { name: String! folder: Boolean! length: Int! + # Properties map + properties: Object +} + +input RMSubjectProjectPermissions { + subjectId: String! + permissions: [String!]! +} + + +input RMProjectPermissions { + projectId: String! + permissions: [String!]! } extend type Query { - # List accessible projects + "List accessible projects for a current user" rmListProjects: [RMProject!]! - # List accessible projects + "List shared projects for a current user" + rmListSharedProjects: [RMProject!]! + + "Returns project information by projectId" + rmProject(projectId: String!): RMProject! + + "Returns available project permissions. Can be read only by users with admin permissions" + rmListProjectPermissions: [AdminPermissionInfo!]! + + "Returns project permissions for the specified project. Can be read only by users with admin permissions" + rmListProjectGrantedPermissions(projectId: String!): [AdminObjectGrantInfo!]! + + "Returns all project grants bysubjectId. Can be read only by users with admin permissions" + rmListSubjectProjectsPermissionGrants(subjectId: String!): [AdminObjectGrantInfo!]! + + "Returns resources in the specified project and folder. If folder is not specified, returns resources in the root folder" rmListResources( projectId: String!, folder: String, nameMask: String, readProperties: Boolean, - readHistory: Boolean): [RMResource!]! + readHistory: Boolean + ): [RMResource!]! - # Reads resource contents as string in UTF-8 + "Reads resource contents as string in UTF-8" rmReadResourceAsString( projectId: String!, - resourcePath: String!): String! + resourcePath: String! + ): String! } extend type Mutation { - + "Creates a new resource in the specified project and folder. If isFolder is true then creates a folder, otherwise creates a file" rmCreateResource( projectId: String!, resourcePath: String!, - isFolder: Boolean!): String! + isFolder: Boolean! + ): String! + "Moves resource to the specified new path in the same project. Can be used to rename a resource" rmMoveResource( projectId: String!, oldResourcePath: String!, - newResourcePath: String): String! + newResourcePath: String + ): String! + "Deletes resource by path in the specified project. If recursive is true then deletes all sub-resources in the folder" rmDeleteResource( projectId: String!, resourcePath: String!, - recursive: Boolean!): Boolean + recursive: Boolean! + ): Boolean + """ + Writes string content to the resource. + If forceOverwrite is true then overwrites existing resource, otherwise throws an error if resource already exists + """ rmWriteResourceStringContent( projectId: String!, resourcePath: String!, - data: String!): String! + data: String!, + forceOverwrite: Boolean! + ): String! + + "Creates a new project with the specified projectId and projectName." + rmCreateProject( + projectId: ID, + projectName: String!, + description: String + ): RMProject! + + "Deletes project by projectId. Returns true if project was deleted, false if project not found" + rmDeleteProject(projectId: ID!): Boolean! + + rmSetProjectPermissions(projectId: String!, permissions: [RMSubjectProjectPermissions!]!): Boolean! @deprecated(reason: "use setConnectionSubjectAccess") + + rmSetSubjectProjectPermissions(subjectId: String!, permissions: [RMProjectPermissions!]!): Boolean! @deprecated + + "Adds project permissions to the specified projects based on subject IDs and permissions. Returns true if permissions were added successfully." + rmAddProjectsPermissions(projectIds: [ID!]!, subjectIds: [ID!]!, permissions:[String!]! ): Boolean @since(version: "23.2.2") + "Deletes project permissions from the specified projects based on subject IDs and permissions. Returns true if permissions were deleted successfully." + rmDeleteProjectsPermissions(projectIds: [ID!]!, subjectIds: [ID!]!, permissions:[String!]!): Boolean @since(version: "23.2.2") + + "Sets resource property by name. If value is null then removes the property (e.g., sets relation between resource and connection)." + rmSetResourceProperty(projectId: String!, resourcePath: String!, name: ID!, value: String): Boolean! }`, BuiltIn: false}, {Name: "../schema/service.sql.graphqls", Input: `#################################################### # SQL helpers @@ -6318,7 +7992,9 @@ type SQLCompletionProposal { type SQLContextInfo { id: ID! + projectId: ID! connectionId: ID! + autoCommit: Boolean defaultCatalog: String defaultSchema: String @@ -6335,7 +8011,7 @@ input SQLDataFilterConstraint { } input SQLDataFilter { - # Row offset. We use Float because offset may be bigger than 32 bit. + "Row offset. We use Float because offset may be bigger than 32 bit." offset: Float limit: Int @@ -6354,18 +8030,27 @@ type SQLResultColumn { dataKind: String typeName: String fullTypeName: String - # Column value max length. We use Float because it may be bigger than 32 bit. + "Column value max length. We use Float because it may be bigger than 32 bit" maxLength: Float scale: Int precision: Int required: Boolean! + autoGenerated: Boolean! readOnly: Boolean! readOnlyStatus: String - # Operations supported for this attribute + "Operations supported for this attribute" supportedOperations: [DataTypeLogicalOperation!]! + + "Description of the column" + description: String @since(version: "25.1.3") +} + +type SQLResultRowMetaData { + data: [Object]! + metaData: Object } type DatabaseDocument { @@ -6376,17 +8061,32 @@ type DatabaseDocument { } type SQLResultSet { + "Result set ID" id: ID! + "Returns list of columns in the result set" columns: [ SQLResultColumn ] - rows: [ [ Object ] ] + "Returns list of rows in the result set. Each row is an array of column values" + rows: [ [ Object ] ] @deprecated(reason: "use rowsWithMetaData (23.3.5)") + "Returns list of rows in the result set. Each row contains data and metadata" + rowsWithMetaData: [SQLResultRowMetaData] @since(version: "23.3.5") # True means that resultset was generated by single entity query # New rows can be added, old rows can be deleted singleEntity: Boolean! # server always returns hasMoreData = false hasMoreData: Boolean! - # can't update data or load LOB file if hasRowIdentifier = false + "Identifies if result set has row identifier. If true then it is possible update data or load LOB files" hasRowIdentifier: Boolean! + "Identifies if result has children collections. If true then children collections can be read from the result set" + hasChildrenCollection: Boolean! + "Identifies if result set supports dynamic trace. If true then dynamic trace can be read from the result set" + hasDynamicTrace: Boolean! @since(version: "24.1.2") + "Identifies if result set supports data filter. If true then data filter can be applied to the result set" + isSupportsDataFilter: Boolean! + "Identifies if result set is read-only. If true then no updates are allowed" + readOnly: Boolean! @since(version: "25.0.1") + "Status of read-only result set. If readOnly is true then this field contains reason why result set is read-only" + readOnlyStatus: String @since(version: "25.0.1") } type SQLQueryResults { @@ -6408,6 +8108,10 @@ type SQLExecuteInfo { duration: Int! # Actual conditions applied to query filterText: String +# # original sql query without SQLDataFilter +# originalQuery: String + # Full query that was executed, contains all used filters + fullQuery: String # Results results: [ SQLQueryResults! ]! } @@ -6415,6 +8119,12 @@ type SQLExecuteInfo { input SQLResultRow { data: [ Object ]! updateValues: Object + metaData: Object +} + +input SQLResultRowMetaDataInput { + data: [Object] + metaData: Object! } type DataTypeLogicalOperation { @@ -6467,18 +8177,49 @@ type SQLScriptQuery { start: Int! end: Int! } + +#################################################### +# Dynamic trace info +#################################################### +type DynamicTraceProperty { + name: String! + value: String + description: String +} + +#################################################### +# Transactional info +#################################################### +type TransactionLogInfoItem { + id: Int! + time: DateTime! + type: String! + queryString: String! + durationMs: Int! + rows: Int! + result: String! +} +type TransactionLogInfos { + count: Int! + transactionLogInfos: [TransactionLogInfoItem!]! +} + + #################################################### # Query and Mutation #################################################### extend type Query { - sqlDialectInfo( connectionId: ID! ): SQLDialectInfo + "Returns SQL dialect info for the specified connection" + sqlDialectInfo( projectId: ID, connectionId: ID! ): SQLDialectInfo - # Lists SQL contexts for a connection (optional) or returns the particular context info - sqlListContexts( connectionId: ID, contextId: ID ): [ SQLContextInfo ]! + "Lists SQL contexts for a connection (optional) or returns the particular context info" + sqlListContexts( projectId: ID, connectionId: ID, contextId: ID ): [ SQLContextInfo ]! + "Returns proposals for SQL completion at the specified position in the query" sqlCompletionProposals( + projectId: ID, connectionId: ID!, contextId: ID!, query: String!, @@ -6487,68 +8228,95 @@ extend type Query { simpleMode: Boolean ): [ SQLCompletionProposal ] + "Formats SQL query and returns formatted query string" sqlFormatQuery( + projectId: ID, connectionId: ID!, contextId: ID!, query: String! ): String! + "Returns suported operations for the specified attribute index in the results" sqlSupportedOperations( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, attributeIndex: Int! ): [DataTypeLogicalOperation!]! - # List of all available entity query generators - sqlEntityQueryGenerators(nodePathList: [String!]! - ): [SQLQueryGenerator!]! - - # Options: - # fullyQualifiedNames: Boolean - # compactSQL: Boolean - # showComments: Boolean - # showPermissions: Boolean - # showFullDdl: Boolean - # excludeAutoGeneratedColumn: Boolean - # useCustomDataFormat: Boolean + "Returns list of all available entity query generators" + sqlEntityQueryGenerators(nodePathList: [String!]!): [SQLQueryGenerator!]! + + """ + Generates SQL query for the specified entity query generator. + Available options: + fullyQualifiedNames - Use fully qualified names for entities + compactSQL - Use compact SQL format + showComments - Show comments in generated SQL + showPermissions - Show permissions in generated SQL + showFullDdl - Show full DDL in generated SQL + excludeAutoGeneratedColumn - Exclude auto-generated columns in generated SQL + useCustomDataFormat - Use custom data format for generated SQL + """ sqlGenerateEntityQuery( generatorId: String!, options: Object!, nodePathList: [String!]! ): String! + "Parses SQL script and returns script info with queries start and end positions" sqlParseScript( + projectId: ID, connectionId: ID!, script: String! ): SQLScriptInfo! + "Parses SQL query and returns query info with start and end positions" sqlParseQuery( + projectId: ID, connectionId: ID!, script: String!, position: Int! ): SQLScriptQuery! + + "Generates SQL query for grouping data in the specified results" + sqlGenerateGroupingQuery( + projectId: ID, + contextId: ID!, + connectionId: ID!, + resultsId: ID!, + columnNames: [String!], + functions: [String!], + showDuplicatesOnly: Boolean + ): String! } extend type Mutation { - sqlContextCreate( connectionId: ID!, defaultCatalog: String, defaultSchema: String ): SQLContextInfo! + "Creates SQL context for the specified connection" + sqlContextCreate( projectId: ID, connectionId: ID!, defaultCatalog: String, defaultSchema: String ): SQLContextInfo! - sqlContextSetDefaults( connectionId: ID!, contextId: ID!, defaultCatalog: ID, defaultSchema: ID ): Boolean! + "Sets SQL context defaults" + sqlContextSetDefaults( projectId: ID, connectionId: ID!, contextId: ID!, defaultCatalog: ID, defaultSchema: ID ): Boolean! - sqlContextDestroy( connectionId: ID!, contextId: ID! ): Boolean! + "Destroys SQL context and closes all results" + sqlContextDestroy( projectId: ID, connectionId: ID!, contextId: ID! ): Boolean! - # Execute SQL and return results + "Creates async task for executing SQL query" asyncSqlExecuteQuery( + projectId: ID, connectionId: ID!, contextId: ID!, sql: String!, resultId: ID, filter: SQLDataFilter, - dataFormat: ResultDataFormat # requested data format. May be ignored by server + dataFormat: ResultDataFormat, # requested data format. May be ignored by server + readLogs: Boolean # added 23.2.1 ): AsyncTaskInfo! - # Read data from table + "Creates async task for reading data from the container node" asyncReadDataFromContainer( + projectId: ID, connectionId: ID!, contextId: ID!, containerNodePath: ID!, @@ -6557,11 +8325,31 @@ extend type Mutation { dataFormat: ResultDataFormat ): AsyncTaskInfo! - # Close results (free resources) - sqlResultClose(connectionId: ID!, contextId: ID!, resultId: ID!): Boolean! + "Returns transaction log info for the specified project, connection and context" + getTransactionLogInfo( + projectId: ID!, + connectionId: ID!, + contextId: ID! + ): TransactionLogInfos! + + "Closes SQL results (free resources)" + sqlResultClose(projectId: ID, connectionId: ID!, contextId: ID!, resultId: ID!): Boolean! + + "Creates async task for updating results data in batch mode" + asyncUpdateResultsDataBatch( + projectId: ID!, + connectionId: ID!, + contextId: ID!, + resultsId: ID!, + + updatedRows: [SQLResultRow!], + deletedRows: [SQLResultRow!], + addedRows: [SQLResultRow!], + ): AsyncTaskInfo! @since(version: "25.0.0") - # Update multiple cell values + "Synchronously updates results data in batch mode" updateResultsDataBatch( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, @@ -6569,10 +8357,11 @@ extend type Mutation { updatedRows: [ SQLResultRow! ], deletedRows: [ SQLResultRow! ], addedRows: [ SQLResultRow! ], - ): SQLExecuteInfo! + ): SQLExecuteInfo! @deprecated(reason: "use async function (25.0.0)") - # Return SQL script for cell values update + "Returns SQL script for cell values update" updateResultsDataBatchScript( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, @@ -6582,29 +8371,92 @@ extend type Mutation { addedRows: [ SQLResultRow! ], ): String! - #Return BLOB name + "Returns BLOB value" readLobValue( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, lobColumnIndex: Int!, row: [ SQLResultRow! ]! - ): String! + ): String! @deprecated(reason: "use sqlReadLobValue (23.3.3)") + + "Returns BLOB value as Base64 encoded string" + sqlReadLobValue( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID!, + lobColumnIndex: Int!, + row: SQLResultRow! + ): String! @since(version: "23.3.3") - # Returns SQLExecuteInfo + "Returns full string value ignoring any limits" + sqlReadStringValue( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID!, + columnIndex: Int!, + row: SQLResultRow! + ): String! @since(version: "23.3.3") + + "Returns SQL execution results for async SQL execute task" asyncSqlExecuteResults(taskId: ID!): SQLExecuteInfo ! - # Read data from table + "Creates async task to generating SQL execution plan" asyncSqlExplainExecutionPlan( + projectId: ID, connectionId: ID!, contextId: ID!, query: String!, configuration: Object! ): AsyncTaskInfo! - # Returns SQLExecutionPlan + "Returns SQL execution plan for async SQL explain task" asyncSqlExplainExecutionPlanResult(taskId: ID!): SQLExecutionPlan ! + "Creates async task to count rows in SQL results" + asyncSqlRowDataCount( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID! + ): AsyncTaskInfo! + + "Returns row count for async SQL row data count task" + asyncSqlRowDataCountResult(taskId: ID!): Int! + + "Reads dynamic trace from provided database results" + sqlGetDynamicTrace( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID! + ): [DynamicTraceProperty!]! @since(version: "24.1.2") + + "Creates async task to set auto-commit mode" + asyncSqlSetAutoCommit( + projectId: ID!, + connectionId: ID!, + contextId: ID!, + autoCommit: Boolean! + ): AsyncTaskInfo! @since(version: "24.0.1") + + "Creates async task to commit transaction" + asyncSqlCommitTransaction( + projectId: ID!, + connectionId: ID!, + contextId: ID! + ): AsyncTaskInfo! @since(version: "24.0.1") + + "Creates async task to rollback transaction" + asyncSqlRollbackTransaction( + projectId: ID!, + connectionId: ID!, + contextId: ID! + ): AsyncTaskInfo! @since(version: "24.0.1") + } `, BuiltIn: false}, } @@ -6614,2599 +8466,2574 @@ var parsedSchema = gqlparser.MustLoadSchema(sources...) // region ***************************** args.gotpl ***************************** -func (ec *executionContext) field_DatabaseObjectInfo_properties_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) dir_since_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *model.ObjectPropertyFilter - if tmp, ok := rawArgs["filter"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - arg0, err = ec.unmarshalOObjectPropertyFilter2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyFilter(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "version", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["version"] = arg0 + return args, nil +} + +func (ec *executionContext) field_DatabaseObjectInfo_properties_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "filter", ec.unmarshalOObjectPropertyFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyFilter) + if err != nil { + return nil, err } args["filter"] = arg0 return args, nil } -func (ec *executionContext) field_Mutation_asyncReadDataFromContainer_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_adminUpdateProductConfiguration_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "configuration", ec.unmarshalNObject2interface) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["configuration"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Mutation_asyncReadDataFromContainer_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["containerNodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("containerNodePath")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["containerNodePath"] = arg2 - var arg3 *string - if tmp, ok := rawArgs["resultId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultId")) - arg3, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["resultId"] = arg3 - var arg4 *model.SQLDataFilter - if tmp, ok := rawArgs["filter"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - arg4, err = ec.unmarshalOSQLDataFilter2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter(ctx, tmp) - if err != nil { - return nil, err - } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "containerNodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["filter"] = arg4 - var arg5 *model.ResultDataFormat - if tmp, ok := rawArgs["dataFormat"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataFormat")) - arg5, err = ec.unmarshalOResultDataFormat2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx, tmp) - if err != nil { - return nil, err - } + args["containerNodePath"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "resultId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["resultId"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "filter", ec.unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter) + if err != nil { + return nil, err } - args["dataFormat"] = arg5 + args["filter"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "dataFormat", ec.unmarshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat) + if err != nil { + return nil, err + } + args["dataFormat"] = arg6 return args, nil } -func (ec *executionContext) field_Mutation_asyncSqlExecuteQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_asyncSqlCommitTransaction_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["sql"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("sql")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["sql"] = arg2 - var arg3 *string - if tmp, ok := rawArgs["resultId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultId")) - arg3, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["contextId"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Mutation_asyncSqlExecuteQuery_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["resultId"] = arg3 - var arg4 *model.SQLDataFilter - if tmp, ok := rawArgs["filter"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - arg4, err = ec.unmarshalOSQLDataFilter2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["filter"] = arg4 - var arg5 *model.ResultDataFormat - if tmp, ok := rawArgs["dataFormat"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataFormat")) - arg5, err = ec.unmarshalOResultDataFormat2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "sql", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["sql"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "resultId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["resultId"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "filter", ec.unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter) + if err != nil { + return nil, err } - args["dataFormat"] = arg5 + args["filter"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "dataFormat", ec.unmarshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat) + if err != nil { + return nil, err + } + args["dataFormat"] = arg6 + arg7, err := graphql.ProcessArgField(ctx, rawArgs, "readLogs", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["readLogs"] = arg7 return args, nil } -func (ec *executionContext) field_Mutation_asyncSqlExecuteResults_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_asyncSqlExecuteResults_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["taskId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("taskId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "taskId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["taskId"] = arg0 return args, nil } -func (ec *executionContext) field_Mutation_asyncSqlExplainExecutionPlanResult_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_asyncSqlExplainExecutionPlanResult_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["taskId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("taskId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "taskId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["taskId"] = arg0 return args, nil } -func (ec *executionContext) field_Mutation_asyncSqlExplainExecutionPlan_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_asyncSqlExplainExecutionPlan_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["query"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("query")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["query"] = arg2 - var arg3 interface{} - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg3, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "query", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["query"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "configuration", ec.unmarshalNObject2interface) + if err != nil { + return nil, err } - args["configuration"] = arg3 + args["configuration"] = arg4 return args, nil } -func (ec *executionContext) field_Mutation_asyncTaskCancel_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_asyncSqlRollbackTransaction_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Mutation_asyncSqlRowDataCountResult_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "taskId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["taskId"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Mutation_asyncSqlRowDataCount_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + return args, nil +} + +func (ec *executionContext) field_Mutation_asyncSqlSetAutoCommit_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "autoCommit", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err + } + args["autoCommit"] = arg3 + return args, nil +} + +func (ec *executionContext) field_Mutation_asyncTaskCancel_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["id"] = arg0 return args, nil } -func (ec *executionContext) field_Mutation_asyncTaskInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_asyncTaskInfo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["id"] = arg0 - var arg1 bool - if tmp, ok := rawArgs["removeOnFinish"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("removeOnFinish")) - arg1, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "removeOnFinish", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err } args["removeOnFinish"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_asyncTaskStatus_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_asyncUpdateResultsDataBatch_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["id"] = arg0 + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "updatedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["updatedRows"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "deletedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["deletedRows"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "addedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["addedRows"] = arg6 return args, nil } -func (ec *executionContext) field_Mutation_changeSessionLanguage_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_changeSessionLanguage_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["locale"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("locale")) - arg0, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "locale", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["locale"] = arg0 return args, nil } -func (ec *executionContext) field_Mutation_closeConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_closeConnection_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["id"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_copyConnectionFromNode_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_copyConnectionFromNode_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePath", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["nodePath"] = arg0 - var arg1 *model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg1, err = ec.unmarshalOConnectionConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "config", ec.unmarshalOConnectionConfig2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig) + if err != nil { + return nil, err } args["config"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_createConnectionFolder_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_createConnectionFolder_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["parentFolderPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parentFolderPath")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "parentFolderPath", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } args["parentFolderPath"] = arg0 - var arg1 string - if tmp, ok := rawArgs["folderName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folderName")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "folderName", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["folderName"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_createConnectionFromTemplate_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_createConnection_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["templateId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("templateId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "config", ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig) + if err != nil { + return nil, err } - args["templateId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["connectionName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionName")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["config"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["connectionName"] = arg1 + args["projectId"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_createConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_deleteConnectionFolder_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "folderPath", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["config"] = arg0 + args["folderPath"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_deleteConnectionFolder_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_deleteConnection_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["folderPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folderPath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["folderPath"] = arg0 + args["id"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_deleteConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_federatedLogin_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "provider", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["id"] = arg0 + args["provider"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "configuration", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["configuration"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "linkUser", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["linkUser"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "forceSessionsLogout", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["forceSessionsLogout"] = arg3 return args, nil } -func (ec *executionContext) field_Mutation_initConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_getTransactionLogInfo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Mutation_initConnection_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["id"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["credentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - arg1, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["credentials"] = arg1 - var arg2 []*model.NetworkHandlerConfigInput - if tmp, ok := rawArgs["networkCredentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("networkCredentials")) - arg2, err = ec.unmarshalONetworkHandlerConfigInput2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "credentials", ec.unmarshalOObject2interface) + if err != nil { + return nil, err } - args["networkCredentials"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["saveCredentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("saveCredentials")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + args["credentials"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "networkCredentials", ec.unmarshalONetworkHandlerConfigInput2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInputᚄ) + if err != nil { + return nil, err + } + args["networkCredentials"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "saveCredentials", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["saveCredentials"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "sharedCredentials", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["sharedCredentials"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "selectedSecretId", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } - args["saveCredentials"] = arg3 + args["selectedSecretId"] = arg6 return args, nil } -func (ec *executionContext) field_Mutation_navDeleteNodes_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_navDeleteNodes_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["nodePaths"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePaths")) - arg0, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePaths", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } args["nodePaths"] = arg0 return args, nil } -func (ec *executionContext) field_Mutation_navMoveNodesToFolder_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_navMoveNodesToFolder_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["nodePaths"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePaths")) - arg0, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePaths", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } args["nodePaths"] = arg0 - var arg1 string - if tmp, ok := rawArgs["folderPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folderPath")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "folderPath", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["folderPath"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_navRenameNode_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_navReloadNode_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["nodePath"] = arg0 - var arg1 string - if tmp, ok := rawArgs["newName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("newName")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["newName"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_openConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_navRenameNode_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["config"] = arg0 + args["nodePath"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "newName", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["newName"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_openSession_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_navSetFolderFilter_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["defaultLocale"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultLocale")) - arg0, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["defaultLocale"] = arg0 + args["nodePath"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "include", ec.unmarshalOString2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["include"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "exclude", ec.unmarshalOString2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["exclude"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_readLobValue_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_openSession_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "defaultLocale", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["defaultLocale"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Mutation_readLobValue_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["resultsId"] = arg2 - var arg3 int - if tmp, ok := rawArgs["lobColumnIndex"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("lobColumnIndex")) - arg3, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["lobColumnIndex"] = arg3 - var arg4 []*model.SQLResultRow - if tmp, ok := rawArgs["row"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("row")) - arg4, err = ec.unmarshalNSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "lobColumnIndex", ec.unmarshalNInt2int) + if err != nil { + return nil, err + } + args["lobColumnIndex"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "row", ec.unmarshalNSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err } - args["row"] = arg4 + args["row"] = arg5 return args, nil } -func (ec *executionContext) field_Mutation_rmCreateResource_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmAddProjectsPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectIds", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["projectIds"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "subjectIds", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["subjectIds"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "permissions", ec.unmarshalNString2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["permissions"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Mutation_rmCreateProject_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectName", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["resourcePath"] = arg1 - var arg2 bool - if tmp, ok := rawArgs["isFolder"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("isFolder")) - arg2, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } + args["projectName"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "description", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } - args["isFolder"] = arg2 + args["description"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_rmDeleteResource_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmCreateResource_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "resourcePath", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["resourcePath"] = arg1 - var arg2 bool - if tmp, ok := rawArgs["recursive"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("recursive")) - arg2, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "isFolder", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err } - args["recursive"] = arg2 + args["isFolder"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_rmMoveResource_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmDeleteProject_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["oldResourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("oldResourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + return args, nil +} + +func (ec *executionContext) field_Mutation_rmDeleteProjectsPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectIds", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } - args["oldResourcePath"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["newResourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("newResourcePath")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectIds"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "subjectIds", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } - args["newResourcePath"] = arg2 + args["subjectIds"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "permissions", ec.unmarshalNString2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["permissions"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_rmWriteResourceStringContent_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmDeleteResource_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "resourcePath", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["resourcePath"] = arg1 - var arg2 string - if tmp, ok := rawArgs["data"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("data")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "recursive", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err } - args["data"] = arg2 + args["recursive"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_setConnectionNavigatorSettings_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmMoveResource_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["id"] = arg0 - var arg1 model.NavigatorSettingsInput - if tmp, ok := rawArgs["settings"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("settings")) - arg1, err = ec.unmarshalNNavigatorSettingsInput2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettingsInput(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "oldResourcePath", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["oldResourcePath"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "newResourcePath", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } - args["settings"] = arg1 + args["newResourcePath"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_setUserConfigurationParameter_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmSetProjectPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["name"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["name"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["value"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("value")) - arg1, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "permissions", ec.unmarshalNRMSubjectProjectPermissions2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMSubjectProjectPermissionsᚄ) + if err != nil { + return nil, err } - args["value"] = arg1 + args["permissions"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_sqlContextCreate_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmSetResourceProperty_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["defaultCatalog"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultCatalog")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "resourcePath", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["defaultCatalog"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["defaultSchema"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultSchema")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["resourcePath"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "name", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["defaultSchema"] = arg2 + args["name"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "value", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err + } + args["value"] = arg3 return args, nil } -func (ec *executionContext) field_Mutation_sqlContextDestroy_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmSetSubjectProjectPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "subjectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["subjectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "permissions", ec.unmarshalNRMProjectPermissions2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectPermissionsᚄ) + if err != nil { + return nil, err } - args["contextId"] = arg1 + args["permissions"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_sqlContextSetDefaults_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_rmWriteResourceStringContent_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "resourcePath", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["defaultCatalog"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultCatalog")) - arg2, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["resourcePath"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "data", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["defaultCatalog"] = arg2 - var arg3 *string - if tmp, ok := rawArgs["defaultSchema"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultSchema")) - arg3, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["data"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "forceOverwrite", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err } - args["defaultSchema"] = arg3 + args["forceOverwrite"] = arg3 return args, nil } -func (ec *executionContext) field_Mutation_sqlResultClose_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_setConnectionNavigatorSettings_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["id"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "settings", ec.unmarshalNNavigatorSettingsInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettingsInput) + if err != nil { + return nil, err } - args["resultId"] = arg2 + args["settings"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_testConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_setUserConfigurationParameter_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "name", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["config"] = arg0 + args["name"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "value", ec.unmarshalOObject2interface) + if err != nil { + return nil, err + } + args["value"] = arg1 return args, nil } -func (ec *executionContext) field_Mutation_testNetworkHandler_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_setUserPreferences_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.NetworkHandlerConfigInput - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNNetworkHandlerConfigInput2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "preferences", ec.unmarshalNObject2interface) + if err != nil { + return nil, err } - args["config"] = arg0 + args["preferences"] = arg0 return args, nil } -func (ec *executionContext) field_Mutation_updateConnection_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_sqlContextCreate_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["config"] = arg0 + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "defaultCatalog", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err + } + args["defaultCatalog"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "defaultSchema", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err + } + args["defaultSchema"] = arg3 return args, nil } -func (ec *executionContext) field_Mutation_updateResultsDataBatchScript_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_sqlContextDestroy_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["resultsId"] = arg2 - var arg3 []*model.SQLResultRow - if tmp, ok := rawArgs["updatedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("updatedRows")) - arg3, err = ec.unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["updatedRows"] = arg3 - var arg4 []*model.SQLResultRow - if tmp, ok := rawArgs["deletedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("deletedRows")) - arg4, err = ec.unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["deletedRows"] = arg4 - var arg5 []*model.SQLResultRow - if tmp, ok := rawArgs["addedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addedRows")) - arg5, err = ec.unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["addedRows"] = arg5 + args["contextId"] = arg2 return args, nil } -func (ec *executionContext) field_Mutation_updateResultsDataBatch_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_sqlContextSetDefaults_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["resultsId"] = arg2 - var arg3 []*model.SQLResultRow - if tmp, ok := rawArgs["updatedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("updatedRows")) - arg3, err = ec.unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["updatedRows"] = arg3 - var arg4 []*model.SQLResultRow - if tmp, ok := rawArgs["deletedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("deletedRows")) - arg4, err = ec.unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "defaultCatalog", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["deletedRows"] = arg4 - var arg5 []*model.SQLResultRow - if tmp, ok := rawArgs["addedRows"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addedRows")) - arg5, err = ec.unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["defaultCatalog"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "defaultSchema", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["addedRows"] = arg5 + args["defaultSchema"] = arg4 return args, nil } -func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_sqlGetDynamicTrace_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["name"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["name"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_allConnections_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["id"] = arg0 - return args, nil -} - -func (ec *executionContext) field_Query_authChangeLocalPassword_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { - var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["oldPassword"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("oldPassword")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["oldPassword"] = arg0 - var arg1 string - if tmp, ok := rawArgs["newPassword"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("newPassword")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["newPassword"] = arg1 + args["resultsId"] = arg3 return args, nil } -func (ec *executionContext) field_Query_authLogin_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_sqlReadLobValue_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["provider"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("provider")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["provider"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["configuration"] = arg1 - var arg2 interface{} - if tmp, ok := rawArgs["credentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - arg2, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["credentials"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["linkUser"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("linkUser")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["linkUser"] = arg3 + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "lobColumnIndex", ec.unmarshalNInt2int) + if err != nil { + return nil, err + } + args["lobColumnIndex"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "row", ec.unmarshalNSQLResultRow2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow) + if err != nil { + return nil, err + } + args["row"] = arg5 return args, nil } -func (ec *executionContext) field_Query_authLogout_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_sqlReadStringValue_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["provider"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("provider")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["provider"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["configuration"] = arg1 + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "columnIndex", ec.unmarshalNInt2int) + if err != nil { + return nil, err + } + args["columnIndex"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "row", ec.unmarshalNSQLResultRow2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow) + if err != nil { + return nil, err + } + args["row"] = arg5 return args, nil } -func (ec *executionContext) field_Query_authUpdateStatus_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_sqlResultClose_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["authId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["authId"] = arg0 - var arg1 *bool - if tmp, ok := rawArgs["linkUser"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("linkUser")) - arg1, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["linkUser"] = arg1 + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultId"] = arg3 return args, nil } -func (ec *executionContext) field_Query_configureServer_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_testConnection_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.ServerConfigInput - if tmp, ok := rawArgs["configuration"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configuration")) - arg0, err = ec.unmarshalNServerConfigInput2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfigInput(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "config", ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig) + if err != nil { + return nil, err } - args["configuration"] = arg0 + args["config"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg1 return args, nil } -func (ec *executionContext) field_Query_connectionFolders_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_testNetworkHandler_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["path"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("path")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "config", ec.unmarshalNNetworkHandlerConfigInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput) + if err != nil { + return nil, err } - args["path"] = arg0 + args["config"] = arg0 return args, nil } -func (ec *executionContext) field_Query_connectionInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_updateConnection_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "config", ec.unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig) + if err != nil { + return nil, err } - args["id"] = arg0 + args["config"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg1 return args, nil } -func (ec *executionContext) field_Query_connectionState_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_updateResultsDataBatchScript_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["id"] = arg0 + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "updatedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["updatedRows"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "deletedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["deletedRows"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "addedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["addedRows"] = arg6 return args, nil } -func (ec *executionContext) field_Query_copyConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Mutation_updateResultsDataBatch_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["nodePath"] = arg0 - var arg1 *model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg1, err = ec.unmarshalOConnectionConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["config"] = arg1 + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "updatedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["updatedRows"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "deletedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["deletedRows"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "addedRows", ec.unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ) + if err != nil { + return nil, err + } + args["addedRows"] = arg6 return args, nil } -func (ec *executionContext) field_Query_createConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg0, err = ec.unmarshalNConnectionConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "name", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["config"] = arg0 + args["name"] = arg0 return args, nil } -func (ec *executionContext) field_Query_createRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_addConnectionsAccess_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["roleId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["roleName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleName")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionIds", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } - args["roleName"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionIds"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "subjects", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } - args["description"] = arg2 + args["subjects"] = arg2 return args, nil } -func (ec *executionContext) field_Query_createUser_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_adminUserInfo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["userId"] = arg0 return args, nil } -func (ec *executionContext) field_Query_dataTransferExportDataFromContainer_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_authChangeLocalPassword_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["containerNodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("containerNodePath")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "oldPassword", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["containerNodePath"] = arg1 - var arg2 model.DataTransferParameters - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg2, err = ec.unmarshalNDataTransferParameters2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferParameters(ctx, tmp) - if err != nil { - return nil, err - } + args["oldPassword"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "newPassword", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["parameters"] = arg2 + args["newPassword"] = arg1 return args, nil } -func (ec *executionContext) field_Query_dataTransferExportDataFromResults_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_authLogin_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "provider", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["provider"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "configuration", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["configuration"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "credentials", ec.unmarshalOObject2interface) + if err != nil { + return nil, err } - args["resultsId"] = arg2 - var arg3 model.DataTransferParameters - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg3, err = ec.unmarshalNDataTransferParameters2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferParameters(ctx, tmp) - if err != nil { - return nil, err - } + args["credentials"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "linkUser", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err } - args["parameters"] = arg3 + args["linkUser"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "forceSessionsLogout", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["forceSessionsLogout"] = arg4 return args, nil } -func (ec *executionContext) field_Query_dataTransferRemoveDataFile_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_authLogoutExtended_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["dataFileId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataFileId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "provider", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["dataFileId"] = arg0 + args["provider"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "configuration", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["configuration"] = arg1 return args, nil } -func (ec *executionContext) field_Query_deleteAuthProviderConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_authLogout_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "provider", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["id"] = arg0 + args["provider"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "configuration", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["configuration"] = arg1 return args, nil } -func (ec *executionContext) field_Query_deleteConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_authUpdateStatus_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "authId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["id"] = arg0 + args["authId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "linkUser", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["linkUser"] = arg1 return args, nil } -func (ec *executionContext) field_Query_deleteRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_configureServer_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "configuration", ec.unmarshalNServerConfigInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfigInput) + if err != nil { + return nil, err } - args["roleId"] = arg0 + args["configuration"] = arg0 return args, nil } -func (ec *executionContext) field_Query_deleteUserMetaParameter_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_connectionFolders_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "path", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["path"] = arg1 + return args, nil +} + +func (ec *executionContext) field_Query_connectionInfo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["id"] = arg1 + return args, nil +} + +func (ec *executionContext) field_Query_createTeam_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["teamId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "teamName", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err + } + args["teamName"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "description", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err + } + args["description"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Query_createUser_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["userId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "enabled", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err + } + args["enabled"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "authRole", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err + } + args["authRole"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Query_dataTransferExportDataFromContainer_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "containerNodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["containerNodePath"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "parameters", ec.unmarshalNDataTransferParameters2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferParameters) + if err != nil { + return nil, err + } + args["parameters"] = arg3 + return args, nil +} + +func (ec *executionContext) field_Query_dataTransferExportDataFromResults_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "parameters", ec.unmarshalNDataTransferParameters2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferParameters) + if err != nil { + return nil, err + } + args["parameters"] = arg4 + return args, nil +} + +func (ec *executionContext) field_Query_dataTransferRemoveDataFile_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "dataFileId", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["dataFileId"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_deleteAuthProviderConfiguration_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["id"] = arg0 return args, nil } -func (ec *executionContext) field_Query_deleteUser_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_deleteConnectionsAccess_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionIds", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["connectionIds"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "subjects", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["subjects"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Query_deleteTeam_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["teamId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "force", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["force"] = arg1 + return args, nil +} + +func (ec *executionContext) field_Query_deleteUserCredentials_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["userId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "providerId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["providerId"] = arg1 return args, nil } -func (ec *executionContext) field_Query_driverList_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_deleteUserMetaParameter_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["id"] = arg0 return args, nil } -func (ec *executionContext) field_Query_enableUser_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_deleteUser_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["userId"] = arg0 - var arg1 bool - if tmp, ok := rawArgs["enabled"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabled")) - arg1, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } + return args, nil +} + +func (ec *executionContext) field_Query_driverList_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["id"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_enableUser_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["userId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "enabled", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err } args["enabled"] = arg1 return args, nil } -func (ec *executionContext) field_Query_getConnectionSubjectAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_federatedAuthTaskResult_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "taskId", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["taskId"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_getConnectionSubjectAccess_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["connectionId"] = arg0 + args["connectionId"] = arg1 return args, nil } -func (ec *executionContext) field_Query_getSubjectConnectionAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_getSubjectConnectionAccess_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["subjectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subjectId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "subjectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["subjectId"] = arg0 return args, nil } -func (ec *executionContext) field_Query_grantUserRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_grantUserTeam_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["userId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["roleId"] = arg1 + args["teamId"] = arg1 return args, nil } -func (ec *executionContext) field_Query_listAuthProviderConfigurationParameters_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_listAuthProviderConfigurationParameters_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "providerId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["providerId"] = arg0 return args, nil } -func (ec *executionContext) field_Query_listAuthProviderConfigurations_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_listAuthProviderConfigurations_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "providerId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } args["providerId"] = arg0 return args, nil } -func (ec *executionContext) field_Query_listRoles_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_listTeams_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["roleId"] = arg0 + args["teamId"] = arg0 return args, nil } -func (ec *executionContext) field_Query_listUsers_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_listUsers_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "page", ec.unmarshalNPageInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐPageInput) + if err != nil { + return nil, err } - args["userId"] = arg0 + args["page"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "filter", ec.unmarshalNAdminUserFilterInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserFilterInput) + if err != nil { + return nil, err + } + args["filter"] = arg1 return args, nil } -func (ec *executionContext) field_Query_metadataGetNodeDDL_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_metadataGetNodeDDL_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodeId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodeId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodeId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["nodeId"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["options"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("options")) - arg1, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "options", ec.unmarshalOObject2interface) + if err != nil { + return nil, err } args["options"] = arg1 return args, nil } -func (ec *executionContext) field_Query_navGetStructContainers_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_metadataGetNodeExtendedDDL_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodeId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["nodeId"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_navGetStructContainers_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["catalog"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("catalog")) - arg2, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "catalog", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["catalog"] = arg2 + args["catalog"] = arg3 return args, nil } -func (ec *executionContext) field_Query_navNodeChildren_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_navNodeChildren_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["parentPath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parentPath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "parentPath", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["parentPath"] = arg0 - var arg1 *int - if tmp, ok := rawArgs["offset"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("offset")) - arg1, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "offset", ec.unmarshalOInt2ᚖint) + if err != nil { + return nil, err } args["offset"] = arg1 - var arg2 *int - if tmp, ok := rawArgs["limit"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("limit")) - arg2, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "limit", ec.unmarshalOInt2ᚖint) + if err != nil { + return nil, err } args["limit"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["onlyFolders"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("onlyFolders")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "onlyFolders", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err } args["onlyFolders"] = arg3 return args, nil } -func (ec *executionContext) field_Query_navNodeInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_navNodeInfo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["nodePath"] = arg0 return args, nil } -func (ec *executionContext) field_Query_navNodeParents_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_navNodeParents_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["nodePath"] = arg0 return args, nil } -func (ec *executionContext) field_Query_navRefreshNode_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_navRefreshNode_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["nodePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePath")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePath", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["nodePath"] = arg0 return args, nil } -func (ec *executionContext) field_Query_readSessionLog_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_readSessionLog_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *int - if tmp, ok := rawArgs["maxEntries"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("maxEntries")) - arg0, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "maxEntries", ec.unmarshalOInt2ᚖint) + if err != nil { + return nil, err } args["maxEntries"] = arg0 - var arg1 *bool - if tmp, ok := rawArgs["clearEntries"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearEntries")) - arg1, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "clearEntries", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err } args["clearEntries"] = arg1 return args, nil } -func (ec *executionContext) field_Query_revokeUserRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_revokeUserTeam_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["userId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["roleId"] = arg1 + args["teamId"] = arg1 return args, nil } -func (ec *executionContext) field_Query_rmListResources_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_rmListProjectGrantedPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["projectId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["folder"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folder")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + return args, nil +} + +func (ec *executionContext) field_Query_rmListResources_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "folder", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["folder"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["nameMask"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameMask")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "nameMask", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["nameMask"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["readProperties"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("readProperties")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "readProperties", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err } args["readProperties"] = arg3 - var arg4 *bool - if tmp, ok := rawArgs["readHistory"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("readHistory")) - arg4, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "readHistory", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err } args["readHistory"] = arg4 return args, nil } -func (ec *executionContext) field_Query_rmReadResourceAsString_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_rmListSubjectProjectsPermissionGrants_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["projectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "subjectId", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["subjectId"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_rmProject_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["projectId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["resourcePath"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourcePath")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + return args, nil +} + +func (ec *executionContext) field_Query_rmReadResourceAsString_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "resourcePath", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["resourcePath"] = arg1 return args, nil } -func (ec *executionContext) field_Query_saveAuthProviderConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_saveAuthProviderConfiguration_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "providerId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["providerId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["id"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["displayName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("displayName")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "displayName", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["displayName"] = arg2 - var arg3 *bool - if tmp, ok := rawArgs["disabled"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("disabled")) - arg3, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "disabled", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err } args["disabled"] = arg3 - var arg4 *string - if tmp, ok := rawArgs["iconURL"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("iconURL")) - arg4, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "iconURL", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["iconURL"] = arg4 - var arg5 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg5, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "description", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["description"] = arg5 - var arg6 interface{} - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg6, err = ec.unmarshalOObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "parameters", ec.unmarshalOObject2interface) + if err != nil { + return nil, err } args["parameters"] = arg6 return args, nil } -func (ec *executionContext) field_Query_saveUserMetaParameter_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_saveUserMetaParameter_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["id"] = arg0 - var arg1 string - if tmp, ok := rawArgs["displayName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("displayName")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "displayName", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["displayName"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "description", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["description"] = arg2 - var arg3 bool - if tmp, ok := rawArgs["required"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("required")) - arg3, err = ec.unmarshalNBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "required", ec.unmarshalNBoolean2bool) + if err != nil { + return nil, err } args["required"] = arg3 return args, nil } -func (ec *executionContext) field_Query_searchConnections_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_searchConnections_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["hostNames"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hostNames")) - arg0, err = ec.unmarshalNString2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "hostNames", ec.unmarshalNString2ᚕstringᚄ) + if err != nil { + return nil, err } args["hostNames"] = arg0 return args, nil } -func (ec *executionContext) field_Query_setConnectionSubjectAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_setConnectionSubjectAccess_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 []string - if tmp, ok := rawArgs["subjects"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subjects")) - arg1, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "subjects", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } - args["subjects"] = arg1 + args["subjects"] = arg2 return args, nil } -func (ec *executionContext) field_Query_setDefaultNavigatorSettings_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_setDefaultNavigatorSettings_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 model.NavigatorSettingsInput - if tmp, ok := rawArgs["settings"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("settings")) - arg0, err = ec.unmarshalNNavigatorSettingsInput2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettingsInput(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "settings", ec.unmarshalNNavigatorSettingsInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettingsInput) + if err != nil { + return nil, err } args["settings"] = arg0 return args, nil } -func (ec *executionContext) field_Query_setSubjectConnectionAccess_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_setSubjectConnectionAccess_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["subjectId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subjectId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "subjectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["subjectId"] = arg0 - var arg1 []string - if tmp, ok := rawArgs["connections"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connections")) - arg1, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connections", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } args["connections"] = arg1 return args, nil } -func (ec *executionContext) field_Query_setSubjectPermissions_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_setSubjectPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "subjectId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["roleId"] = arg0 - var arg1 []string - if tmp, ok := rawArgs["permissions"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("permissions")) - arg1, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args["subjectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "permissions", ec.unmarshalNID2ᚕstringᚄ) + if err != nil { + return nil, err } args["permissions"] = arg1 return args, nil } -func (ec *executionContext) field_Query_setUserCredentials_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_setTeamMetaParameterValues_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["teamId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "parameters", ec.unmarshalNObject2interface) + if err != nil { + return nil, err + } + args["parameters"] = arg1 + return args, nil +} + +func (ec *executionContext) field_Query_setUserAuthRole_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["userId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["providerId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "authRole", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err + } + args["authRole"] = arg1 + return args, nil +} + +func (ec *executionContext) field_Query_setUserCredentials_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["userId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "providerId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["providerId"] = arg1 - var arg2 interface{} - if tmp, ok := rawArgs["credentials"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - arg2, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "credentials", ec.unmarshalNObject2interface) + if err != nil { + return nil, err } args["credentials"] = arg2 return args, nil } -func (ec *executionContext) field_Query_setUserMetaParameterValues_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_setUserMetaParameterValues_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["userId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["userId"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["parameters"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parameters")) - arg1, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "parameters", ec.unmarshalNObject2interface) + if err != nil { + return nil, err } args["parameters"] = arg1 return args, nil } -func (ec *executionContext) field_Query_sqlCompletionProposals_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_setUserTeamRole_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "userId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["userId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["query"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("query")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["teamId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "teamRole", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } - args["query"] = arg2 - var arg3 int - if tmp, ok := rawArgs["position"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("position")) - arg3, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } + args["teamRole"] = arg2 + return args, nil +} + +func (ec *executionContext) field_Query_sqlCompletionProposals_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["position"] = arg3 - var arg4 *int - if tmp, ok := rawArgs["maxResults"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("maxResults")) - arg4, err = ec.unmarshalOInt2ᚖint(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["maxResults"] = arg4 - var arg5 *bool - if tmp, ok := rawArgs["simpleMode"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("simpleMode")) - arg5, err = ec.unmarshalOBoolean2ᚖbool(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "query", ec.unmarshalNString2string) + if err != nil { + return nil, err + } + args["query"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "position", ec.unmarshalNInt2int) + if err != nil { + return nil, err + } + args["position"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "maxResults", ec.unmarshalOInt2ᚖint) + if err != nil { + return nil, err } - args["simpleMode"] = arg5 + args["maxResults"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "simpleMode", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["simpleMode"] = arg6 return args, nil } -func (ec *executionContext) field_Query_sqlDialectInfo_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlDialectInfo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["connectionId"] = arg0 + args["connectionId"] = arg1 return args, nil } -func (ec *executionContext) field_Query_sqlEntityQueryGenerators_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlEntityQueryGenerators_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 []string - if tmp, ok := rawArgs["nodePathList"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePathList")) - arg0, err = ec.unmarshalNString2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "nodePathList", ec.unmarshalNString2ᚕstringᚄ) + if err != nil { + return nil, err } args["nodePathList"] = arg0 return args, nil } -func (ec *executionContext) field_Query_sqlFormatQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlFormatQuery_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["query"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("query")) - arg2, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "query", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["query"] = arg2 + args["query"] = arg3 return args, nil } -func (ec *executionContext) field_Query_sqlGenerateEntityQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlGenerateEntityQuery_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["generatorId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("generatorId")) - arg0, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "generatorId", ec.unmarshalNString2string) + if err != nil { + return nil, err } args["generatorId"] = arg0 - var arg1 interface{} - if tmp, ok := rawArgs["options"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("options")) - arg1, err = ec.unmarshalNObject2interface(ctx, tmp) - if err != nil { - return nil, err - } + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "options", ec.unmarshalNObject2interface) + if err != nil { + return nil, err } args["options"] = arg1 - var arg2 []string - if tmp, ok := rawArgs["nodePathList"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nodePathList")) - arg2, err = ec.unmarshalNString2ᚕstringᚄ(ctx, tmp) - if err != nil { - return nil, err - } + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "nodePathList", ec.unmarshalNString2ᚕstringᚄ) + if err != nil { + return nil, err } args["nodePathList"] = arg2 return args, nil } -func (ec *executionContext) field_Query_sqlListContexts_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlGenerateGroupingQuery_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err } args["contextId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "columnNames", ec.unmarshalOString2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["columnNames"] = arg4 + arg5, err := graphql.ProcessArgField(ctx, rawArgs, "functions", ec.unmarshalOString2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["functions"] = arg5 + arg6, err := graphql.ProcessArgField(ctx, rawArgs, "showDuplicatesOnly", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["showDuplicatesOnly"] = arg6 return args, nil } -func (ec *executionContext) field_Query_sqlParseQuery_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlListContexts_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["script"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("script")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["script"] = arg1 - var arg2 int - if tmp, ok := rawArgs["position"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("position")) - arg2, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["position"] = arg2 + args["contextId"] = arg2 return args, nil } -func (ec *executionContext) field_Query_sqlParseScript_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlParseQuery_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["script"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("script")) - arg1, err = ec.unmarshalNString2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "script", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["script"] = arg1 + args["script"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "position", ec.unmarshalNInt2int) + if err != nil { + return nil, err + } + args["position"] = arg3 return args, nil } -func (ec *executionContext) field_Query_sqlSupportedOperations_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlParseScript_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["connectionId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } - } - args["connectionId"] = arg0 - var arg1 string - if tmp, ok := rawArgs["contextId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("contextId")) - arg1, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["contextId"] = arg1 - var arg2 string - if tmp, ok := rawArgs["resultsId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resultsId")) - arg2, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["resultsId"] = arg2 - var arg3 int - if tmp, ok := rawArgs["attributeIndex"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("attributeIndex")) - arg3, err = ec.unmarshalNInt2int(ctx, tmp) - if err != nil { - return nil, err - } + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "script", ec.unmarshalNString2string) + if err != nil { + return nil, err } - args["attributeIndex"] = arg3 + args["script"] = arg2 return args, nil } -func (ec *executionContext) field_Query_updateConnectionConfiguration_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_sqlSupportedOperations_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["id"] = arg0 - var arg1 model.ConnectionConfig - if tmp, ok := rawArgs["config"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) - arg1, err = ec.unmarshalNConnectionConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx, tmp) - if err != nil { - return nil, err - } + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "connectionId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["config"] = arg1 + args["connectionId"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "contextId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["contextId"] = arg2 + arg3, err := graphql.ProcessArgField(ctx, rawArgs, "resultsId", ec.unmarshalNID2string) + if err != nil { + return nil, err + } + args["resultsId"] = arg3 + arg4, err := graphql.ProcessArgField(ctx, rawArgs, "attributeIndex", ec.unmarshalNInt2int) + if err != nil { + return nil, err + } + args["attributeIndex"] = arg4 return args, nil } -func (ec *executionContext) field_Query_updateRole_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_updateTeam_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 string - if tmp, ok := rawArgs["roleId"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleId")) - arg0, err = ec.unmarshalNID2string(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "teamId", ec.unmarshalNID2string) + if err != nil { + return nil, err } - args["roleId"] = arg0 - var arg1 *string - if tmp, ok := rawArgs["roleName"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleName")) - arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["teamId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "teamName", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } - args["roleName"] = arg1 - var arg2 *string - if tmp, ok := rawArgs["description"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - arg2, err = ec.unmarshalOString2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args["teamName"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "description", ec.unmarshalOString2ᚖstring) + if err != nil { + return nil, err } args["description"] = arg2 return args, nil } -func (ec *executionContext) field_Query_userConnections_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field_Query_userConnections_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 *string - if tmp, ok := rawArgs["id"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - arg0, err = ec.unmarshalOID2ᚖstring(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "projectId", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err } - args["id"] = arg0 + args["projectId"] = arg0 + arg1, err := graphql.ProcessArgField(ctx, rawArgs, "id", ec.unmarshalOID2ᚖstring) + if err != nil { + return nil, err + } + args["id"] = arg1 + arg2, err := graphql.ProcessArgField(ctx, rawArgs, "projectIds", ec.unmarshalOID2ᚕstringᚄ) + if err != nil { + return nil, err + } + args["projectIds"] = arg2 return args, nil } -func (ec *executionContext) field___Type_enumValues_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field___Directive_args_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 bool - if tmp, ok := rawArgs["includeDeprecated"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) - arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "includeDeprecated", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err } args["includeDeprecated"] = arg0 return args, nil } -func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +func (ec *executionContext) field___Field_args_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { var err error - args := map[string]interface{}{} - var arg0 bool - if tmp, ok := rawArgs["includeDeprecated"]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) - arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) - if err != nil { - return nil, err - } + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "includeDeprecated", ec.unmarshalOBoolean2ᚖbool) + if err != nil { + return nil, err + } + args["includeDeprecated"] = arg0 + return args, nil +} + +func (ec *executionContext) field___Type_enumValues_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "includeDeprecated", ec.unmarshalOBoolean2bool) + if err != nil { + return nil, err + } + args["includeDeprecated"] = arg0 + return args, nil +} + +func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := graphql.ProcessArgField(ctx, rawArgs, "includeDeprecated", ec.unmarshalOBoolean2bool) + if err != nil { + return nil, err } args["includeDeprecated"] = arg0 return args, nil @@ -9216,42 +11043,118 @@ func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArg // region ************************** directives.gotpl ************************** -// endregion ************************** directives.gotpl ************************** - -// region **************************** field.gotpl ***************************** +func (ec *executionContext) _queryMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) graphql.Marshaler { -func (ec *executionContext) _AdminAuthProviderConfiguration_providerId(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_providerId(ctx, field) + for _, d := range obj.Directives { + switch d.Name { + case "since": + rawArgs := d.ArgumentMap(ec.Variables) + args, err := ec.dir_since_args(ctx, rawArgs) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + n := next + next = func(ctx context.Context) (any, error) { + if ec.directives.Since == nil { + return nil, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, n, args["version"].(string)) + } + } + } + tmp, err := next(ctx) if err != nil { + ec.Error(ctx, err) return graphql.Null } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + if data, ok := tmp.(graphql.Marshaler); ok { + return data + } + ec.Errorf(ctx, `unexpected type %T from directive, should be graphql.Marshaler`, tmp) + return graphql.Null + +} + +func (ec *executionContext) _mutationMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) graphql.Marshaler { + + for _, d := range obj.Directives { + switch d.Name { + case "since": + rawArgs := d.ArgumentMap(ec.Variables) + args, err := ec.dir_since_args(ctx, rawArgs) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + n := next + next = func(ctx context.Context) (any, error) { + if ec.directives.Since == nil { + return nil, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, n, args["version"].(string)) + } } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderID, nil - }) + } + tmp, err := next(ctx) if err != nil { ec.Error(ctx, err) return graphql.Null } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") + if data, ok := tmp.(graphql.Marshaler); ok { + return data + } + ec.Errorf(ctx, `unexpected type %T from directive, should be graphql.Marshaler`, tmp) + return graphql.Null + +} + +func (ec *executionContext) _fieldMiddleware(ctx context.Context, obj any, next graphql.Resolver) graphql.Resolver { + fc := graphql.GetFieldContext(ctx) + for _, d := range fc.Field.Directives { + switch d.Name { + case "since": + rawArgs := d.ArgumentMap(ec.Variables) + args, err := ec.dir_since_args(ctx, rawArgs) + if err != nil { + ec.Error(ctx, err) + return nil + } + n := next + next = func(ctx context.Context) (any, error) { + if ec.directives.Since == nil { + return nil, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, n, args["version"].(string)) + } } - return graphql.Null } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return next +} + +// endregion ************************** directives.gotpl ************************** + +// region **************************** field.gotpl ***************************** + +func (ec *executionContext) _AdminAuthProviderConfiguration_providerId(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_providerId, + func(ctx context.Context) (any, error) { + return obj.ProviderID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_providerId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_providerId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9265,37 +11168,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_provider } func (ec *executionContext) _AdminAuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9309,37 +11199,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_id(ctx c } func (ec *executionContext) _AdminAuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9353,37 +11230,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_displayN } func (ec *executionContext) _AdminAuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_disabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Disabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_disabled, + func(ctx context.Context) (any, error) { + return obj.Disabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_disabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9397,34 +11261,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_disabled } func (ec *executionContext) _AdminAuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_iconURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IconURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_iconURL, + func(ctx context.Context) (any, error) { + return obj.IconURL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_iconURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9438,34 +11292,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_iconURL( } func (ec *executionContext) _AdminAuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9479,37 +11323,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_descript } func (ec *executionContext) _AdminAuthProviderConfiguration_parameters(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_parameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Parameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_parameters, + func(ctx context.Context) (any, error) { + return obj.Parameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_parameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_parameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9523,34 +11354,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_paramete } func (ec *executionContext) _AdminAuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_signInLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignInLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_signInLink, + func(ctx context.Context) (any, error) { + return obj.SignInLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signInLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9564,34 +11385,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signInLi } func (ec *executionContext) _AdminAuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_signOutLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignOutLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_signOutLink, + func(ctx context.Context) (any, error) { + return obj.SignOutLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signOutLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9605,34 +11416,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_signOutL } func (ec *executionContext) _AdminAuthProviderConfiguration_redirectLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RedirectLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_redirectLink, + func(ctx context.Context) (any, error) { + return obj.RedirectLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_redirectLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9646,34 +11447,102 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_redirect } func (ec *executionContext) _AdminAuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetadataLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_metadataLink, + func(ctx context.Context) (any, error) { + return obj.MetadataLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_metadataLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminAuthProviderConfiguration", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AdminAuthProviderConfiguration_acsLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_acsLink, + func(ctx context.Context) (any, error) { + return obj.AcsLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_acsLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminAuthProviderConfiguration", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _AdminAuthProviderConfiguration_entityIdLink(ctx context.Context, field graphql.CollectedField, obj *model.AdminAuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminAuthProviderConfiguration_entityIdLink, + func(ctx context.Context) (any, error) { + return obj.EntityIDLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.2.1") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_entityIdLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminAuthProviderConfiguration", Field: field, @@ -9687,37 +11556,24 @@ func (ec *executionContext) fieldContext_AdminAuthProviderConfiguration_metadata } func (ec *executionContext) _AdminConnectionGrantInfo_connectionId(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectionID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionGrantInfo_connectionId, + func(ctx context.Context) (any, error) { + return obj.ConnectionID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_connectionId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_connectionId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionGrantInfo", Field: field, @@ -9731,37 +11587,24 @@ func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_connectionId(c } func (ec *executionContext) _AdminConnectionGrantInfo_dataSourceId(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataSourceID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionGrantInfo_dataSourceId, + func(ctx context.Context) (any, error) { + return obj.DataSourceID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_dataSourceId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionGrantInfo", Field: field, @@ -9775,37 +11618,24 @@ func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_dataSourceId(c } func (ec *executionContext) _AdminConnectionGrantInfo_subjectId(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubjectID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionGrantInfo_subjectId, + func(ctx context.Context) (any, error) { + return obj.SubjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionGrantInfo", Field: field, @@ -9819,37 +11649,24 @@ func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectId(ctx } func (ec *executionContext) _AdminConnectionGrantInfo_subjectType(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionGrantInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubjectType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.AdminSubjectType) - fc.Result = res - return ec.marshalNAdminSubjectType2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminSubjectType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionGrantInfo_subjectType, + func(ctx context.Context) (any, error) { + return obj.SubjectType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAdminSubjectType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminSubjectType, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionGrantInfo", Field: field, @@ -9863,37 +11680,24 @@ func (ec *executionContext) fieldContext_AdminConnectionGrantInfo_subjectType(ct } func (ec *executionContext) _AdminConnectionSearchInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionSearchInfo_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionSearchInfo", Field: field, @@ -9907,37 +11711,24 @@ func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_displayName(c } func (ec *executionContext) _AdminConnectionSearchInfo_host(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_host(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Host, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionSearchInfo_host, + func(ctx context.Context) (any, error) { + return obj.Host, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_host(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_host(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionSearchInfo", Field: field, @@ -9951,37 +11742,24 @@ func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_host(ctx cont } func (ec *executionContext) _AdminConnectionSearchInfo_port(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_port(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Port, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionSearchInfo_port, + func(ctx context.Context) (any, error) { + return obj.Port, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_port(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_port(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionSearchInfo", Field: field, @@ -9995,37 +11773,24 @@ func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_port(ctx cont } func (ec *executionContext) _AdminConnectionSearchInfo_possibleDrivers(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_possibleDrivers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PossibleDrivers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionSearchInfo_possibleDrivers, + func(ctx context.Context) (any, error) { + return obj.PossibleDrivers, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_possibleDrivers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_possibleDrivers(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminConnectionSearchInfo", Field: field, @@ -10039,39 +11804,57 @@ func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_possibleDrive } func (ec *executionContext) _AdminConnectionSearchInfo_defaultDriver(ctx context.Context, field graphql.CollectedField, obj *model.AdminConnectionSearchInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminConnectionSearchInfo_defaultDriver(ctx, field) - if err != nil { - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminConnectionSearchInfo_defaultDriver, + func(ctx context.Context) (any, error) { + return obj.DefaultDriver, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_defaultDriver(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminConnectionSearchInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultDriver, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AdminObjectGrantInfo_subjectId(ctx context.Context, field graphql.CollectedField, obj *model.AdminObjectGrantInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminObjectGrantInfo_subjectId, + func(ctx context.Context) (any, error) { + return obj.SubjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_defaultDriver(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminObjectGrantInfo_subjectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AdminConnectionSearchInfo", + Object: "AdminObjectGrantInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10082,38 +11865,155 @@ func (ec *executionContext) fieldContext_AdminConnectionSearchInfo_defaultDriver return fc, nil } -func (ec *executionContext) _AdminPermissionInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_id(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _AdminObjectGrantInfo_subjectType(ctx context.Context, field graphql.CollectedField, obj *model.AdminObjectGrantInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminObjectGrantInfo_subjectType, + func(ctx context.Context) (any, error) { + return obj.SubjectType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAdminSubjectType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminSubjectType, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminObjectGrantInfo_subjectType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminObjectGrantInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type AdminSubjectType does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AdminObjectGrantInfo_objectPermissions(ctx context.Context, field graphql.CollectedField, obj *model.AdminObjectGrantInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminObjectGrantInfo_objectPermissions, + func(ctx context.Context) (any, error) { + return obj.ObjectPermissions, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAdminObjectPermissions2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminObjectPermissions, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminObjectGrantInfo_objectPermissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminObjectGrantInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "objectId": + return ec.fieldContext_AdminObjectPermissions_objectId(ctx, field) + case "permissions": + return ec.fieldContext_AdminObjectPermissions_permissions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminObjectPermissions", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AdminObjectPermissions_objectId(ctx context.Context, field graphql.CollectedField, obj *model.AdminObjectPermissions) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminObjectPermissions_objectId, + func(ctx context.Context) (any, error) { + return obj.ObjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminObjectPermissions_objectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminObjectPermissions", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _AdminObjectPermissions_permissions(ctx context.Context, field graphql.CollectedField, obj *model.AdminObjectPermissions) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminObjectPermissions_permissions, + func(ctx context.Context) (any, error) { + return obj.Permissions, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminObjectPermissions_permissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminObjectPermissions", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AdminPermissionInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminPermissionInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminPermissionInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminPermissionInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminPermissionInfo", Field: field, @@ -10127,34 +12027,24 @@ func (ec *executionContext) fieldContext_AdminPermissionInfo_id(ctx context.Cont } func (ec *executionContext) _AdminPermissionInfo_label(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminPermissionInfo_label, + func(ctx context.Context) (any, error) { + return obj.Label, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminPermissionInfo_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminPermissionInfo_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminPermissionInfo", Field: field, @@ -10168,34 +12058,24 @@ func (ec *executionContext) fieldContext_AdminPermissionInfo_label(ctx context.C } func (ec *executionContext) _AdminPermissionInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminPermissionInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminPermissionInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminPermissionInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminPermissionInfo", Field: field, @@ -10209,37 +12089,24 @@ func (ec *executionContext) fieldContext_AdminPermissionInfo_description(ctx con } func (ec *executionContext) _AdminPermissionInfo_provider(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_provider(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Provider, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminPermissionInfo_provider, + func(ctx context.Context) (any, error) { + return obj.Provider, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminPermissionInfo_provider(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminPermissionInfo_provider(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminPermissionInfo", Field: field, @@ -10253,34 +12120,24 @@ func (ec *executionContext) fieldContext_AdminPermissionInfo_provider(ctx contex } func (ec *executionContext) _AdminPermissionInfo_category(ctx context.Context, field graphql.CollectedField, obj *model.AdminPermissionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminPermissionInfo_category(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Category, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminPermissionInfo_category, + func(ctx context.Context) (any, error) { + return obj.Category, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminPermissionInfo_category(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminPermissionInfo_category(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminPermissionInfo", Field: field, @@ -10293,40 +12150,27 @@ func (ec *executionContext) fieldContext_AdminPermissionInfo_category(ctx contex return fc, nil } -func (ec *executionContext) _AdminRoleInfo_roleId(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RoleID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _AdminTeamInfo_teamId(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_teamId, + func(ctx context.Context) (any, error) { + return obj.TeamID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminRoleInfo_roleId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminTeamInfo_teamId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", + Object: "AdminTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10337,37 +12181,27 @@ func (ec *executionContext) fieldContext_AdminRoleInfo_roleId(ctx context.Contex return fc, nil } -func (ec *executionContext) _AdminRoleInfo_roleName(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RoleName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _AdminTeamInfo_teamName(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_teamName, + func(ctx context.Context) (any, error) { + return obj.TeamName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminRoleInfo_roleName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminTeamInfo_teamName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", + Object: "AdminTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10378,37 +12212,27 @@ func (ec *executionContext) fieldContext_AdminRoleInfo_roleName(ctx context.Cont return fc, nil } -func (ec *executionContext) _AdminRoleInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _AdminTeamInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AdminRoleInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminTeamInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", + Object: "AdminTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10419,40 +12243,58 @@ func (ec *executionContext) fieldContext_AdminRoleInfo_description(ctx context.C return fc, nil } -func (ec *executionContext) _AdminRoleInfo_grantedUsers(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedUsers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null +func (ec *executionContext) _AdminTeamInfo_metaParameters(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_metaParameters, + func(ctx context.Context) (any, error) { + return obj.MetaParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminTeamInfo_metaParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminTeamInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AdminTeamInfo_grantedUsers(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_grantedUsers, + func(ctx context.Context) (any, error) { + return obj.GrantedUsers, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminRoleInfo_grantedUsers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminTeamInfo_grantedUsers(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", + Object: "AdminTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10463,40 +12305,92 @@ func (ec *executionContext) fieldContext_AdminRoleInfo_grantedUsers(ctx context. return fc, nil } -func (ec *executionContext) _AdminRoleInfo_grantedConnections(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedConnections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null +func (ec *executionContext) _AdminTeamInfo_grantedUsersInfo(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_grantedUsersInfo, + func(ctx context.Context) (any, error) { + return obj.GrantedUsersInfo, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.5") + if err != nil { + var zeroVal []*model.AdminUserTeamGrantInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.AdminUserTeamGrantInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.5") + if err != nil { + var zeroVal []*model.AdminUserTeamGrantInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.AdminUserTeamGrantInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAdminUserTeamGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserTeamGrantInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminTeamInfo_grantedUsersInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminTeamInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "userId": + return ec.fieldContext_AdminUserTeamGrantInfo_userId(ctx, field) + case "teamRole": + return ec.fieldContext_AdminUserTeamGrantInfo_teamRole(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminUserTeamGrantInfo", field.Name) + }, } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_AdminRoleInfo_grantedConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _AdminTeamInfo_grantedConnections(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_grantedConnections, + func(ctx context.Context) (any, error) { + return obj.GrantedConnections, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminTeamInfo_grantedConnections(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", + Object: "AdminTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10517,40 +12411,27 @@ func (ec *executionContext) fieldContext_AdminRoleInfo_grantedConnections(ctx co return fc, nil } -func (ec *executionContext) _AdminRoleInfo_rolePermissions(ctx context.Context, field graphql.CollectedField, obj *model.AdminRoleInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RolePermissions, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) +func (ec *executionContext) _AdminTeamInfo_teamPermissions(ctx context.Context, field graphql.CollectedField, obj *model.AdminTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminTeamInfo_teamPermissions, + func(ctx context.Context) (any, error) { + return obj.TeamPermissions, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminRoleInfo_rolePermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminTeamInfo_teamPermissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AdminRoleInfo", + Object: "AdminTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10562,37 +12443,24 @@ func (ec *executionContext) fieldContext_AdminRoleInfo_rolePermissions(ctx conte } func (ec *executionContext) _AdminUserInfo_userId(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_userId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_userId, + func(ctx context.Context) (any, error) { + return obj.UserID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_userId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_userId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10606,37 +12474,24 @@ func (ec *executionContext) fieldContext_AdminUserInfo_userId(ctx context.Contex } func (ec *executionContext) _AdminUserInfo_metaParameters(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetaParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_metaParameters, + func(ctx context.Context) (any, error) { + return obj.MetaParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_metaParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_metaParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10650,37 +12505,24 @@ func (ec *executionContext) fieldContext_AdminUserInfo_metaParameters(ctx contex } func (ec *executionContext) _AdminUserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConfigurationParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_configurationParameters, + func(ctx context.Context) (any, error) { + return obj.ConfigurationParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_configurationParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10693,38 +12535,25 @@ func (ec *executionContext) fieldContext_AdminUserInfo_configurationParameters(c return fc, nil } -func (ec *executionContext) _AdminUserInfo_grantedRoles(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_grantedRoles(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedRoles, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) +func (ec *executionContext) _AdminUserInfo_grantedTeams(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_grantedTeams, + func(ctx context.Context) (any, error) { + return obj.GrantedTeams, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_grantedRoles(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_grantedTeams(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10738,37 +12567,24 @@ func (ec *executionContext) fieldContext_AdminUserInfo_grantedRoles(ctx context. } func (ec *executionContext) _AdminUserInfo_grantedConnections(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.GrantedConnections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_grantedConnections, + func(ctx context.Context) (any, error) { + return obj.GrantedConnections, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_grantedConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_grantedConnections(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10792,37 +12608,24 @@ func (ec *executionContext) fieldContext_AdminUserInfo_grantedConnections(ctx co } func (ec *executionContext) _AdminUserInfo_origins(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_origins(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Origins, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectOrigin) - fc.Result = res - return ec.marshalNObjectOrigin2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOriginᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_origins, + func(ctx context.Context) (any, error) { + return obj.Origins, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectOrigin2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOriginᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_origins(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_origins(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10850,37 +12653,24 @@ func (ec *executionContext) fieldContext_AdminUserInfo_origins(ctx context.Conte } func (ec *executionContext) _AdminUserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LinkedAuthProviders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_linkedAuthProviders, + func(ctx context.Context) (any, error) { + return obj.LinkedAuthProviders, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_linkedAuthProviders(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10894,37 +12684,24 @@ func (ec *executionContext) fieldContext_AdminUserInfo_linkedAuthProviders(ctx c } func (ec *executionContext) _AdminUserInfo_enabled(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AdminUserInfo_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_enabled, + func(ctx context.Context) (any, error) { + return obj.Enabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AdminUserInfo_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_enabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AdminUserInfo", Field: field, @@ -10937,40 +12714,27 @@ func (ec *executionContext) fieldContext_AdminUserInfo_enabled(ctx context.Conte return fc, nil } -func (ec *executionContext) _AsyncTaskInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _AdminUserInfo_authRole(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_authRole, + func(ctx context.Context) (any, error) { + return obj.AuthRole, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AsyncTaskInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_authRole(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", + Object: "AdminUserInfo", Field: field, IsMethod: false, IsResolver: false, @@ -10981,120 +12745,260 @@ func (ec *executionContext) fieldContext_AsyncTaskInfo_id(ctx context.Context, f return fc, nil } -func (ec *executionContext) _AsyncTaskInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _AdminUserInfo_disableDate(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_disableDate, + func(ctx context.Context) (any, error) { + return obj.DisableDate, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.2") + if err != nil { + var zeroVal *time.Time + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *time.Time + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalODateTime2ᚖtimeᚐTime, + true, + false, + ) } -func (ec *executionContext) fieldContext_AsyncTaskInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_disableDate(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", + Object: "AdminUserInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type DateTime does not have child fields") }, } return fc, nil } -func (ec *executionContext) _AsyncTaskInfo_running(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_running(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Running, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _AdminUserInfo_disabledBy(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_disabledBy, + func(ctx context.Context) (any, error) { + return obj.DisabledBy, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.2") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AsyncTaskInfo_running(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AdminUserInfo_disabledBy(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "AsyncTaskInfo", + Object: "AdminUserInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _AsyncTaskInfo_status(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_status(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _AdminUserInfo_disableReason(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserInfo_disableReason, + func(ctx context.Context) (any, error) { + return obj.DisableReason, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.2") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AdminUserInfo_disableReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminUserInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Status, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AdminUserTeamGrantInfo_userId(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserTeamGrantInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserTeamGrantInfo_userId, + func(ctx context.Context) (any, error) { + return obj.UserID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.5") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AdminUserTeamGrantInfo_userId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminUserTeamGrantInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AdminUserTeamGrantInfo_teamRole(ctx context.Context, field graphql.CollectedField, obj *model.AdminUserTeamGrantInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AdminUserTeamGrantInfo_teamRole, + func(ctx context.Context) (any, error) { + return obj.TeamRole, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.5") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AdminUserTeamGrantInfo_teamRole(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AdminUserTeamGrantInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AsyncTaskInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AsyncTaskInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AsyncTaskInfo_status(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AsyncTaskInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AsyncTaskInfo", Field: field, @@ -11107,88 +13011,118 @@ func (ec *executionContext) fieldContext_AsyncTaskInfo_status(ctx context.Contex return fc, nil } -func (ec *executionContext) _AsyncTaskInfo_error(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_error(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Error, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ServerError) - fc.Result = res - return ec.marshalOServerError2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError(ctx, field.Selections, res) +func (ec *executionContext) _AsyncTaskInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AsyncTaskInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AsyncTaskInfo_error(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AsyncTaskInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AsyncTaskInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "message": - return ec.fieldContext_ServerError_message(ctx, field) - case "errorCode": - return ec.fieldContext_ServerError_errorCode(ctx, field) - case "errorType": - return ec.fieldContext_ServerError_errorType(ctx, field) - case "stackTrace": - return ec.fieldContext_ServerError_stackTrace(ctx, field) - case "causedBy": - return ec.fieldContext_ServerError_causedBy(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerError", field.Name) + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _AsyncTaskInfo_result(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_result(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Result, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _AsyncTaskInfo_running(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AsyncTaskInfo_running, + func(ctx context.Context) (any, error) { + return obj.Running, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AsyncTaskInfo_running(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AsyncTaskInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AsyncTaskInfo_status(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AsyncTaskInfo_status, + func(ctx context.Context) (any, error) { + return obj.Status, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AsyncTaskInfo_status(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AsyncTaskInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*model.SQLExecuteInfo) - fc.Result = res - return ec.marshalOSQLExecuteInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AsyncTaskInfo_error(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AsyncTaskInfo_error, + func(ctx context.Context) (any, error) { + return obj.Error, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError, + true, + false, + ) } -func (ec *executionContext) fieldContext_AsyncTaskInfo_result(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AsyncTaskInfo_error(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AsyncTaskInfo", Field: field, @@ -11196,50 +13130,42 @@ func (ec *executionContext) fieldContext_AsyncTaskInfo_result(ctx context.Contex IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "statusMessage": - return ec.fieldContext_SQLExecuteInfo_statusMessage(ctx, field) - case "duration": - return ec.fieldContext_SQLExecuteInfo_duration(ctx, field) - case "filterText": - return ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) - case "results": - return ec.fieldContext_SQLExecuteInfo_results(ctx, field) + case "message": + return ec.fieldContext_ServerError_message(ctx, field) + case "errorCode": + return ec.fieldContext_ServerError_errorCode(ctx, field) + case "errorType": + return ec.fieldContext_ServerError_errorType(ctx, field) + case "stackTrace": + return ec.fieldContext_ServerError_stackTrace(ctx, field) + case "causedBy": + return ec.fieldContext_ServerError_causedBy(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type SQLExecuteInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type ServerError", field.Name) }, } return fc, nil } func (ec *executionContext) _AsyncTaskInfo_taskResult(ctx context.Context, field graphql.CollectedField, obj *model.AsyncTaskInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.TaskResult, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AsyncTaskInfo_taskResult, + func(ctx context.Context) (any, error) { + return obj.TaskResult, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_AsyncTaskInfo_taskResult(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AsyncTaskInfo_taskResult(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AsyncTaskInfo", Field: field, @@ -11253,37 +13179,24 @@ func (ec *executionContext) fieldContext_AsyncTaskInfo_taskResult(ctx context.Co } func (ec *executionContext) _AuthCredentialInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11297,37 +13210,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_id(ctx context.Conte } func (ec *executionContext) _AuthCredentialInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11341,34 +13241,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_displayName(ctx cont } func (ec *executionContext) _AuthCredentialInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11382,37 +13272,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_description(ctx cont } func (ec *executionContext) _AuthCredentialInfo_admin(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_admin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Admin, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_admin, + func(ctx context.Context) (any, error) { + return obj.Admin, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_admin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_admin(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11426,37 +13303,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_admin(ctx context.Co } func (ec *executionContext) _AuthCredentialInfo_user(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_user(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.User, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_user, + func(ctx context.Context) (any, error) { + return obj.User, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_user(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_user(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11470,37 +13334,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_user(ctx context.Con } func (ec *executionContext) _AuthCredentialInfo_identifying(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_identifying(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Identifying, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_identifying, + func(ctx context.Context) (any, error) { + return obj.Identifying, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_identifying(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_identifying(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11514,34 +13365,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_identifying(ctx cont } func (ec *executionContext) _AuthCredentialInfo_possibleValues(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_possibleValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PossibleValues, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalOString2ᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_possibleValues, + func(ctx context.Context) (any, error) { + return obj.PossibleValues, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_possibleValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_possibleValues(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11555,34 +13396,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_possibleValues(ctx c } func (ec *executionContext) _AuthCredentialInfo_encryption(ctx context.Context, field graphql.CollectedField, obj *model.AuthCredentialInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthCredentialInfo_encryption(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Encryption, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.AuthCredentialEncryption) - fc.Result = res - return ec.marshalOAuthCredentialEncryption2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialEncryption(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthCredentialInfo_encryption, + func(ctx context.Context) (any, error) { + return obj.Encryption, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOAuthCredentialEncryption2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialEncryption, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthCredentialInfo_encryption(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthCredentialInfo_encryption(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthCredentialInfo", Field: field, @@ -11596,34 +13427,24 @@ func (ec *executionContext) fieldContext_AuthCredentialInfo_encryption(ctx conte } func (ec *executionContext) _AuthInfo_redirectLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_redirectLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RedirectLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthInfo_redirectLink, + func(ctx context.Context) (any, error) { + return obj.RedirectLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthInfo_redirectLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthInfo_redirectLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthInfo", Field: field, @@ -11637,34 +13458,24 @@ func (ec *executionContext) fieldContext_AuthInfo_redirectLink(ctx context.Conte } func (ec *executionContext) _AuthInfo_authId(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_authId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthInfo_authId, + func(ctx context.Context) (any, error) { + return obj.AuthID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthInfo_authId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthInfo_authId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthInfo", Field: field, @@ -11678,37 +13489,24 @@ func (ec *executionContext) fieldContext_AuthInfo_authId(ctx context.Context, fi } func (ec *executionContext) _AuthInfo_authStatus(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_authStatus(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthStatus, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.AuthStatus) - fc.Result = res - return ec.marshalNAuthStatus2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthStatus(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthInfo_authStatus, + func(ctx context.Context) (any, error) { + return obj.AuthStatus, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAuthStatus2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthStatus, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthInfo_authStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthInfo_authStatus(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthInfo", Field: field, @@ -11722,34 +13520,24 @@ func (ec *executionContext) fieldContext_AuthInfo_authStatus(ctx context.Context } func (ec *executionContext) _AuthInfo_userTokens(ctx context.Context, field graphql.CollectedField, obj *model.AuthInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthInfo_userTokens(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserTokens, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.UserAuthToken) - fc.Result = res - return ec.marshalOUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthInfo_userTokens, + func(ctx context.Context) (any, error) { + return obj.UserTokens, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthInfo_userTokens(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthInfo_userTokens(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthInfo", Field: field, @@ -11779,37 +13567,24 @@ func (ec *executionContext) fieldContext_AuthInfo_userTokens(ctx context.Context } func (ec *executionContext) _AuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, @@ -11823,37 +13598,24 @@ func (ec *executionContext) fieldContext_AuthProviderConfiguration_id(ctx contex } func (ec *executionContext) _AuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, @@ -11867,37 +13629,24 @@ func (ec *executionContext) fieldContext_AuthProviderConfiguration_displayName(c } func (ec *executionContext) _AuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_disabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Disabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_disabled, + func(ctx context.Context) (any, error) { + return obj.Disabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_disabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_disabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, @@ -11910,76 +13659,56 @@ func (ec *executionContext) fieldContext_AuthProviderConfiguration_disabled(ctx return fc, nil } -func (ec *executionContext) _AuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_iconURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IconURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _AuthProviderConfiguration_authRoleProvided(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_authRoleProvided, + func(ctx context.Context) (any, error) { + return obj.AuthRoleProvided, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_authRoleProvided(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _AuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _AuthProviderConfiguration_iconURL(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_iconURL, + func(ctx context.Context) (any, error) { + return obj.IconURL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_iconURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, @@ -11992,35 +13721,25 @@ func (ec *executionContext) fieldContext_AuthProviderConfiguration_description(c return fc, nil } -func (ec *executionContext) _AuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_signInLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignInLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _AuthProviderConfiguration_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, @@ -12033,35 +13752,87 @@ func (ec *executionContext) fieldContext_AuthProviderConfiguration_signInLink(ct return fc, nil } -func (ec *executionContext) _AuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_signOutLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SignOutLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _AuthProviderConfiguration_signInLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_signInLink, + func(ctx context.Context) (any, error) { + return obj.SignInLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderConfiguration_signInLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderConfiguration", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_signOutLink, + func(ctx context.Context) (any, error) { + return obj.SignOutLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderConfiguration_signOutLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderConfiguration", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AuthProviderConfiguration_redirectLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_redirectLink, + func(ctx context.Context) (any, error) { + return obj.RedirectLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_signOutLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_redirectLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, @@ -12075,34 +13846,102 @@ func (ec *executionContext) fieldContext_AuthProviderConfiguration_signOutLink(c } func (ec *executionContext) _AuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderConfiguration_metadataLink(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetadataLink, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_metadataLink, + func(ctx context.Context) (any, error) { + return obj.MetadataLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderConfiguration_metadataLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderConfiguration", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AuthProviderConfiguration_acsLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_acsLink, + func(ctx context.Context) (any, error) { + return obj.AcsLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderConfiguration_acsLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderConfiguration", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AuthProviderConfiguration_entityIdLink(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderConfiguration) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderConfiguration_entityIdLink, + func(ctx context.Context) (any, error) { + return obj.EntityIDLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.2.1") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderConfiguration_metadataLink(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderConfiguration_entityIdLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderConfiguration", Field: field, @@ -12116,34 +13955,24 @@ func (ec *executionContext) fieldContext_AuthProviderConfiguration_metadataLink( } func (ec *executionContext) _AuthProviderCredentialsProfile_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderCredentialsProfile_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderCredentialsProfile", Field: field, @@ -12157,34 +13986,24 @@ func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_id(ctx c } func (ec *executionContext) _AuthProviderCredentialsProfile_label(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderCredentialsProfile_label, + func(ctx context.Context) (any, error) { + return obj.Label, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderCredentialsProfile", Field: field, @@ -12198,34 +14017,24 @@ func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_label(ct } func (ec *executionContext) _AuthProviderCredentialsProfile_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderCredentialsProfile_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderCredentialsProfile", Field: field, @@ -12239,37 +14048,24 @@ func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_descript } func (ec *executionContext) _AuthProviderCredentialsProfile_credentialParameters(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderCredentialsProfile) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderCredentialsProfile_credentialParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CredentialParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AuthCredentialInfo) - fc.Result = res - return ec.marshalNAuthCredentialInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderCredentialsProfile_credentialParameters, + func(ctx context.Context) (any, error) { + return obj.CredentialParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAuthCredentialInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_credentialParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_credentialParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderCredentialsProfile", Field: field, @@ -12301,37 +14097,24 @@ func (ec *executionContext) fieldContext_AuthProviderCredentialsProfile_credenti } func (ec *executionContext) _AuthProviderInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12345,37 +14128,24 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_id(ctx context.Context } func (ec *executionContext) _AuthProviderInfo_label(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_label, + func(ctx context.Context) (any, error) { + return obj.Label, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12389,34 +14159,24 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_label(ctx context.Cont } func (ec *executionContext) _AuthProviderInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12430,34 +14190,24 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_icon(ctx context.Conte } func (ec *executionContext) _AuthProviderInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12471,37 +14221,86 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_description(ctx contex } func (ec *executionContext) _AuthProviderInfo_defaultProvider(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_defaultProvider(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultProvider, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_defaultProvider, + func(ctx context.Context) (any, error) { + return obj.DefaultProvider, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderInfo_defaultProvider(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AuthProviderInfo_trusted(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_trusted, + func(ctx context.Context) (any, error) { + return obj.Trusted, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderInfo_trusted(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AuthProviderInfo_private(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_private, + func(ctx context.Context) (any, error) { + return obj.Private, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_defaultProvider(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_private(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12514,38 +14313,134 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_defaultProvider(ctx co return fc, nil } -func (ec *executionContext) _AuthProviderInfo_configurable(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_configurable(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _AuthProviderInfo_authHidden(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_authHidden, + func(ctx context.Context) (any, error) { + return obj.AuthHidden, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.2.4") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderInfo_authHidden(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Configurable, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AuthProviderInfo_supportProvisioning(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_supportProvisioning, + func(ctx context.Context) (any, error) { + return obj.SupportProvisioning, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderInfo_supportProvisioning(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _AuthProviderInfo_configurable(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_configurable, + func(ctx context.Context) (any, error) { + return obj.Configurable, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderInfo_configurable(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AuthProviderInfo_federated(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_federated, + func(ctx context.Context) (any, error) { + return obj.Federated, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_configurable(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_federated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12559,34 +14454,97 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_configurable(ctx conte } func (ec *executionContext) _AuthProviderInfo_configurations(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_configurations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Configurations, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_configurations, + func(ctx context.Context) (any, error) { + return obj.Configurations, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfigurationᚄ, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_AuthProviderInfo_configurations(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AuthProviderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_AuthProviderConfiguration_id(ctx, field) + case "displayName": + return ec.fieldContext_AuthProviderConfiguration_displayName(ctx, field) + case "disabled": + return ec.fieldContext_AuthProviderConfiguration_disabled(ctx, field) + case "authRoleProvided": + return ec.fieldContext_AuthProviderConfiguration_authRoleProvided(ctx, field) + case "iconURL": + return ec.fieldContext_AuthProviderConfiguration_iconURL(ctx, field) + case "description": + return ec.fieldContext_AuthProviderConfiguration_description(ctx, field) + case "signInLink": + return ec.fieldContext_AuthProviderConfiguration_signInLink(ctx, field) + case "signOutLink": + return ec.fieldContext_AuthProviderConfiguration_signOutLink(ctx, field) + case "redirectLink": + return ec.fieldContext_AuthProviderConfiguration_redirectLink(ctx, field) + case "metadataLink": + return ec.fieldContext_AuthProviderConfiguration_metadataLink(ctx, field) + case "acsLink": + return ec.fieldContext_AuthProviderConfiguration_acsLink(ctx, field) + case "entityIdLink": + return ec.fieldContext_AuthProviderConfiguration_entityIdLink(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AuthProviderConfiguration", field.Name) + }, } - res := resTmp.([]*model.AuthProviderConfiguration) - fc.Result = res - return ec.marshalOAuthProviderConfiguration2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfigurationᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _AuthProviderInfo_templateConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_templateConfiguration, + func(ctx context.Context) (any, error) { + return obj.TemplateConfiguration, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.2") + if err != nil { + var zeroVal *model.AuthProviderConfiguration + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.AuthProviderConfiguration + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfiguration, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_configurations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_templateConfiguration(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12600,6 +14558,8 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_configurations(ctx con return ec.fieldContext_AuthProviderConfiguration_displayName(ctx, field) case "disabled": return ec.fieldContext_AuthProviderConfiguration_disabled(ctx, field) + case "authRoleProvided": + return ec.fieldContext_AuthProviderConfiguration_authRoleProvided(ctx, field) case "iconURL": return ec.fieldContext_AuthProviderConfiguration_iconURL(ctx, field) case "description": @@ -12608,8 +14568,14 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_configurations(ctx con return ec.fieldContext_AuthProviderConfiguration_signInLink(ctx, field) case "signOutLink": return ec.fieldContext_AuthProviderConfiguration_signOutLink(ctx, field) + case "redirectLink": + return ec.fieldContext_AuthProviderConfiguration_redirectLink(ctx, field) case "metadataLink": return ec.fieldContext_AuthProviderConfiguration_metadataLink(ctx, field) + case "acsLink": + return ec.fieldContext_AuthProviderConfiguration_acsLink(ctx, field) + case "entityIdLink": + return ec.fieldContext_AuthProviderConfiguration_entityIdLink(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type AuthProviderConfiguration", field.Name) }, @@ -12618,37 +14584,24 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_configurations(ctx con } func (ec *executionContext) _AuthProviderInfo_credentialProfiles(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_credentialProfiles(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CredentialProfiles, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AuthProviderCredentialsProfile) - fc.Result = res - return ec.marshalNAuthProviderCredentialsProfile2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfileᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_credentialProfiles, + func(ctx context.Context) (any, error) { + return obj.CredentialProfiles, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAuthProviderCredentialsProfile2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfileᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_credentialProfiles(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_credentialProfiles(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12672,37 +14625,24 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_credentialProfiles(ctx } func (ec *executionContext) _AuthProviderInfo_requiredFeatures(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_AuthProviderInfo_requiredFeatures(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RequiredFeatures, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_requiredFeatures, + func(ctx context.Context) (any, error) { + return obj.RequiredFeatures, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_AuthProviderInfo_requiredFeatures(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_requiredFeatures(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "AuthProviderInfo", Field: field, @@ -12715,81 +14655,74 @@ func (ec *executionContext) fieldContext_AuthProviderInfo_requiredFeatures(ctx c return fc, nil } -func (ec *executionContext) _ConnectionFolderInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionFolderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionFolderInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _AuthProviderInfo_required(ctx context.Context, field graphql.CollectedField, obj *model.AuthProviderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_AuthProviderInfo_required, + func(ctx context.Context) (any, error) { + return obj.Required, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionFolderInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_AuthProviderInfo_required(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ConnectionFolderInfo", + Object: "AuthProviderInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionFolderInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionFolderInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionFolderInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _Condition_expression(ctx context.Context, field graphql.CollectedField, obj *model.Condition) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Condition_expression, + func(ctx context.Context) (any, error) { + return obj.Expression, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.1") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionFolderInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Condition_expression(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ConnectionFolderInfo", + Object: "Condition", Field: field, IsMethod: false, IsResolver: false, @@ -12800,40 +14733,86 @@ func (ec *executionContext) fieldContext_ConnectionFolderInfo_description(ctx co return fc, nil } -func (ec *executionContext) _ConnectionInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _Condition_conditionType(ctx context.Context, field graphql.CollectedField, obj *model.Condition) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Condition_conditionType, + func(ctx context.Context) (any, error) { + return obj.ConditionType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.1") + if err != nil { + var zeroVal model.ConditionType + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal model.ConditionType + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.1") + if err != nil { + var zeroVal model.ConditionType + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal model.ConditionType + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNConditionType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConditionType, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Condition_conditionType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ConnectionInfo", + Object: "Condition", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ConditionType does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ConnectionFolderInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionFolderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionFolderInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ConnectionFolderInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionFolderInfo", Field: field, IsMethod: false, IsResolver: false, @@ -12844,38 +14823,118 @@ func (ec *executionContext) fieldContext_ConnectionInfo_id(ctx context.Context, return fc, nil } -func (ec *executionContext) _ConnectionInfo_driverId(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_driverId(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _ConnectionFolderInfo_projectId(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionFolderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionFolderInfo_projectId, + func(ctx context.Context) (any, error) { + return obj.ProjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ConnectionFolderInfo_projectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionFolderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _ConnectionFolderInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionFolderInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionFolderInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ConnectionFolderInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionFolderInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_driverId(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_driverId, + func(ctx context.Context) (any, error) { + return obj.DriverID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_driverId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_driverId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -12889,37 +14948,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_driverId(ctx context.Con } func (ec *executionContext) _ConnectionInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -12933,34 +14979,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_name(ctx context.Context } func (ec *executionContext) _ConnectionInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -12974,34 +15010,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_description(ctx context. } func (ec *executionContext) _ConnectionInfo_host(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_host(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Host, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_host, + func(ctx context.Context) (any, error) { + return obj.Host, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_host(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_host(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13015,34 +15041,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_host(ctx context.Context } func (ec *executionContext) _ConnectionInfo_port(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_port(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Port, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_port, + func(ctx context.Context) (any, error) { + return obj.Port, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_port(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_port(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13056,34 +15072,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_port(ctx context.Context } func (ec *executionContext) _ConnectionInfo_serverName(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_serverName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_serverName, + func(ctx context.Context) (any, error) { + return obj.ServerName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_serverName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_serverName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13097,34 +15103,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_serverName(ctx context.C } func (ec *executionContext) _ConnectionInfo_databaseName(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DatabaseName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_databaseName, + func(ctx context.Context) (any, error) { + return obj.DatabaseName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_databaseName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_databaseName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13138,34 +15134,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_databaseName(ctx context } func (ec *executionContext) _ConnectionInfo_url(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_url(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.URL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_url, + func(ctx context.Context) (any, error) { + return obj.URL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_url(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_url(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13178,35 +15164,41 @@ func (ec *executionContext) fieldContext_ConnectionInfo_url(ctx context.Context, return fc, nil } -func (ec *executionContext) _ConnectionInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_mainPropertyValues(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_mainPropertyValues, + func(ctx context.Context) (any, error) { + return obj.MainPropertyValues, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.2") + if err != nil { + var zeroVal any + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal any + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_mainPropertyValues(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13219,126 +15211,103 @@ func (ec *executionContext) fieldContext_ConnectionInfo_properties(ctx context.C return fc, nil } -func (ec *executionContext) _ConnectionInfo_template(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_template(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Template, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_expertSettingsValues(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_expertSettingsValues, + func(ctx context.Context) (any, error) { + return obj.ExpertSettingsValues, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.2.1") + if err != nil { + var zeroVal any + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal any + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_template(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_expertSettingsValues(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type Object does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_connected(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_connected(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Connected, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_keepAliveInterval(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_keepAliveInterval, + func(ctx context.Context) (any, error) { + return obj.KeepAliveInterval, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_connected(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_keepAliveInterval(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_provided(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_provided(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Provided, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_autocommit(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_autocommit, + func(ctx context.Context) (any, error) { + return obj.Autocommit, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_provided(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_autocommit(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13351,38 +15320,56 @@ func (ec *executionContext) fieldContext_ConnectionInfo_provided(ctx context.Con return fc, nil } -func (ec *executionContext) _ConnectionInfo_readOnly(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReadOnly, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null +func (ec *executionContext) _ConnectionInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_ConnectionInfo_readOnly(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _ConnectionInfo_connected(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_connected, + func(ctx context.Context) (any, error) { + return obj.Connected, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_connected(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13395,38 +15382,25 @@ func (ec *executionContext) fieldContext_ConnectionInfo_readOnly(ctx context.Con return fc, nil } -func (ec *executionContext) _ConnectionInfo_useUrl(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UseURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_provided(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_provided, + func(ctx context.Context) (any, error) { + return obj.Provided, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_useUrl(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_provided(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13439,38 +15413,25 @@ func (ec *executionContext) fieldContext_ConnectionInfo_useUrl(ctx context.Conte return fc, nil } -func (ec *executionContext) _ConnectionInfo_saveCredentials(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SaveCredentials, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_readOnly(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_readOnly, + func(ctx context.Context) (any, error) { + return obj.ReadOnly, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_saveCredentials(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_readOnly(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13483,158 +15444,134 @@ func (ec *executionContext) fieldContext_ConnectionInfo_saveCredentials(ctx cont return fc, nil } -func (ec *executionContext) _ConnectionInfo_folder(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_folder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Folder, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_useUrl(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_useUrl, + func(ctx context.Context) (any, error) { + return obj.UseURL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_folder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_useUrl(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_nodePath(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodePath, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_saveCredentials(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_saveCredentials, + func(ctx context.Context) (any, error) { + return obj.SaveCredentials, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_nodePath(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_saveCredentials(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_connectTime(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_sharedCredentials(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_sharedCredentials, + func(ctx context.Context) (any, error) { + return obj.SharedCredentials, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_connectTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_sharedCredentials(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_connectionError(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectionError, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ServerError) - fc.Result = res - return ec.marshalOServerError2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_sharedSecrets(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_sharedSecrets, + func(ctx context.Context) (any, error) { + return obj.SharedSecrets, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.5") + if err != nil { + var zeroVal []*model.SecretInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.SecretInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNSecretInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSecretInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_connectionError(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_sharedSecrets(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13642,236 +15579,341 @@ func (ec *executionContext) fieldContext_ConnectionInfo_connectionError(ctx cont IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "message": - return ec.fieldContext_ServerError_message(ctx, field) - case "errorCode": - return ec.fieldContext_ServerError_errorCode(ctx, field) - case "errorType": - return ec.fieldContext_ServerError_errorType(ctx, field) - case "stackTrace": - return ec.fieldContext_ServerError_stackTrace(ctx, field) - case "causedBy": - return ec.fieldContext_ServerError_causedBy(ctx, field) + case "displayName": + return ec.fieldContext_SecretInfo_displayName(ctx, field) + case "secretId": + return ec.fieldContext_SecretInfo_secretId(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ServerError", field.Name) + return nil, fmt.Errorf("no field named %q was found under type SecretInfo", field.Name) }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_serverVersion(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_credentialsSaved(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_credentialsSaved, + func(ctx context.Context) (any, error) { + return obj.CredentialsSaved, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_serverVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_credentialsSaved(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_clientVersion(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ClientVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_authNeeded(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_authNeeded, + func(ctx context.Context) (any, error) { + return obj.AuthNeeded, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_clientVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_authNeeded(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_origin(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_origin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Origin, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ObjectOrigin) - fc.Result = res - return ec.marshalNObjectOrigin2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_folder(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_folder, + func(ctx context.Context) (any, error) { + return obj.Folder, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_origin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_folder(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "type": - return ec.fieldContext_ObjectOrigin_type(ctx, field) - case "subType": - return ec.fieldContext_ObjectOrigin_subType(ctx, field) - case "displayName": - return ec.fieldContext_ObjectOrigin_displayName(ctx, field) - case "icon": - return ec.fieldContext_ObjectOrigin_icon(ctx, field) - case "configuration": - return ec.fieldContext_ObjectOrigin_configuration(ctx, field) - case "details": - return ec.fieldContext_ObjectOrigin_details(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ObjectOrigin", field.Name) + return nil, errors.New("field of type ID does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_authNeeded(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthNeeded, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _ConnectionInfo_nodePath(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_nodePath, + func(ctx context.Context) (any, error) { + return obj.NodePath, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_nodePath(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_connectTime(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_connectTime, + func(ctx context.Context) (any, error) { + return obj.ConnectTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_connectTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_connectionError(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_connectionError, + func(ctx context.Context) (any, error) { + return obj.ConnectionError, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_authNeeded(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_connectionError(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + switch field.Name { + case "message": + return ec.fieldContext_ServerError_message(ctx, field) + case "errorCode": + return ec.fieldContext_ServerError_errorCode(ctx, field) + case "errorType": + return ec.fieldContext_ServerError_errorType(ctx, field) + case "stackTrace": + return ec.fieldContext_ServerError_stackTrace(ctx, field) + case "causedBy": + return ec.fieldContext_ServerError_causedBy(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ServerError", field.Name) }, } return fc, nil } -func (ec *executionContext) _ConnectionInfo_authModel(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_authModel(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _ConnectionInfo_serverVersion(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_serverVersion, + func(ctx context.Context) (any, error) { + return obj.ServerVersion, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_serverVersion(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthModel, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_clientVersion(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_clientVersion, + func(ctx context.Context) (any, error) { + return obj.ClientVersion, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_clientVersion(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_origin(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_origin, + func(ctx context.Context) (any, error) { + return obj.Origin, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_origin(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "type": + return ec.fieldContext_ObjectOrigin_type(ctx, field) + case "subType": + return ec.fieldContext_ObjectOrigin_subType(ctx, field) + case "displayName": + return ec.fieldContext_ObjectOrigin_displayName(ctx, field) + case "icon": + return ec.fieldContext_ObjectOrigin_icon(ctx, field) + case "configuration": + return ec.fieldContext_ObjectOrigin_configuration(ctx, field) + case "details": + return ec.fieldContext_ObjectOrigin_details(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ObjectOrigin", field.Name) + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_authModel(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_authModel, + func(ctx context.Context) (any, error) { + return obj.AuthModel, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_authModel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_authModel(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13885,37 +15927,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_authModel(ctx context.Co } func (ec *executionContext) _ConnectionInfo_authProperties(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_authProperties, + func(ctx context.Context) (any, error) { + return obj.AuthProperties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_authProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_authProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13929,6 +15958,8 @@ func (ec *executionContext) fieldContext_ConnectionInfo_authProperties(ctx conte return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -13945,6 +15976,14 @@ func (ec *executionContext) fieldContext_ConnectionInfo_authProperties(ctx conte return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -13953,37 +15992,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_authProperties(ctx conte } func (ec *executionContext) _ConnectionInfo_providerProperties(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_providerProperties, + func(ctx context.Context) (any, error) { + return obj.ProviderProperties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_providerProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_providerProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -13997,37 +16023,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_providerProperties(ctx c } func (ec *executionContext) _ConnectionInfo_networkHandlersConfig(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NetworkHandlersConfig, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NetworkHandlerConfig) - fc.Result = res - return ec.marshalNNetworkHandlerConfig2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_networkHandlersConfig, + func(ctx context.Context) (any, error) { + return obj.NetworkHandlersConfig, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNNetworkHandlerConfig2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_networkHandlersConfig(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_networkHandlersConfig(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -14051,6 +16064,8 @@ func (ec *executionContext) fieldContext_ConnectionInfo_networkHandlersConfig(ct return ec.fieldContext_NetworkHandlerConfig_savePassword(ctx, field) case "properties": return ec.fieldContext_NetworkHandlerConfig_properties(ctx, field) + case "secureProperties": + return ec.fieldContext_NetworkHandlerConfig_secureProperties(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type NetworkHandlerConfig", field.Name) }, @@ -14059,37 +16074,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_networkHandlersConfig(ct } func (ec *executionContext) _ConnectionInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_features, + func(ctx context.Context) (any, error) { + return obj.Features, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_features(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -14103,37 +16105,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_features(ctx context.Con } func (ec *executionContext) _ConnectionInfo_navigatorSettings(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NavigatorSettings, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorSettings) - fc.Result = res - return ec.marshalNNavigatorSettings2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettings(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_navigatorSettings, + func(ctx context.Context) (any, error) { + return obj.NavigatorSettings, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNNavigatorSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettings, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_navigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_navigatorSettings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -14163,37 +16152,24 @@ func (ec *executionContext) fieldContext_ConnectionInfo_navigatorSettings(ctx co } func (ec *executionContext) _ConnectionInfo_supportedDataFormats(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportedDataFormats, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]model.ResultDataFormat) - fc.Result = res - return ec.marshalNResultDataFormat2ᚕdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormatᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_supportedDataFormats, + func(ctx context.Context) (any, error) { + return obj.SupportedDataFormats, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNResultDataFormat2ᚕgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormatᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ConnectionInfo_supportedDataFormats(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_supportedDataFormats(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ConnectionInfo", Field: field, @@ -14206,204 +16182,182 @@ func (ec *executionContext) fieldContext_ConnectionInfo_supportedDataFormats(ctx return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_configurationType(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_configurationType, + func(ctx context.Context) (any, error) { + return obj.ConfigurationType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalODriverConfigurationType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType, + true, + false, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_configurationType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type DriverConfigurationType does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_canViewSettings(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_canViewSettings, + func(ctx context.Context) (any, error) { + return obj.CanViewSettings, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_canViewSettings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_canEdit(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_canEdit, + func(ctx context.Context) (any, error) { + return obj.CanEdit, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_canEdit(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_fileExtension(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_fileExtension(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FileExtension, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_canDelete(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_canDelete, + func(ctx context.Context) (any, error) { + return obj.CanDelete, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_fileExtension(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_canDelete(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_appFileExtension(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_appFileExtension(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AppFileExtension, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null +func (ec *executionContext) _ConnectionInfo_projectId(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_projectId, + func(ctx context.Context) (any, error) { + return obj.ProjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ConnectionInfo_projectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ConnectionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _ConnectionInfo_requiredAuth(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_requiredAuth, + func(ctx context.Context) (any, error) { + return obj.RequiredAuth, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appFileExtension(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_requiredAuth(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, @@ -14414,37 +16368,43 @@ func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appFileExtens return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_appName(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_appName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AppName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_defaultCatalogName(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_defaultCatalogName, + func(ctx context.Context) (any, error) { + return obj.DefaultCatalogName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.5") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_defaultCatalogName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, @@ -14455,81 +16415,90 @@ func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appName(ctx c return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_order(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_order(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Order, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_defaultSchemaName(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_defaultSchemaName, + func(ctx context.Context) (any, error) { + return obj.DefaultSchemaName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.5") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_order(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_defaultSchemaName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ConnectionInfo_tools(ctx context.Context, field graphql.CollectedField, obj *model.ConnectionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ConnectionInfo_tools, + func(ctx context.Context) (any, error) { + return obj.Tools, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.3") + if err != nil { + var zeroVal []string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ConnectionInfo_tools(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "ConnectionInfo", Field: field, IsMethod: false, IsResolver: false, @@ -14540,102 +16509,192 @@ func (ec *executionContext) fieldContext_DataTransferProcessorInfo_icon(ctx cont return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, field.Selections, res) +func (ec *executionContext) _DataTransferDefaultExportSettings_outputSettings(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferDefaultExportSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferDefaultExportSettings_outputSettings, + func(ctx context.Context) (any, error) { + return obj.OutputSettings, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDataTransferOutputSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferOutputSettings, + true, + true, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DataTransferDefaultExportSettings_outputSettings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "DataTransferDefaultExportSettings", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "id": - return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - case "displayName": - return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - case "description": - return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - case "category": - return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - case "dataType": - return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - case "value": - return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - case "validValues": - return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - case "defaultValue": - return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - case "length": - return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - case "features": - return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - case "order": - return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "insertBom": + return ec.fieldContext_DataTransferOutputSettings_insertBom(ctx, field) + case "encoding": + return ec.fieldContext_DataTransferOutputSettings_encoding(ctx, field) + case "timestampPattern": + return ec.fieldContext_DataTransferOutputSettings_timestampPattern(ctx, field) + case "compress": + return ec.fieldContext_DataTransferOutputSettings_compress(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type DataTransferOutputSettings", field.Name) }, } return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_isBinary(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_isBinary(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsBinary, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _DataTransferDefaultExportSettings_supportedEncodings(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferDefaultExportSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferDefaultExportSettings_supportedEncodings, + func(ctx context.Context) (any, error) { + return obj.SupportedEncodings, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DataTransferDefaultExportSettings_supportedEncodings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferDefaultExportSettings", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DataTransferOutputSettings_insertBom(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferOutputSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferOutputSettings_insertBom, + func(ctx context.Context) (any, error) { + return obj.InsertBom, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DataTransferOutputSettings_insertBom(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferOutputSettings", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DataTransferOutputSettings_encoding(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferOutputSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferOutputSettings_encoding, + func(ctx context.Context) (any, error) { + return obj.Encoding, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_isBinary(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DataTransferOutputSettings_encoding(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTransferProcessorInfo", + Object: "DataTransferOutputSettings", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _DataTransferOutputSettings_timestampPattern(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferOutputSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferOutputSettings_timestampPattern, + func(ctx context.Context) (any, error) { + return obj.TimestampPattern, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DataTransferOutputSettings_timestampPattern(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferOutputSettings", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _DataTransferOutputSettings_compress(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferOutputSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferOutputSettings_compress, + func(ctx context.Context) (any, error) { + return obj.Compress, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DataTransferOutputSettings_compress(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferOutputSettings", Field: field, IsMethod: false, IsResolver: false, @@ -14646,123 +16705,431 @@ func (ec *executionContext) fieldContext_DataTransferProcessorInfo_isBinary(ctx return fc, nil } -func (ec *executionContext) _DataTransferProcessorInfo_isHTML(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTransferProcessorInfo_isHTML(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _DataTransferProcessorInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsHTML, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DataTransferProcessorInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DataTransferProcessorInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DataTransferProcessorInfo_fileExtension(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_fileExtension, + func(ctx context.Context) (any, error) { + return obj.FileExtension, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DataTransferProcessorInfo_isHTML(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_fileExtension(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DataTransferProcessorInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DataTypeLogicalOperation_id(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTypeLogicalOperation_id(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _DataTransferProcessorInfo_appFileExtension(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_appFileExtension, + func(ctx context.Context) (any, error) { + return obj.AppFileExtension, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appFileExtension(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DataTransferProcessorInfo_appName(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_appName, + func(ctx context.Context) (any, error) { + return obj.AppName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_appName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DataTransferProcessorInfo_order(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_order, + func(ctx context.Context) (any, error) { + return obj.Order, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_order(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_DataTypeLogicalOperation_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _DataTransferProcessorInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DataTypeLogicalOperation", + Object: "DataTransferProcessorInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DataTypeLogicalOperation_expression(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTypeLogicalOperation_expression(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _DataTransferProcessorInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) + case "displayName": + return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) + case "description": + return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) + case "category": + return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) + case "dataType": + return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) + case "value": + return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) + case "validValues": + return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) + case "defaultValue": + return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) + case "length": + return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) + case "features": + return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) + case "order": + return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Expression, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DataTransferProcessorInfo_isBinary(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_isBinary, + func(ctx context.Context) (any, error) { + return obj.IsBinary, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_isBinary(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DataTransferProcessorInfo_isHTML(ctx context.Context, field graphql.CollectedField, obj *model.DataTransferProcessorInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTransferProcessorInfo_isHTML, + func(ctx context.Context) (any, error) { + return obj.IsHTML, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DataTransferProcessorInfo_isHTML(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTransferProcessorInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _DataTypeLogicalOperation_id(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTypeLogicalOperation_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DataTypeLogicalOperation_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DataTypeLogicalOperation", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DataTypeLogicalOperation_expression(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTypeLogicalOperation_expression, + func(ctx context.Context) (any, error) { + return obj.Expression, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DataTypeLogicalOperation_expression(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DataTypeLogicalOperation_expression(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DataTypeLogicalOperation", Field: field, @@ -14776,34 +17143,24 @@ func (ec *executionContext) fieldContext_DataTypeLogicalOperation_expression(ctx } func (ec *executionContext) _DataTypeLogicalOperation_argumentCount(ctx context.Context, field graphql.CollectedField, obj *model.DataTypeLogicalOperation) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DataTypeLogicalOperation_argumentCount(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ArgumentCount, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DataTypeLogicalOperation_argumentCount, + func(ctx context.Context) (any, error) { + return obj.ArgumentCount, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_DataTypeLogicalOperation_argumentCount(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DataTypeLogicalOperation_argumentCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DataTypeLogicalOperation", Field: field, @@ -14817,37 +17174,24 @@ func (ec *executionContext) fieldContext_DataTypeLogicalOperation_argumentCount( } func (ec *executionContext) _DatabaseAuthModel_id(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseAuthModel_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseAuthModel_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseAuthModel_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseAuthModel", Field: field, @@ -14861,37 +17205,24 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_id(ctx context.Contex } func (ec *executionContext) _DatabaseAuthModel_displayName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseAuthModel_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseAuthModel_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseAuthModel_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseAuthModel", Field: field, @@ -14905,34 +17236,24 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_displayName(ctx conte } func (ec *executionContext) _DatabaseAuthModel_description(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseAuthModel_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseAuthModel_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseAuthModel_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseAuthModel", Field: field, @@ -14946,34 +17267,24 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_description(ctx conte } func (ec *executionContext) _DatabaseAuthModel_icon(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseAuthModel_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseAuthModel_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseAuthModel_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseAuthModel", Field: field, @@ -14987,34 +17298,24 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_icon(ctx context.Cont } func (ec *executionContext) _DatabaseAuthModel_requiresLocalConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_requiresLocalConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RequiresLocalConfiguration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseAuthModel_requiresLocalConfiguration, + func(ctx context.Context) (any, error) { + return obj.RequiresLocalConfiguration, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseAuthModel_requiresLocalConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseAuthModel_requiresLocalConfiguration(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseAuthModel", Field: field, @@ -15027,38 +17328,56 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_requiresLocalConfigur return fc, nil } -func (ec *executionContext) _DatabaseAuthModel_properties(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseAuthModel_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null +func (ec *executionContext) _DatabaseAuthModel_requiredAuth(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseAuthModel_requiredAuth, + func(ctx context.Context) (any, error) { + return obj.RequiredAuth, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DatabaseAuthModel_requiredAuth(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DatabaseAuthModel", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DatabaseAuthModel_properties(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseAuthModel) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseAuthModel_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseAuthModel_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseAuthModel_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseAuthModel", Field: field, @@ -15072,6 +17391,8 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_properties(ctx contex return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -15088,6 +17409,14 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_properties(ctx contex return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -15096,37 +17425,24 @@ func (ec *executionContext) fieldContext_DatabaseAuthModel_properties(ctx contex } func (ec *executionContext) _DatabaseCatalog_catalog(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseCatalog) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseCatalog_catalog(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Catalog, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseCatalog_catalog, + func(ctx context.Context) (any, error) { + return obj.Catalog, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseCatalog_catalog(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseCatalog_catalog(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseCatalog", Field: field, @@ -15136,10 +17452,14 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_catalog(ctx context.Con switch field.Name { case "id": return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) case "name": return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) case "fullName": return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) case "icon": return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) case "description": @@ -15148,8 +17468,12 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_catalog(ctx context.Con return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) case "hasChildren": return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) case "object": return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) case "features": return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) case "nodeDetails": @@ -15160,6 +17484,10 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_catalog(ctx context.Con return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) case "navigable": return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) }, @@ -15168,37 +17496,24 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_catalog(ctx context.Con } func (ec *executionContext) _DatabaseCatalog_schemaList(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseCatalog) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseCatalog_schemaList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SchemaList, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseCatalog_schemaList, + func(ctx context.Context) (any, error) { + return obj.SchemaList, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseCatalog_schemaList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseCatalog_schemaList(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseCatalog", Field: field, @@ -15208,10 +17523,14 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_schemaList(ctx context. switch field.Name { case "id": return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) case "name": return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) case "fullName": return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) case "icon": return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) case "description": @@ -15220,8 +17539,12 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_schemaList(ctx context. return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) case "hasChildren": return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) case "object": return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) case "features": return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) case "nodeDetails": @@ -15232,6 +17555,10 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_schemaList(ctx context. return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) case "navigable": return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) }, @@ -15240,34 +17567,24 @@ func (ec *executionContext) fieldContext_DatabaseCatalog_schemaList(ctx context. } func (ec *executionContext) _DatabaseDocument_id(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseDocument_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseDocument_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseDocument_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseDocument", Field: field, @@ -15281,34 +17598,24 @@ func (ec *executionContext) fieldContext_DatabaseDocument_id(ctx context.Context } func (ec *executionContext) _DatabaseDocument_contentType(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_contentType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ContentType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseDocument_contentType, + func(ctx context.Context) (any, error) { + return obj.ContentType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseDocument_contentType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseDocument_contentType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseDocument", Field: field, @@ -15322,34 +17629,24 @@ func (ec *executionContext) fieldContext_DatabaseDocument_contentType(ctx contex } func (ec *executionContext) _DatabaseDocument_properties(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseDocument_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseDocument_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseDocument_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseDocument", Field: field, @@ -15363,34 +17660,24 @@ func (ec *executionContext) fieldContext_DatabaseDocument_properties(ctx context } func (ec *executionContext) _DatabaseDocument_data(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseDocument) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseDocument_data(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Data, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseDocument_data, + func(ctx context.Context) (any, error) { + return obj.Data, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseDocument_data(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseDocument_data(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseDocument", Field: field, @@ -15404,34 +17691,24 @@ func (ec *executionContext) fieldContext_DatabaseDocument_data(ctx context.Conte } func (ec *executionContext) _DatabaseObjectInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15445,34 +17722,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_name(ctx context.Con } func (ec *executionContext) _DatabaseObjectInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15486,34 +17753,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_description(ctx cont } func (ec *executionContext) _DatabaseObjectInfo_type(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15527,31 +17784,21 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_type(ctx context.Con } func (ec *executionContext) _DatabaseObjectInfo_properties(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo, + true, + false, + ) } func (ec *executionContext) fieldContext_DatabaseObjectInfo_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -15568,6 +17815,8 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_properties(ctx conte return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -15584,6 +17833,14 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_properties(ctx conte return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -15597,40 +17854,30 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_properties(ctx conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_DatabaseObjectInfo_properties_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _DatabaseObjectInfo_ordinalPosition(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_ordinalPosition(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.OrdinalPosition, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_ordinalPosition, + func(ctx context.Context) (any, error) { + return obj.OrdinalPosition, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_ordinalPosition(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_ordinalPosition(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15644,34 +17891,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_ordinalPosition(ctx } func (ec *executionContext) _DatabaseObjectInfo_fullyQualifiedName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_fullyQualifiedName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullyQualifiedName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_fullyQualifiedName, + func(ctx context.Context) (any, error) { + return obj.FullyQualifiedName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_fullyQualifiedName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_fullyQualifiedName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15685,34 +17922,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_fullyQualifiedName(c } func (ec *executionContext) _DatabaseObjectInfo_overloadedName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_overloadedName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.OverloadedName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_overloadedName, + func(ctx context.Context) (any, error) { + return obj.OverloadedName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_overloadedName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_overloadedName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15726,34 +17953,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_overloadedName(ctx c } func (ec *executionContext) _DatabaseObjectInfo_uniqueName(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_uniqueName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UniqueName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_uniqueName, + func(ctx context.Context) (any, error) { + return obj.UniqueName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_uniqueName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_uniqueName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15767,34 +17984,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_uniqueName(ctx conte } func (ec *executionContext) _DatabaseObjectInfo_state(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_state(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.State, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_state, + func(ctx context.Context) (any, error) { + return obj.State, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_state(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_state(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15808,34 +18015,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_state(ctx context.Co } func (ec *executionContext) _DatabaseObjectInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_features, + func(ctx context.Context) (any, error) { + return obj.Features, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕstringᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_features(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15849,34 +18046,24 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_features(ctx context } func (ec *executionContext) _DatabaseObjectInfo_editors(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseObjectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseObjectInfo_editors(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Editors, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseObjectInfo_editors, + func(ctx context.Context) (any, error) { + return obj.Editors, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕstringᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_DatabaseObjectInfo_editors(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseObjectInfo_editors(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseObjectInfo", Field: field, @@ -15889,38 +18076,96 @@ func (ec *executionContext) fieldContext_DatabaseObjectInfo_editors(ctx context. return fc, nil } -func (ec *executionContext) _DatabaseStructContainers_catalogList(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_catalogList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CatalogList, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null +func (ec *executionContext) _DatabaseStructContainers_parentNode(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseStructContainers_parentNode, + func(ctx context.Context) (any, error) { + return obj.ParentNode, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalONavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DatabaseStructContainers_parentNode(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DatabaseStructContainers", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) + case "name": + return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) + case "fullName": + return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) + case "icon": + return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) + case "description": + return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) + case "nodeType": + return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) + case "hasChildren": + return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) + case "object": + return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) + case "features": + return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) + case "nodeDetails": + return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) + case "folder": + return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) + case "inline": + return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) + case "navigable": + return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) + }, } - res := resTmp.([]*model.DatabaseCatalog) - fc.Result = res - return ec.marshalNDatabaseCatalog2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalogᚄ(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_DatabaseStructContainers_catalogList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _DatabaseStructContainers_catalogList(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseStructContainers_catalogList, + func(ctx context.Context) (any, error) { + return obj.CatalogList, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDatabaseCatalog2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalogᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DatabaseStructContainers_catalogList(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseStructContainers", Field: field, @@ -15940,37 +18185,24 @@ func (ec *executionContext) fieldContext_DatabaseStructContainers_catalogList(ct } func (ec *executionContext) _DatabaseStructContainers_schemaList(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_schemaList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SchemaList, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseStructContainers_schemaList, + func(ctx context.Context) (any, error) { + return obj.SchemaList, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseStructContainers_schemaList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseStructContainers_schemaList(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseStructContainers", Field: field, @@ -15980,10 +18212,14 @@ func (ec *executionContext) fieldContext_DatabaseStructContainers_schemaList(ctx switch field.Name { case "id": return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) case "name": return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) case "fullName": return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) case "icon": return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) case "description": @@ -15992,8 +18228,12 @@ func (ec *executionContext) fieldContext_DatabaseStructContainers_schemaList(ctx return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) case "hasChildren": return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) case "object": return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) case "features": return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) case "nodeDetails": @@ -16004,6 +18244,10 @@ func (ec *executionContext) fieldContext_DatabaseStructContainers_schemaList(ctx return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) case "navigable": return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) }, @@ -16012,37 +18256,24 @@ func (ec *executionContext) fieldContext_DatabaseStructContainers_schemaList(ctx } func (ec *executionContext) _DatabaseStructContainers_supportsCatalogChange(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_supportsCatalogChange(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsCatalogChange, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseStructContainers_supportsCatalogChange, + func(ctx context.Context) (any, error) { + return obj.SupportsCatalogChange, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsCatalogChange(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsCatalogChange(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseStructContainers", Field: field, @@ -16056,37 +18287,24 @@ func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsCatalo } func (ec *executionContext) _DatabaseStructContainers_supportsSchemaChange(ctx context.Context, field graphql.CollectedField, obj *model.DatabaseStructContainers) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DatabaseStructContainers_supportsSchemaChange(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsSchemaChange, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DatabaseStructContainers_supportsSchemaChange, + func(ctx context.Context) (any, error) { + return obj.SupportsSchemaChange, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsSchemaChange(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsSchemaChange(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DatabaseStructContainers", Field: field, @@ -16099,40 +18317,43 @@ func (ec *executionContext) fieldContext_DatabaseStructContainers_supportsSchema return fc, nil } -func (ec *executionContext) _DriverInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _DriverFileInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DriverFileInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverFileInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.2") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverFileInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DriverInfo", + Object: "DriverFileInfo", Field: field, IsMethod: false, IsResolver: false, @@ -16143,37 +18364,43 @@ func (ec *executionContext) fieldContext_DriverInfo_id(ctx context.Context, fiel return fc, nil } -func (ec *executionContext) _DriverInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverFileInfo_fileName(ctx context.Context, field graphql.CollectedField, obj *model.DriverFileInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverFileInfo_fileName, + func(ctx context.Context) (any, error) { + return obj.FileName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.2") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverFileInfo_fileName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DriverInfo", + Object: "DriverFileInfo", Field: field, IsMethod: false, IsResolver: false, @@ -16184,37 +18411,43 @@ func (ec *executionContext) fieldContext_DriverInfo_name(ctx context.Context, fi return fc, nil } -func (ec *executionContext) _DriverInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverFileInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DriverFileInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverFileInfo_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.2") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverFileInfo_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "DriverInfo", + Object: "DriverFileInfo", Field: field, IsMethod: false, IsResolver: false, @@ -16225,76 +18458,56 @@ func (ec *executionContext) fieldContext_DriverInfo_description(ctx context.Cont return fc, nil } -func (ec *executionContext) _DriverInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type ID does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DriverInfo_iconBig(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_iconBig(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IconBig, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_iconBig(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16307,76 +18520,56 @@ func (ec *executionContext) fieldContext_DriverInfo_iconBig(ctx context.Context, return fc, nil } -func (ec *executionContext) _DriverInfo_providerId(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_providerId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_providerId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DriverInfo_driverClassName(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverClassName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverClassName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_driverClassName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16389,35 +18582,25 @@ func (ec *executionContext) fieldContext_DriverInfo_driverClassName(ctx context. return fc, nil } -func (ec *executionContext) _DriverInfo_defaultHost(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultHost(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultHost, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverInfo_iconBig(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_iconBig, + func(ctx context.Context) (any, error) { + return obj.IconBig, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_defaultHost(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_iconBig(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16430,76 +18613,87 @@ func (ec *executionContext) fieldContext_DriverInfo_defaultHost(ctx context.Cont return fc, nil } -func (ec *executionContext) _DriverInfo_defaultPort(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultPort(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultPort, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverInfo_driverId(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverId, + func(ctx context.Context) (any, error) { + return obj.DriverID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_defaultPort(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_driverId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type ID does not have child fields") }, } return fc, nil } -func (ec *executionContext) _DriverInfo_defaultDatabase(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultDatabase(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultDatabase, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null +func (ec *executionContext) _DriverInfo_providerId(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_providerId, + func(ctx context.Context) (any, error) { + return obj.ProviderID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_providerId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DriverInfo_driverClassName(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverClassName, + func(ctx context.Context) (any, error) { + return obj.DriverClassName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_defaultDatabase(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_driverClassName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16512,35 +18706,118 @@ func (ec *executionContext) fieldContext_DriverInfo_defaultDatabase(ctx context. return fc, nil } -func (ec *executionContext) _DriverInfo_defaultServer(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultServer(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _DriverInfo_defaultHost(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_defaultHost, + func(ctx context.Context) (any, error) { + return obj.DefaultHost, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_defaultHost(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultServer, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DriverInfo_defaultPort(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_defaultPort, + func(ctx context.Context) (any, error) { + return obj.DefaultPort, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_defaultPort(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DriverInfo_defaultDatabase(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_defaultDatabase, + func(ctx context.Context) (any, error) { + return obj.DefaultDatabase, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_defaultDatabase(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DriverInfo_defaultServer(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_defaultServer, + func(ctx context.Context) (any, error) { + return obj.DefaultServer, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_defaultServer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_defaultServer(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16554,34 +18831,24 @@ func (ec *executionContext) fieldContext_DriverInfo_defaultServer(ctx context.Co } func (ec *executionContext) _DriverInfo_defaultUser(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultUser, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_defaultUser, + func(ctx context.Context) (any, error) { + return obj.DefaultUser, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_defaultUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_defaultUser(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16595,34 +18862,24 @@ func (ec *executionContext) fieldContext_DriverInfo_defaultUser(ctx context.Cont } func (ec *executionContext) _DriverInfo_sampleURL(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_sampleURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SampleURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_sampleURL, + func(ctx context.Context) (any, error) { + return obj.SampleURL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_sampleURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_sampleURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16636,34 +18893,24 @@ func (ec *executionContext) fieldContext_DriverInfo_sampleURL(ctx context.Contex } func (ec *executionContext) _DriverInfo_driverInfoURL(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverInfoURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverInfoURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverInfoURL, + func(ctx context.Context) (any, error) { + return obj.DriverInfoURL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_driverInfoURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_driverInfoURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16677,34 +18924,24 @@ func (ec *executionContext) fieldContext_DriverInfo_driverInfoURL(ctx context.Co } func (ec *executionContext) _DriverInfo_driverPropertiesURL(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverPropertiesURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverPropertiesURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverPropertiesURL, + func(ctx context.Context) (any, error) { + return obj.DriverPropertiesURL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_driverPropertiesURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_driverPropertiesURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16718,34 +18955,24 @@ func (ec *executionContext) fieldContext_DriverInfo_driverPropertiesURL(ctx cont } func (ec *executionContext) _DriverInfo_embedded(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_embedded(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Embedded, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_embedded, + func(ctx context.Context) (any, error) { + return obj.Embedded, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_embedded(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_embedded(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16759,37 +18986,24 @@ func (ec *executionContext) fieldContext_DriverInfo_embedded(ctx context.Context } func (ec *executionContext) _DriverInfo_enabled(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_enabled, + func(ctx context.Context) (any, error) { + return obj.Enabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_enabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16803,34 +19017,24 @@ func (ec *executionContext) fieldContext_DriverInfo_enabled(ctx context.Context, } func (ec *executionContext) _DriverInfo_requiresServerName(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_requiresServerName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RequiresServerName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_requiresServerName, + func(ctx context.Context) (any, error) { + return obj.RequiresServerName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_requiresServerName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_requiresServerName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16843,35 +19047,72 @@ func (ec *executionContext) fieldContext_DriverInfo_requiresServerName(ctx conte return fc, nil } -func (ec *executionContext) _DriverInfo_allowsEmptyPassword(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_allowsEmptyPassword(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AllowsEmptyPassword, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null +func (ec *executionContext) _DriverInfo_requiresDatabaseName(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_requiresDatabaseName, + func(ctx context.Context) (any, error) { + return obj.RequiresDatabaseName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_requiresDatabaseName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DriverInfo_useCustomPage(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_useCustomPage, + func(ctx context.Context) (any, error) { + return obj.UseCustomPage, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.2") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_allowsEmptyPassword(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_useCustomPage(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16885,34 +19126,24 @@ func (ec *executionContext) fieldContext_DriverInfo_allowsEmptyPassword(ctx cont } func (ec *executionContext) _DriverInfo_licenseRequired(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_licenseRequired(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseRequired, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_licenseRequired, + func(ctx context.Context) (any, error) { + return obj.LicenseRequired, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_licenseRequired(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_licenseRequired(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16926,34 +19157,24 @@ func (ec *executionContext) fieldContext_DriverInfo_licenseRequired(ctx context. } func (ec *executionContext) _DriverInfo_license(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_license(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.License, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_license, + func(ctx context.Context) (any, error) { + return obj.License, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_license(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_license(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -16967,34 +19188,24 @@ func (ec *executionContext) fieldContext_DriverInfo_license(ctx context.Context, } func (ec *executionContext) _DriverInfo_custom(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_custom(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Custom, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_custom, + func(ctx context.Context) (any, error) { + return obj.Custom, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_custom(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_custom(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17008,34 +19219,24 @@ func (ec *executionContext) fieldContext_DriverInfo_custom(ctx context.Context, } func (ec *executionContext) _DriverInfo_promotedScore(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_promotedScore(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PromotedScore, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_promotedScore, + func(ctx context.Context) (any, error) { + return obj.PromotedScore, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_promotedScore(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_promotedScore(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17049,37 +19250,24 @@ func (ec *executionContext) fieldContext_DriverInfo_promotedScore(ctx context.Co } func (ec *executionContext) _DriverInfo_driverProperties(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverProperties, + func(ctx context.Context) (any, error) { + return obj.DriverProperties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_driverProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_driverProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17093,6 +19281,8 @@ func (ec *executionContext) fieldContext_DriverInfo_driverProperties(ctx context return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -17109,6 +19299,14 @@ func (ec *executionContext) fieldContext_DriverInfo_driverProperties(ctx context return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -17117,37 +19315,24 @@ func (ec *executionContext) fieldContext_DriverInfo_driverProperties(ctx context } func (ec *executionContext) _DriverInfo_driverParameters(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_driverParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DriverParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverParameters, + func(ctx context.Context) (any, error) { + return obj.DriverParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_driverParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_driverParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17160,38 +19345,187 @@ func (ec *executionContext) fieldContext_DriverInfo_driverParameters(ctx context return fc, nil } -func (ec *executionContext) _DriverInfo_providerProperties(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_providerProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProviderProperties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _DriverInfo_mainProperties(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_mainProperties, + func(ctx context.Context) (any, error) { + return obj.MainProperties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.2") + if err != nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_mainProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) + case "displayName": + return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) + case "description": + return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) + case "category": + return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) + case "dataType": + return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) + case "value": + return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) + case "validValues": + return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) + case "defaultValue": + return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) + case "length": + return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) + case "features": + return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) + case "order": + return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DriverInfo_providerProperties(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_providerProperties, + func(ctx context.Context) (any, error) { + return obj.ProviderProperties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_providerProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) + case "displayName": + return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) + case "description": + return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) + case "category": + return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) + case "dataType": + return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) + case "value": + return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) + case "validValues": + return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) + case "defaultValue": + return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) + case "length": + return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) + case "features": + return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) + case "order": + return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) + }, } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DriverInfo_expertSettingsProperties(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_expertSettingsProperties, + func(ctx context.Context) (any, error) { + return obj.ExpertSettingsProperties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.2.1") + if err != nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_providerProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_expertSettingsProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17205,6 +19539,8 @@ func (ec *executionContext) fieldContext_DriverInfo_providerProperties(ctx conte return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -17221,6 +19557,14 @@ func (ec *executionContext) fieldContext_DriverInfo_providerProperties(ctx conte return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -17229,34 +19573,24 @@ func (ec *executionContext) fieldContext_DriverInfo_providerProperties(ctx conte } func (ec *executionContext) _DriverInfo_anonymousAccess(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_anonymousAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AnonymousAccess, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_anonymousAccess, + func(ctx context.Context) (any, error) { + return obj.AnonymousAccess, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_DriverInfo_anonymousAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_anonymousAccess(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17270,37 +19604,24 @@ func (ec *executionContext) fieldContext_DriverInfo_anonymousAccess(ctx context. } func (ec *executionContext) _DriverInfo_defaultAuthModel(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_defaultAuthModel(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultAuthModel, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_defaultAuthModel, + func(ctx context.Context) (any, error) { + return obj.DefaultAuthModel, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_defaultAuthModel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_defaultAuthModel(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17314,37 +19635,24 @@ func (ec *executionContext) fieldContext_DriverInfo_defaultAuthModel(ctx context } func (ec *executionContext) _DriverInfo_applicableAuthModels(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_applicableAuthModels(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ApplicableAuthModels, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_applicableAuthModels, + func(ctx context.Context) (any, error) { + return obj.ApplicableAuthModels, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_applicableAuthModels(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_applicableAuthModels(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17358,37 +19666,24 @@ func (ec *executionContext) fieldContext_DriverInfo_applicableAuthModels(ctx con } func (ec *executionContext) _DriverInfo_applicableNetworkHandlers(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_DriverInfo_applicableNetworkHandlers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ApplicableNetworkHandlers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNID2ᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_applicableNetworkHandlers, + func(ctx context.Context) (any, error) { + return obj.ApplicableNetworkHandlers, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_DriverInfo_applicableNetworkHandlers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_applicableNetworkHandlers(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "DriverInfo", Field: field, @@ -17401,81 +19696,255 @@ func (ec *executionContext) fieldContext_DriverInfo_applicableNetworkHandlers(ct return fc, nil } -func (ec *executionContext) _LogEntry_time(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_time(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Time, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _DriverInfo_configurationTypes(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_configurationTypes, + func(ctx context.Context) (any, error) { + return obj.ConfigurationTypes, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDriverConfigurationType2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_configurationTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type DriverConfigurationType does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DriverInfo_downloadable(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_downloadable, + func(ctx context.Context) (any, error) { + return obj.Downloadable, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.3") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_downloadable(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(*time.Time) - fc.Result = res - return ec.marshalODateTime2ᚖtimeᚐTime(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DriverInfo_driverInstalled(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverInstalled, + func(ctx context.Context) (any, error) { + return obj.DriverInstalled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_LogEntry_time(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverInfo_driverInstalled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "LogEntry", + Object: "DriverInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type DateTime does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _LogEntry_type(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_type(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _DriverInfo_driverLibraries(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_driverLibraries, + func(ctx context.Context) (any, error) { + return obj.DriverLibraries, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDriverLibraryInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverLibraryInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_driverLibraries(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_DriverLibraryInfo_id(ctx, field) + case "name": + return ec.fieldContext_DriverLibraryInfo_name(ctx, field) + case "icon": + return ec.fieldContext_DriverLibraryInfo_icon(ctx, field) + case "libraryFiles": + return ec.fieldContext_DriverLibraryInfo_libraryFiles(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type DriverLibraryInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DriverInfo_safeEmbeddedDriver(ctx context.Context, field graphql.CollectedField, obj *model.DriverInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverInfo_safeEmbeddedDriver, + func(ctx context.Context) (any, error) { + return obj.SafeEmbeddedDriver, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.0") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverInfo_safeEmbeddedDriver(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DriverLibraryInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.DriverLibraryInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverLibraryInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DriverLibraryInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverLibraryInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DriverLibraryInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.DriverLibraryInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverLibraryInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_LogEntry_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverLibraryInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "LogEntry", + Object: "DriverLibraryInfo", Field: field, IsMethod: false, IsResolver: false, @@ -17486,37 +19955,27 @@ func (ec *executionContext) fieldContext_LogEntry_type(ctx context.Context, fiel return fc, nil } -func (ec *executionContext) _LogEntry_message(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _DriverLibraryInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.DriverLibraryInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverLibraryInfo_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_LogEntry_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DriverLibraryInfo_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "LogEntry", + Object: "DriverLibraryInfo", Field: field, IsMethod: false, IsResolver: false, @@ -17527,37 +19986,113 @@ func (ec *executionContext) fieldContext_LogEntry_message(ctx context.Context, f return fc, nil } -func (ec *executionContext) _LogEntry_stackTrace(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_LogEntry_stackTrace(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StackTrace, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _DriverLibraryInfo_libraryFiles(ctx context.Context, field graphql.CollectedField, obj *model.DriverLibraryInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DriverLibraryInfo_libraryFiles, + func(ctx context.Context) (any, error) { + return obj.LibraryFiles, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.2") + if err != nil { + var zeroVal []*model.DriverFileInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.DriverFileInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalODriverFileInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverFileInfoᚄ, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DriverLibraryInfo_libraryFiles(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DriverLibraryInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_DriverFileInfo_id(ctx, field) + case "fileName": + return ec.fieldContext_DriverFileInfo_fileName(ctx, field) + case "icon": + return ec.fieldContext_DriverFileInfo_icon(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type DriverFileInfo", field.Name) + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _DynamicTraceProperty_name(ctx context.Context, field graphql.CollectedField, obj *model.DynamicTraceProperty) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DynamicTraceProperty_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_DynamicTraceProperty_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DynamicTraceProperty", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _DynamicTraceProperty_value(ctx context.Context, field graphql.CollectedField, obj *model.DynamicTraceProperty) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DynamicTraceProperty_value, + func(ctx context.Context) (any, error) { + return obj.Value, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_LogEntry_stackTrace(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_DynamicTraceProperty_value(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "LogEntry", + Object: "DynamicTraceProperty", Field: field, IsMethod: false, IsResolver: false, @@ -17568,290 +20103,433 @@ func (ec *executionContext) fieldContext_LogEntry_stackTrace(ctx context.Context return fc, nil } -func (ec *executionContext) _Mutation_setUserConfigurationParameter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_setUserConfigurationParameter(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _DynamicTraceProperty_description(ctx context.Context, field graphql.CollectedField, obj *model.DynamicTraceProperty) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_DynamicTraceProperty_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_DynamicTraceProperty_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "DynamicTraceProperty", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SetUserConfigurationParameter(rctx, fc.Args["name"].(string), - func() interface{} { - if fc.Args["value"] == nil { - return nil + return fc, nil +} + +func (ec *executionContext) _FederatedAuthInfo_redirectLink(ctx context.Context, field graphql.CollectedField, obj *model.FederatedAuthInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_FederatedAuthInfo_redirectLink, + func(ctx context.Context) (any, error) { + return obj.RedirectLink, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal string + return zeroVal, err } - return fc.Args["value"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_setUserConfigurationParameter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_FederatedAuthInfo_redirectLink(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Mutation", + Object: "FederatedAuthInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_setUserConfigurationParameter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Mutation_openSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_openSession(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().OpenSession(rctx, fc.Args["defaultLocale"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SessionInfo) - fc.Result = res - return ec.marshalNSessionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo(ctx, field.Selections, res) +func (ec *executionContext) _FederatedAuthInfo_taskInfo(ctx context.Context, field graphql.CollectedField, obj *model.FederatedAuthInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_FederatedAuthInfo_taskInfo, + func(ctx context.Context) (any, error) { + return obj.TaskInfo, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_openSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_FederatedAuthInfo_taskInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Mutation", + Object: "FederatedAuthInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "createTime": - return ec.fieldContext_SessionInfo_createTime(ctx, field) - case "lastAccessTime": - return ec.fieldContext_SessionInfo_lastAccessTime(ctx, field) - case "locale": - return ec.fieldContext_SessionInfo_locale(ctx, field) - case "cacheExpired": - return ec.fieldContext_SessionInfo_cacheExpired(ctx, field) - case "serverMessages": - return ec.fieldContext_SessionInfo_serverMessages(ctx, field) - case "connections": - return ec.fieldContext_SessionInfo_connections(ctx, field) - case "actionParameters": - return ec.fieldContext_SessionInfo_actionParameters(ctx, field) + case "id": + return ec.fieldContext_AsyncTaskInfo_id(ctx, field) + case "name": + return ec.fieldContext_AsyncTaskInfo_name(ctx, field) + case "running": + return ec.fieldContext_AsyncTaskInfo_running(ctx, field) + case "status": + return ec.fieldContext_AsyncTaskInfo_status(ctx, field) + case "error": + return ec.fieldContext_AsyncTaskInfo_error(ctx, field) + case "taskResult": + return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type SessionInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_openSession_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Mutation_closeSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_closeSession(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CloseSession(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _FederatedAuthResult_userTokens(ctx context.Context, field graphql.CollectedField, obj *model.FederatedAuthResult) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_FederatedAuthResult_userTokens, + func(ctx context.Context) (any, error) { + return obj.UserTokens, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal []*model.UserAuthToken + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.UserAuthToken + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal []*model.UserAuthToken + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.UserAuthToken + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_closeSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_FederatedAuthResult_userTokens(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Mutation", + Object: "FederatedAuthResult", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + switch field.Name { + case "authProvider": + return ec.fieldContext_UserAuthToken_authProvider(ctx, field) + case "authConfiguration": + return ec.fieldContext_UserAuthToken_authConfiguration(ctx, field) + case "loginTime": + return ec.fieldContext_UserAuthToken_loginTime(ctx, field) + case "userId": + return ec.fieldContext_UserAuthToken_userId(ctx, field) + case "displayName": + return ec.fieldContext_UserAuthToken_displayName(ctx, field) + case "message": + return ec.fieldContext_UserAuthToken_message(ctx, field) + case "origin": + return ec.fieldContext_UserAuthToken_origin(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type UserAuthToken", field.Name) }, } return fc, nil } -func (ec *executionContext) _Mutation_touchSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_touchSession(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().TouchSession(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _LogEntry_time(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_LogEntry_time, + func(ctx context.Context) (any, error) { + return obj.Time, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalODateTime2ᚖtimeᚐTime, + true, + false, + ) } -func (ec *executionContext) fieldContext_Mutation_touchSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_LogEntry_time(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Mutation", + Object: "LogEntry", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type DateTime does not have child fields") }, } return fc, nil } -func (ec *executionContext) _Mutation_refreshSessionConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_refreshSessionConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RefreshSessionConnections(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _LogEntry_type(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_LogEntry_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_refreshSessionConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_LogEntry_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Mutation", + Object: "LogEntry", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _Mutation_changeSessionLanguage(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_changeSessionLanguage(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _LogEntry_message(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_LogEntry_message, + func(ctx context.Context) (any, error) { + return obj.Message, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_LogEntry_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "LogEntry", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().ChangeSessionLanguage(rctx, fc.Args["locale"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _LogEntry_stackTrace(ctx context.Context, field graphql.CollectedField, obj *model.LogEntry) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_LogEntry_stackTrace, + func(ctx context.Context) (any, error) { + return obj.StackTrace, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_LogEntry_stackTrace(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "LogEntry", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _LogoutInfo_redirectLinks(ctx context.Context, field graphql.CollectedField, obj *model.LogoutInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_LogoutInfo_redirectLinks, + func(ctx context.Context) (any, error) { + return obj.RedirectLinks, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal []string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_LogoutInfo_redirectLinks(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "LogoutInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Mutation_changeSessionLanguage(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Mutation_adminUpdateProductConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_adminUpdateProductConfiguration, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AdminUpdateProductConfiguration(ctx, + func() any { + if fc.Args["configuration"] == nil { + return nil + } + return fc.Args["configuration"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.4") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_adminUpdateProductConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -17868,45 +20546,195 @@ func (ec *executionContext) fieldContext_Mutation_changeSessionLanguage(ctx cont } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_changeSessionLanguage_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_adminUpdateProductConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_createConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_createConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } +func (ec *executionContext) _Mutation_setUserConfigurationParameter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_setUserConfigurationParameter, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SetUserConfigurationParameter(ctx, fc.Args["name"].(string), + func() any { + if fc.Args["value"] == nil { + return nil + } + return fc.Args["value"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_setUserConfigurationParameter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CreateConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_setUserConfigurationParameter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_setUserPreferences(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_setUserPreferences, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SetUserPreferences(ctx, + func() any { + if fc.Args["preferences"] == nil { + return nil + } + return fc.Args["preferences"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal *model.UserInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.UserInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_setUserPreferences(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "userId": + return ec.fieldContext_UserInfo_userId(ctx, field) + case "displayName": + return ec.fieldContext_UserInfo_displayName(ctx, field) + case "authRole": + return ec.fieldContext_UserInfo_authRole(ctx, field) + case "authTokens": + return ec.fieldContext_UserInfo_authTokens(ctx, field) + case "linkedAuthProviders": + return ec.fieldContext_UserInfo_linkedAuthProviders(ctx, field) + case "metaParameters": + return ec.fieldContext_UserInfo_metaParameters(ctx, field) + case "configurationParameters": + return ec.fieldContext_UserInfo_configurationParameters(ctx, field) + case "teams": + return ec.fieldContext_UserInfo_teams(ctx, field) + case "isAnonymous": + return ec.fieldContext_UserInfo_isAnonymous(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type UserInfo", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } - return graphql.Null + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_setUserPreferences_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Mutation_createConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Mutation_federatedLogin(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_federatedLogin, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().FederatedLogin(ctx, fc.Args["provider"].(string), fc.Args["configuration"].(*string), fc.Args["linkUser"].(*bool), fc.Args["forceSessionsLogout"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal *model.FederatedAuthInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.FederatedAuthInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal *model.FederatedAuthInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.FederatedAuthInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNFederatedAuthInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐFederatedAuthInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_federatedLogin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -17914,70 +20742,12 @@ func (ec *executionContext) fieldContext_Mutation_createConnection(ctx context.C IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "redirectLink": + return ec.fieldContext_FederatedAuthInfo_redirectLink(ctx, field) + case "taskInfo": + return ec.fieldContext_FederatedAuthInfo_taskInfo(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type FederatedAuthInfo", field.Name) }, } defer func() { @@ -17987,45 +20757,295 @@ func (ec *executionContext) fieldContext_Mutation_createConnection(ctx context.C } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_createConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_federatedLogin_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_updateConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_updateConnection(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_openSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_openSession, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().OpenSession(ctx, fc.Args["defaultLocale"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSessionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_openSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "createTime": + return ec.fieldContext_SessionInfo_createTime(ctx, field) + case "lastAccessTime": + return ec.fieldContext_SessionInfo_lastAccessTime(ctx, field) + case "locale": + return ec.fieldContext_SessionInfo_locale(ctx, field) + case "cacheExpired": + return ec.fieldContext_SessionInfo_cacheExpired(ctx, field) + case "connections": + return ec.fieldContext_SessionInfo_connections(ctx, field) + case "actionParameters": + return ec.fieldContext_SessionInfo_actionParameters(ctx, field) + case "valid": + return ec.fieldContext_SessionInfo_valid(ctx, field) + case "remainingTime": + return ec.fieldContext_SessionInfo_remainingTime(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type SessionInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().UpdateConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_openSession_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_closeSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_closeSession, + func(ctx context.Context) (any, error) { + return ec.resolvers.Mutation().CloseSession(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Mutation_closeSession(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Mutation_touchSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_touchSession, + func(ctx context.Context) (any, error) { + return ec.resolvers.Mutation().TouchSession(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Mutation_touchSession(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Mutation_updateSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_updateSession, + func(ctx context.Context) (any, error) { + return ec.resolvers.Mutation().UpdateSession(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.0") + if err != nil { + var zeroVal *model.SessionInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.SessionInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSessionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_updateSession(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "createTime": + return ec.fieldContext_SessionInfo_createTime(ctx, field) + case "lastAccessTime": + return ec.fieldContext_SessionInfo_lastAccessTime(ctx, field) + case "locale": + return ec.fieldContext_SessionInfo_locale(ctx, field) + case "cacheExpired": + return ec.fieldContext_SessionInfo_cacheExpired(ctx, field) + case "connections": + return ec.fieldContext_SessionInfo_connections(ctx, field) + case "actionParameters": + return ec.fieldContext_SessionInfo_actionParameters(ctx, field) + case "valid": + return ec.fieldContext_SessionInfo_valid(ctx, field) + case "remainingTime": + return ec.fieldContext_SessionInfo_remainingTime(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type SessionInfo", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") + return fc, nil +} + +func (ec *executionContext) _Mutation_refreshSessionConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_refreshSessionConnections, + func(ctx context.Context) (any, error) { + return ec.resolvers.Mutation().RefreshSessionConnections(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Mutation_refreshSessionConnections(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Mutation_changeSessionLanguage(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_changeSessionLanguage, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().ChangeSessionLanguage(ctx, fc.Args["locale"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Mutation_changeSessionLanguage(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } - return graphql.Null + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_changeSessionLanguage_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Mutation_createConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_createConnection, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().CreateConnection(ctx, fc.Args["config"].(model.ConnectionConfig), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_createConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -18051,10 +21071,16 @@ func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.C return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -18065,6 +21091,14 @@ func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.C return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -18079,8 +21113,6 @@ func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.C return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -18095,6 +21127,24 @@ func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.C return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -18106,100 +21156,33 @@ func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.C } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_updateConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Mutation_deleteConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_deleteConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().DeleteConnection(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Mutation_deleteConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Mutation", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_deleteConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_createConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_createConnectionFromTemplate(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_createConnectionFromTemplate(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CreateConnectionFromTemplate(rctx, fc.Args["templateId"].(string), fc.Args["connectionName"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_updateConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_updateConnection, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().UpdateConnection(ctx, fc.Args["config"].(model.ConnectionConfig), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_createConnectionFromTemplate(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_updateConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -18225,10 +21208,16 @@ func (ec *executionContext) fieldContext_Mutation_createConnectionFromTemplate(c return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -18239,6 +21228,14 @@ func (ec *executionContext) fieldContext_Mutation_createConnectionFromTemplate(c return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -18253,8 +21250,6 @@ func (ec *executionContext) fieldContext_Mutation_createConnectionFromTemplate(c return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -18269,6 +21264,24 @@ func (ec *executionContext) fieldContext_Mutation_createConnectionFromTemplate(c return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -18280,42 +21293,73 @@ func (ec *executionContext) fieldContext_Mutation_createConnectionFromTemplate(c } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_createConnectionFromTemplate_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_updateConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_createConnectionFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_createConnectionFolder(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_deleteConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_deleteConnection, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().DeleteConnection(ctx, fc.Args["id"].(string), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_deleteConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CreateConnectionFolder(rctx, fc.Args["parentFolderPath"].(*string), fc.Args["folderName"].(string)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_deleteConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(*model.ConnectionFolderInfo) - fc.Result = res - return ec.marshalNConnectionFolderInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Mutation_createConnectionFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_createConnectionFolder, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().CreateConnectionFolder(ctx, fc.Args["parentFolderPath"].(*string), fc.Args["folderName"].(string), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionFolderInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_createConnectionFolder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -18328,6 +21372,8 @@ func (ec *executionContext) fieldContext_Mutation_createConnectionFolder(ctx con switch field.Name { case "id": return ec.fieldContext_ConnectionFolderInfo_id(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionFolderInfo_projectId(ctx, field) case "description": return ec.fieldContext_ConnectionFolderInfo_description(ctx, field) } @@ -18343,40 +21389,28 @@ func (ec *executionContext) fieldContext_Mutation_createConnectionFolder(ctx con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_createConnectionFolder_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_deleteConnectionFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_deleteConnectionFolder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().DeleteConnectionFolder(rctx, fc.Args["folderPath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_deleteConnectionFolder, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().DeleteConnectionFolder(ctx, fc.Args["folderPath"].(string), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_deleteConnectionFolder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -18398,40 +21432,28 @@ func (ec *executionContext) fieldContext_Mutation_deleteConnectionFolder(ctx con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_deleteConnectionFolder_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_copyConnectionFromNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_copyConnectionFromNode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CopyConnectionFromNode(rctx, fc.Args["nodePath"].(string), fc.Args["config"].(*model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_copyConnectionFromNode, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().CopyConnectionFromNode(ctx, fc.Args["nodePath"].(string), fc.Args["config"].(*model.ConnectionConfig), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_copyConnectionFromNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -18460,10 +21482,16 @@ func (ec *executionContext) fieldContext_Mutation_copyConnectionFromNode(ctx con return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -18474,6 +21502,14 @@ func (ec *executionContext) fieldContext_Mutation_copyConnectionFromNode(ctx con return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -18488,8 +21524,6 @@ func (ec *executionContext) fieldContext_Mutation_copyConnectionFromNode(ctx con return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -18504,6 +21538,24 @@ func (ec *executionContext) fieldContext_Mutation_copyConnectionFromNode(ctx con return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -18517,40 +21569,28 @@ func (ec *executionContext) fieldContext_Mutation_copyConnectionFromNode(ctx con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_copyConnectionFromNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_testConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_testConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().TestConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_testConnection, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().TestConnection(ctx, fc.Args["config"].(model.ConnectionConfig), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_testConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -18579,10 +21619,16 @@ func (ec *executionContext) fieldContext_Mutation_testConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -18593,6 +21639,14 @@ func (ec *executionContext) fieldContext_Mutation_testConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -18607,8 +21661,6 @@ func (ec *executionContext) fieldContext_Mutation_testConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -18623,6 +21675,24 @@ func (ec *executionContext) fieldContext_Mutation_testConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -18636,40 +21706,28 @@ func (ec *executionContext) fieldContext_Mutation_testConnection(ctx context.Con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_testConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_testNetworkHandler(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_testNetworkHandler(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().TestNetworkHandler(rctx, fc.Args["config"].(model.NetworkHandlerConfigInput)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NetworkEndpointInfo) - fc.Result = res - return ec.marshalNNetworkEndpointInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkEndpointInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_testNetworkHandler, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().TestNetworkHandler(ctx, fc.Args["config"].(model.NetworkHandlerConfigInput)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNNetworkEndpointInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkEndpointInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_testNetworkHandler(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -18699,46 +21757,34 @@ func (ec *executionContext) fieldContext_Mutation_testNetworkHandler(ctx context ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_testNetworkHandler_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_initConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_initConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().InitConnection(rctx, fc.Args["id"].(string), - func() interface{} { - if fc.Args["credentials"] == nil { - return nil - } - return fc.Args["credentials"].(interface{}) - }(), fc.Args["networkCredentials"].([]*model.NetworkHandlerConfigInput), fc.Args["saveCredentials"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_initConnection, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().InitConnection(ctx, fc.Args["id"].(string), fc.Args["projectId"].(*string), + func() any { + if fc.Args["credentials"] == nil { + return nil + } + return fc.Args["credentials"].(any) + }(), fc.Args["networkCredentials"].([]*model.NetworkHandlerConfigInput), fc.Args["saveCredentials"].(*bool), fc.Args["sharedCredentials"].(*bool), fc.Args["selectedSecretId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_initConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -18767,10 +21813,16 @@ func (ec *executionContext) fieldContext_Mutation_initConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -18781,6 +21833,14 @@ func (ec *executionContext) fieldContext_Mutation_initConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -18795,8 +21855,6 @@ func (ec *executionContext) fieldContext_Mutation_initConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -18811,6 +21869,24 @@ func (ec *executionContext) fieldContext_Mutation_initConnection(ctx context.Con return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -18824,40 +21900,28 @@ func (ec *executionContext) fieldContext_Mutation_initConnection(ctx context.Con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_initConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_closeConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_closeConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().CloseConnection(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_closeConnection, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().CloseConnection(ctx, fc.Args["id"].(string), fc.Args["projectId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_closeConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -18886,10 +21950,16 @@ func (ec *executionContext) fieldContext_Mutation_closeConnection(ctx context.Co return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -18900,6 +21970,14 @@ func (ec *executionContext) fieldContext_Mutation_closeConnection(ctx context.Co return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -18914,8 +21992,6 @@ func (ec *executionContext) fieldContext_Mutation_closeConnection(ctx context.Co return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -18930,6 +22006,24 @@ func (ec *executionContext) fieldContext_Mutation_closeConnection(ctx context.Co return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -18943,40 +22037,28 @@ func (ec *executionContext) fieldContext_Mutation_closeConnection(ctx context.Co ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_closeConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_setConnectionNavigatorSettings(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_setConnectionNavigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SetConnectionNavigatorSettings(rctx, fc.Args["id"].(string), fc.Args["settings"].(model.NavigatorSettingsInput)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_setConnectionNavigatorSettings, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SetConnectionNavigatorSettings(ctx, fc.Args["id"].(string), fc.Args["projectId"].(*string), fc.Args["settings"].(model.NavigatorSettingsInput)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_setConnectionNavigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -19005,10 +22087,16 @@ func (ec *executionContext) fieldContext_Mutation_setConnectionNavigatorSettings return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -19019,6 +22107,14 @@ func (ec *executionContext) fieldContext_Mutation_setConnectionNavigatorSettings return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -19033,8 +22129,6 @@ func (ec *executionContext) fieldContext_Mutation_setConnectionNavigatorSettings return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -19049,6 +22143,24 @@ func (ec *executionContext) fieldContext_Mutation_setConnectionNavigatorSettings return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -19062,37 +22174,28 @@ func (ec *executionContext) fieldContext_Mutation_setConnectionNavigatorSettings ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_setConnectionNavigatorSettings_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_asyncTaskCancel(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncTaskCancel(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncTaskCancel(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncTaskCancel, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncTaskCancel(ctx, fc.Args["id"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } func (ec *executionContext) fieldContext_Mutation_asyncTaskCancel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -19114,40 +22217,28 @@ func (ec *executionContext) fieldContext_Mutation_asyncTaskCancel(ctx context.Co ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_asyncTaskCancel_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_asyncTaskInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncTaskInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncTaskInfo(rctx, fc.Args["id"].(string), fc.Args["removeOnFinish"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncTaskInfo, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncTaskInfo(ctx, fc.Args["id"].(string), fc.Args["removeOnFinish"].(bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_asyncTaskInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -19168,8 +22259,6 @@ func (ec *executionContext) fieldContext_Mutation_asyncTaskInfo(ctx context.Cont return ec.fieldContext_AsyncTaskInfo_status(ctx, field) case "error": return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) case "taskResult": return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) } @@ -19185,43 +22274,31 @@ func (ec *executionContext) fieldContext_Mutation_asyncTaskInfo(ctx context.Cont ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_asyncTaskInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_openConnection(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_openConnection(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().OpenConnection(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_navReloadNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_navReloadNode, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().NavReloadNode(ctx, fc.Args["nodePath"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_openConnection(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_navReloadNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -19230,69 +22307,45 @@ func (ec *executionContext) fieldContext_Mutation_openConnection(ctx context.Con Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) + return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) + return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) + case "fullName": + return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) + case "icon": + return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) + return ec.fieldContext_NavigatorNodeInfo_description(ctx, field) + case "nodeType": + return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) + case "hasChildren": + return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) + case "object": + return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) + case "nodeDetails": + return ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) + case "folder": + return ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) + case "inline": + return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) + case "navigable": + return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) }, } defer func() { @@ -19302,68 +22355,40 @@ func (ec *executionContext) fieldContext_Mutation_openConnection(ctx context.Con } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_openConnection_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_navReloadNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_asyncTaskStatus(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncTaskStatus(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncTaskStatus(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_navRenameNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_navRenameNode, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().NavRenameNode(ctx, fc.Args["nodePath"].(string), fc.Args["newName"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_Mutation_asyncTaskStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_navRenameNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, IsMethod: true, IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) + return nil, errors.New("field of type String does not have child fields") }, } defer func() { @@ -19373,49 +22398,40 @@ func (ec *executionContext) fieldContext_Mutation_asyncTaskStatus(ctx context.Co } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncTaskStatus_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_navRenameNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_navRenameNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_navRenameNode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().NavRenameNode(rctx, fc.Args["nodePath"].(string), fc.Args["newName"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_navDeleteNodes(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_navDeleteNodes, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().NavDeleteNodes(ctx, fc.Args["nodePaths"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_Mutation_navRenameNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_navDeleteNodes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, IsMethod: true, IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } defer func() { @@ -19425,49 +22441,40 @@ func (ec *executionContext) fieldContext_Mutation_navRenameNode(ctx context.Cont } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_navRenameNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_navDeleteNodes_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_navDeleteNodes(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_navDeleteNodes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().NavDeleteNodes(rctx, fc.Args["nodePaths"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_navMoveNodesToFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_navMoveNodesToFolder, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().NavMoveNodesToFolder(ctx, fc.Args["nodePaths"].([]string), fc.Args["folderPath"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_navDeleteNodes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_navMoveNodesToFolder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, IsMethod: true, IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } defer func() { @@ -19477,42 +22484,33 @@ func (ec *executionContext) fieldContext_Mutation_navDeleteNodes(ctx context.Con } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_navDeleteNodes_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_navMoveNodesToFolder_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_navMoveNodesToFolder(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_navMoveNodesToFolder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().NavMoveNodesToFolder(rctx, fc.Args["nodePaths"].([]string), fc.Args["folderPath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_navSetFolderFilter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_navSetFolderFilter, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().NavSetFolderFilter(ctx, fc.Args["nodePath"].(string), fc.Args["include"].([]string), fc.Args["exclude"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_navMoveNodesToFolder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_navSetFolderFilter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -19529,42 +22527,30 @@ func (ec *executionContext) fieldContext_Mutation_navMoveNodesToFolder(ctx conte } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_navMoveNodesToFolder_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_navSetFolderFilter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_rmCreateResource(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmCreateResource(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmCreateResource(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["isFolder"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmCreateResource, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmCreateResource(ctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["isFolder"].(bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_rmCreateResource(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -19586,40 +22572,28 @@ func (ec *executionContext) fieldContext_Mutation_rmCreateResource(ctx context.C ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_rmCreateResource_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_rmMoveResource(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmMoveResource(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmMoveResource(rctx, fc.Args["projectId"].(string), fc.Args["oldResourcePath"].(string), fc.Args["newResourcePath"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmMoveResource, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmMoveResource(ctx, fc.Args["projectId"].(string), fc.Args["oldResourcePath"].(string), fc.Args["newResourcePath"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_rmMoveResource(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -19641,37 +22615,28 @@ func (ec *executionContext) fieldContext_Mutation_rmMoveResource(ctx context.Con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_rmMoveResource_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_rmDeleteResource(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmDeleteResource(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmDeleteResource(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["recursive"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmDeleteResource, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmDeleteResource(ctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["recursive"].(bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } func (ec *executionContext) fieldContext_Mutation_rmDeleteResource(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -19693,40 +22658,28 @@ func (ec *executionContext) fieldContext_Mutation_rmDeleteResource(ctx context.C ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_rmDeleteResource_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_rmWriteResourceStringContent(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_rmWriteResourceStringContent(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().RmWriteResourceStringContent(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["data"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmWriteResourceStringContent, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmWriteResourceStringContent(ctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["data"].(string), fc.Args["forceOverwrite"].(bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_rmWriteResourceStringContent(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -19748,43 +22701,31 @@ func (ec *executionContext) fieldContext_Mutation_rmWriteResourceStringContent(c ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_rmWriteResourceStringContent_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_sqlContextCreate(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlContextCreate(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLContextCreate(rctx, fc.Args["connectionId"].(string), fc.Args["defaultCatalog"].(*string), fc.Args["defaultSchema"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLContextInfo) - fc.Result = res - return ec.marshalNSQLContextInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_rmCreateProject(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmCreateProject, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmCreateProject(ctx, fc.Args["projectId"].(*string), fc.Args["projectName"].(string), fc.Args["description"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNRMProject2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProject, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_sqlContextCreate(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_rmCreateProject(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -19793,15 +22734,25 @@ func (ec *executionContext) fieldContext_Mutation_sqlContextCreate(ctx context.C Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { case "id": - return ec.fieldContext_SQLContextInfo_id(ctx, field) - case "connectionId": - return ec.fieldContext_SQLContextInfo_connectionId(ctx, field) - case "defaultCatalog": - return ec.fieldContext_SQLContextInfo_defaultCatalog(ctx, field) - case "defaultSchema": - return ec.fieldContext_SQLContextInfo_defaultSchema(ctx, field) + return ec.fieldContext_RMProject_id(ctx, field) + case "name": + return ec.fieldContext_RMProject_name(ctx, field) + case "description": + return ec.fieldContext_RMProject_description(ctx, field) + case "shared": + return ec.fieldContext_RMProject_shared(ctx, field) + case "global": + return ec.fieldContext_RMProject_global(ctx, field) + case "createTime": + return ec.fieldContext_RMProject_createTime(ctx, field) + case "creator": + return ec.fieldContext_RMProject_creator(ctx, field) + case "projectPermissions": + return ec.fieldContext_RMProject_projectPermissions(ctx, field) + case "resourceTypes": + return ec.fieldContext_RMProject_resourceTypes(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type SQLContextInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type RMProject", field.Name) }, } defer func() { @@ -19811,45 +22762,33 @@ func (ec *executionContext) fieldContext_Mutation_sqlContextCreate(ctx context.C } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_sqlContextCreate_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_rmCreateProject_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_sqlContextSetDefaults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlContextSetDefaults(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLContextSetDefaults(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["defaultCatalog"].(*string), fc.Args["defaultSchema"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_rmDeleteProject(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmDeleteProject, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmDeleteProject(ctx, fc.Args["projectId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_Mutation_sqlContextSetDefaults(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_rmDeleteProject(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -19866,45 +22805,76 @@ func (ec *executionContext) fieldContext_Mutation_sqlContextSetDefaults(ctx cont } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_sqlContextSetDefaults_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_rmDeleteProject_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_sqlContextDestroy(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlContextDestroy(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_rmSetProjectPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmSetProjectPermissions, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmSetProjectPermissions(ctx, fc.Args["projectId"].(string), fc.Args["permissions"].([]*model.RMSubjectProjectPermissions)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_rmSetProjectPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLContextDestroy(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_rmSetProjectPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Mutation_sqlContextDestroy(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Mutation_rmSetSubjectProjectPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmSetSubjectProjectPermissions, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmSetSubjectProjectPermissions(ctx, fc.Args["subjectId"].(string), fc.Args["permissions"].([]*model.RMProjectPermissions)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_rmSetSubjectProjectPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -19921,68 +22891,115 @@ func (ec *executionContext) fieldContext_Mutation_sqlContextDestroy(ctx context. } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_sqlContextDestroy_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_rmSetSubjectProjectPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_asyncSqlExecuteQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExecuteQuery(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_rmAddProjectsPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmAddProjectsPermissions, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmAddProjectsPermissions(ctx, fc.Args["projectIds"].([]string), fc.Args["subjectIds"].([]string), fc.Args["permissions"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.2.2") + if err != nil { + var zeroVal *bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Mutation_rmAddProjectsPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExecuteQuery(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["sql"].(string), fc.Args["resultId"].(*string), fc.Args["filter"].(*model.SQLDataFilter), fc.Args["dataFormat"].(*model.ResultDataFormat)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_rmAddProjectsPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Mutation_rmDeleteProjectsPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmDeleteProjectsPermissions, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmDeleteProjectsPermissions(ctx, fc.Args["projectIds"].([]string), fc.Args["subjectIds"].([]string), fc.Args["permissions"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.2.2") + if err != nil { + var zeroVal *bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Mutation_rmDeleteProjectsPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, IsMethod: true, IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AsyncTaskInfo_id(ctx, field) - case "name": - return ec.fieldContext_AsyncTaskInfo_name(ctx, field) - case "running": - return ec.fieldContext_AsyncTaskInfo_running(ctx, field) - case "status": - return ec.fieldContext_AsyncTaskInfo_status(ctx, field) - case "error": - return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) - case "taskResult": - return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) + return nil, errors.New("field of type Boolean does not have child fields") }, } defer func() { @@ -19992,45 +23009,219 @@ func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteQuery(ctx conte } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncSqlExecuteQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_rmDeleteProjectsPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_asyncReadDataFromContainer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncReadDataFromContainer(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { +func (ec *executionContext) _Mutation_rmSetResourceProperty(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_rmSetResourceProperty, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().RmSetResourceProperty(ctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string), fc.Args["name"].(string), fc.Args["value"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_rmSetResourceProperty(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncReadDataFromContainer(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["containerNodePath"].(string), fc.Args["resultId"].(*string), fc.Args["filter"].(*model.SQLDataFilter), fc.Args["dataFormat"].(*model.ResultDataFormat)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_rmSetResourceProperty_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_sqlContextCreate(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_sqlContextCreate, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SQLContextCreate(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["defaultCatalog"].(*string), fc.Args["defaultSchema"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_sqlContextCreate(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_SQLContextInfo_id(ctx, field) + case "projectId": + return ec.fieldContext_SQLContextInfo_projectId(ctx, field) + case "connectionId": + return ec.fieldContext_SQLContextInfo_connectionId(ctx, field) + case "autoCommit": + return ec.fieldContext_SQLContextInfo_autoCommit(ctx, field) + case "defaultCatalog": + return ec.fieldContext_SQLContextInfo_defaultCatalog(ctx, field) + case "defaultSchema": + return ec.fieldContext_SQLContextInfo_defaultSchema(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type SQLContextInfo", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } - return graphql.Null + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_sqlContextCreate_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Mutation_asyncReadDataFromContainer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Mutation_sqlContextSetDefaults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_sqlContextSetDefaults, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SQLContextSetDefaults(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["defaultCatalog"].(*string), fc.Args["defaultSchema"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_sqlContextSetDefaults(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_sqlContextSetDefaults_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_sqlContextDestroy(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_sqlContextDestroy, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SQLContextDestroy(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_sqlContextDestroy(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_sqlContextDestroy_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_asyncSqlExecuteQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlExecuteQuery, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLExecuteQuery(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["sql"].(string), fc.Args["resultId"].(*string), fc.Args["filter"].(*model.SQLDataFilter), fc.Args["dataFormat"].(*model.ResultDataFormat), fc.Args["readLogs"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -20048,8 +23239,6 @@ func (ec *executionContext) fieldContext_Mutation_asyncReadDataFromContainer(ctx return ec.fieldContext_AsyncTaskInfo_status(ctx, field) case "error": return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) case "taskResult": return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) } @@ -20063,42 +23252,136 @@ func (ec *executionContext) fieldContext_Mutation_asyncReadDataFromContainer(ctx } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_asyncReadDataFromContainer_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_asyncSqlExecuteQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_sqlResultClose(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_sqlResultClose(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_asyncReadDataFromContainer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncReadDataFromContainer, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncReadDataFromContainer(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["containerNodePath"].(string), fc.Args["resultId"].(*string), fc.Args["filter"].(*model.SQLDataFilter), fc.Args["dataFormat"].(*model.ResultDataFormat)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_asyncReadDataFromContainer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_AsyncTaskInfo_id(ctx, field) + case "name": + return ec.fieldContext_AsyncTaskInfo_name(ctx, field) + case "running": + return ec.fieldContext_AsyncTaskInfo_running(ctx, field) + case "status": + return ec.fieldContext_AsyncTaskInfo_status(ctx, field) + case "error": + return ec.fieldContext_AsyncTaskInfo_error(ctx, field) + case "taskResult": + return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().SQLResultClose(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultId"].(string)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_asyncReadDataFromContainer_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_getTransactionLogInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_getTransactionLogInfo, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().GetTransactionLogInfo(ctx, fc.Args["projectId"].(string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNTransactionLogInfos2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐTransactionLogInfos, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_getTransactionLogInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "count": + return ec.fieldContext_TransactionLogInfos_count(ctx, field) + case "transactionLogInfos": + return ec.fieldContext_TransactionLogInfos_transactionLogInfos(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TransactionLogInfos", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } - return graphql.Null + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_getTransactionLogInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Mutation_sqlResultClose(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_sqlResultClose, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SQLResultClose(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_sqlResultClose(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -20120,40 +23403,101 @@ func (ec *executionContext) fieldContext_Mutation_sqlResultClose(ctx context.Con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_sqlResultClose_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_updateResultsDataBatch(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_updateResultsDataBatch(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_asyncUpdateResultsDataBatch(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncUpdateResultsDataBatch, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncUpdateResultsDataBatch(ctx, fc.Args["projectId"].(string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["updatedRows"].([]*model.SQLResultRow), fc.Args["deletedRows"].([]*model.SQLResultRow), fc.Args["addedRows"].([]*model.SQLResultRow)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.0") + if err != nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_asyncUpdateResultsDataBatch(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_AsyncTaskInfo_id(ctx, field) + case "name": + return ec.fieldContext_AsyncTaskInfo_name(ctx, field) + case "running": + return ec.fieldContext_AsyncTaskInfo_running(ctx, field) + case "status": + return ec.fieldContext_AsyncTaskInfo_status(ctx, field) + case "error": + return ec.fieldContext_AsyncTaskInfo_error(ctx, field) + case "taskResult": + return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().UpdateResultsDataBatch(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["updatedRows"].([]*model.SQLResultRow), fc.Args["deletedRows"].([]*model.SQLResultRow), fc.Args["addedRows"].([]*model.SQLResultRow)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_asyncUpdateResultsDataBatch_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLExecuteInfo) - fc.Result = res - return ec.marshalNSQLExecuteInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Mutation_updateResultsDataBatch(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_updateResultsDataBatch, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().UpdateResultsDataBatch(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["updatedRows"].([]*model.SQLResultRow), fc.Args["deletedRows"].([]*model.SQLResultRow), fc.Args["addedRows"].([]*model.SQLResultRow)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_updateResultsDataBatch(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -20170,6 +23514,8 @@ func (ec *executionContext) fieldContext_Mutation_updateResultsDataBatch(ctx con return ec.fieldContext_SQLExecuteInfo_duration(ctx, field) case "filterText": return ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) + case "fullQuery": + return ec.fieldContext_SQLExecuteInfo_fullQuery(ctx, field) case "results": return ec.fieldContext_SQLExecuteInfo_results(ctx, field) } @@ -20185,40 +23531,28 @@ func (ec *executionContext) fieldContext_Mutation_updateResultsDataBatch(ctx con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_updateResultsDataBatch_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_updateResultsDataBatchScript(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_updateResultsDataBatchScript(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().UpdateResultsDataBatchScript(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["updatedRows"].([]*model.SQLResultRow), fc.Args["deletedRows"].([]*model.SQLResultRow), fc.Args["addedRows"].([]*model.SQLResultRow)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_updateResultsDataBatchScript, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().UpdateResultsDataBatchScript(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["updatedRows"].([]*model.SQLResultRow), fc.Args["deletedRows"].([]*model.SQLResultRow), fc.Args["addedRows"].([]*model.SQLResultRow)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_updateResultsDataBatchScript(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -20240,43 +23574,90 @@ func (ec *executionContext) fieldContext_Mutation_updateResultsDataBatchScript(c ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_updateResultsDataBatchScript_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_readLobValue(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_readLobValue(ctx, field) - if err != nil { - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_readLobValue, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().ReadLobValue(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["lobColumnIndex"].(int), fc.Args["row"].([]*model.SQLResultRow)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_readLobValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().ReadLobValue(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["lobColumnIndex"].(int), fc.Args["row"].([]*model.SQLResultRow)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_readLobValue_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Mutation_readLobValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Mutation_sqlReadLobValue(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_sqlReadLobValue, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SQLReadLobValue(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["lobColumnIndex"].(int), fc.Args["row"].(model.SQLResultRow)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_sqlReadLobValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Mutation", Field: field, @@ -20293,42 +23674,89 @@ func (ec *executionContext) fieldContext_Mutation_readLobValue(ctx context.Conte } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Mutation_readLobValue_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Mutation_sqlReadLobValue_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Mutation_asyncSqlExecuteResults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExecuteResults(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_sqlReadStringValue(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_sqlReadStringValue, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SQLReadStringValue(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["columnIndex"].(int), fc.Args["row"].(model.SQLResultRow)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_sqlReadStringValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExecuteResults(rctx, fc.Args["taskId"].(string)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_sqlReadStringValue_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(*model.SQLExecuteInfo) - fc.Result = res - return ec.marshalNSQLExecuteInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Mutation_asyncSqlExecuteResults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlExecuteResults, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLExecuteResults(ctx, fc.Args["taskId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteResults(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -20345,6 +23773,8 @@ func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteResults(ctx con return ec.fieldContext_SQLExecuteInfo_duration(ctx, field) case "filterText": return ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) + case "fullQuery": + return ec.fieldContext_SQLExecuteInfo_fullQuery(ctx, field) case "results": return ec.fieldContext_SQLExecuteInfo_results(ctx, field) } @@ -20360,46 +23790,34 @@ func (ec *executionContext) fieldContext_Mutation_asyncSqlExecuteResults(ctx con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_asyncSqlExecuteResults_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_asyncSqlExplainExecutionPlan(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExplainExecutionPlan(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExplainExecutionPlan(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string), - func() interface{} { - if fc.Args["configuration"] == nil { - return nil - } - return fc.Args["configuration"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlExplainExecutionPlan, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLExplainExecutionPlan(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string), + func() any { + if fc.Args["configuration"] == nil { + return nil + } + return fc.Args["configuration"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_asyncSqlExplainExecutionPlan(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -20420,8 +23838,6 @@ func (ec *executionContext) fieldContext_Mutation_asyncSqlExplainExecutionPlan(c return ec.fieldContext_AsyncTaskInfo_status(ctx, field) case "error": return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) case "taskResult": return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) } @@ -20437,40 +23853,28 @@ func (ec *executionContext) fieldContext_Mutation_asyncSqlExplainExecutionPlan(c ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_asyncSqlExplainExecutionPlan_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Mutation_asyncSqlExplainExecutionPlanResult(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Mutation_asyncSqlExplainExecutionPlanResult(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Mutation().AsyncSQLExplainExecutionPlanResult(rctx, fc.Args["taskId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLExecutionPlan) - fc.Result = res - return ec.marshalNSQLExecutionPlan2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlan(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlExplainExecutionPlanResult, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLExplainExecutionPlanResult(ctx, fc.Args["taskId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLExecutionPlan2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlan, + true, + true, + ) } func (ec *executionContext) fieldContext_Mutation_asyncSqlExplainExecutionPlanResult(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -20498,248 +23902,556 @@ func (ec *executionContext) fieldContext_Mutation_asyncSqlExplainExecutionPlanRe ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Mutation_asyncSqlExplainExecutionPlanResult_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _NavigatorNodeInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _Mutation_asyncSqlRowDataCount(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlRowDataCount, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLRowDataCount(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_asyncSqlRowDataCount(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", + Object: "Mutation", Field: field, - IsMethod: false, - IsResolver: false, + IsMethod: true, + IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + switch field.Name { + case "id": + return ec.fieldContext_AsyncTaskInfo_id(ctx, field) + case "name": + return ec.fieldContext_AsyncTaskInfo_name(ctx, field) + case "running": + return ec.fieldContext_AsyncTaskInfo_running(ctx, field) + case "status": + return ec.fieldContext_AsyncTaskInfo_status(ctx, field) + case "error": + return ec.fieldContext_AsyncTaskInfo_error(ctx, field) + case "taskResult": + return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) }, } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_asyncSqlRowDataCount_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return fc, err } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Mutation_asyncSqlRowDataCountResult(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlRowDataCountResult, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLRowDataCountResult(ctx, fc.Args["taskId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_asyncSqlRowDataCountResult(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", + Object: "Mutation", Field: field, - IsMethod: false, - IsResolver: false, + IsMethod: true, + IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_fullName(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullName, nil - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_asyncSqlRowDataCountResult_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return fc, err } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Mutation_sqlGetDynamicTrace(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_sqlGetDynamicTrace, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().SQLGetDynamicTrace(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.2") + if err != nil { + var zeroVal []*model.DynamicTraceProperty + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.DynamicTraceProperty + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDynamicTraceProperty2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDynamicTracePropertyᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_fullName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_sqlGetDynamicTrace(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", + Object: "Mutation", Field: field, - IsMethod: false, - IsResolver: false, + IsMethod: true, + IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + switch field.Name { + case "name": + return ec.fieldContext_DynamicTraceProperty_name(ctx, field) + case "value": + return ec.fieldContext_DynamicTraceProperty_value(ctx, field) + case "description": + return ec.fieldContext_DynamicTraceProperty_description(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type DynamicTraceProperty", field.Name) }, } - return fc, nil -} - -func (ec *executionContext) _NavigatorNodeInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_sqlGetDynamicTrace_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") +func (ec *executionContext) _Mutation_asyncSqlSetAutoCommit(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlSetAutoCommit, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLSetAutoCommit(ctx, fc.Args["projectId"].(string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["autoCommit"].(bool)) }, - } - return fc, nil -} + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next -func (ec *executionContext) _NavigatorNodeInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_description(ctx, field) - if err != nil { - return graphql.Null + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_asyncSqlSetAutoCommit(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_AsyncTaskInfo_id(ctx, field) + case "name": + return ec.fieldContext_AsyncTaskInfo_name(ctx, field) + case "running": + return ec.fieldContext_AsyncTaskInfo_running(ctx, field) + case "status": + return ec.fieldContext_AsyncTaskInfo_status(ctx, field) + case "error": + return ec.fieldContext_AsyncTaskInfo_error(ctx, field) + case "taskResult": + return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_asyncSqlSetAutoCommit_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return fc, err } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Mutation_asyncSqlCommitTransaction(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlCommitTransaction, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLCommitTransaction(ctx, fc.Args["projectId"].(string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Mutation_asyncSqlCommitTransaction(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "NavigatorNodeInfo", + Object: "Mutation", Field: field, - IsMethod: false, - IsResolver: false, + IsMethod: true, + IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + switch field.Name { + case "id": + return ec.fieldContext_AsyncTaskInfo_id(ctx, field) + case "name": + return ec.fieldContext_AsyncTaskInfo_name(ctx, field) + case "running": + return ec.fieldContext_AsyncTaskInfo_running(ctx, field) + case "status": + return ec.fieldContext_AsyncTaskInfo_status(ctx, field) + case "error": + return ec.fieldContext_AsyncTaskInfo_error(ctx, field) + case "taskResult": + return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) }, } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_asyncSqlCommitTransaction_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } return fc, nil } -func (ec *executionContext) _NavigatorNodeInfo_nodeType(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Mutation_asyncSqlRollbackTransaction(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Mutation_asyncSqlRollbackTransaction, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Mutation().AsyncSQLRollbackTransaction(ctx, fc.Args["projectId"].(string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.AsyncTaskInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Mutation_asyncSqlRollbackTransaction(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_AsyncTaskInfo_id(ctx, field) + case "name": + return ec.fieldContext_AsyncTaskInfo_name(ctx, field) + case "running": + return ec.fieldContext_AsyncTaskInfo_running(ctx, field) + case "status": + return ec.fieldContext_AsyncTaskInfo_status(ctx, field) + case "error": + return ec.fieldContext_AsyncTaskInfo_error(ctx, field) + case "taskResult": + return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AsyncTaskInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodeType, nil - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_asyncSqlRollbackTransaction_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeFilter_include(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeFilter) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeFilter_include, + func(ctx context.Context) (any, error) { + return obj.Include, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕstringᚄ, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeFilter_include(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeFilter", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeFilter_exclude(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeFilter) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeFilter_exclude, + func(ctx context.Context) (any, error) { + return obj.Exclude, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕstringᚄ, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeFilter_exclude(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeFilter", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_uri(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_uri, + func(ctx context.Context) (any, error) { + return obj.URI, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.1") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_uri(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, @@ -20752,76 +24464,242 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeType(ctx context. return fc, nil } -func (ec *executionContext) _NavigatorNodeInfo_hasChildren(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _NavigatorNodeInfo_fullName(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_fullName, + func(ctx context.Context) (any, error) { + return obj.FullName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_fullName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HasChildren, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_plainName(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_plainName, + func(ctx context.Context) (any, error) { + return obj.PlainName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_plainName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_icon(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_hasChildren(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _NavigatorNodeInfo_object(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_object(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _NavigatorNodeInfo_nodeType(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_nodeType, + func(ctx context.Context) (any, error) { + return obj.NodeType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Object, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_hasChildren(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_hasChildren, + func(ctx context.Context) (any, error) { + return obj.HasChildren, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_hasChildren(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_projectId(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_projectId, + func(ctx context.Context) (any, error) { + return obj.ProjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_projectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*model.DatabaseObjectInfo) - fc.Result = res - return ec.marshalODatabaseObjectInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseObjectInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_object(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_object, + func(ctx context.Context) (any, error) { + return obj.Object, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalODatabaseObjectInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseObjectInfo, + true, + false, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_object(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_object(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, @@ -20858,35 +24736,72 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_object(ctx context.Co return fc, nil } -func (ec *executionContext) _NavigatorNodeInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null +func (ec *executionContext) _NavigatorNodeInfo_objectId(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_objectId, + func(ctx context.Context) (any, error) { + return obj.ObjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.2.4") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_NavigatorNodeInfo_objectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorNodeInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.([]string) - fc.Result = res - return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _NavigatorNodeInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_features, + func(ctx context.Context) (any, error) { + return obj.Features, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕstringᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_features(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, @@ -20900,34 +24815,24 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_features(ctx context. } func (ec *executionContext) _NavigatorNodeInfo_nodeDetails(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_nodeDetails(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodeDetails, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_nodeDetails, + func(ctx context.Context) (any, error) { + return obj.NodeDetails, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeDetails(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeDetails(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, @@ -20941,6 +24846,8 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeDetails(ctx conte return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -20957,6 +24864,14 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeDetails(ctx conte return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -20965,34 +24880,24 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_nodeDetails(ctx conte } func (ec *executionContext) _NavigatorNodeInfo_folder(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_folder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Folder, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_folder, + func(ctx context.Context) (any, error) { + return obj.Folder, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_folder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_folder(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, @@ -21006,34 +24911,24 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_folder(ctx context.Co } func (ec *executionContext) _NavigatorNodeInfo_inline(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Inline, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_inline, + func(ctx context.Context) (any, error) { + return obj.Inline, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_inline(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_inline(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, @@ -21047,34 +24942,24 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_inline(ctx context.Co } func (ec *executionContext) _NavigatorNodeInfo_navigable(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Navigable, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_navigable, + func(ctx context.Context) (any, error) { + return obj.Navigable, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorNodeInfo_navigable(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_navigable(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorNodeInfo", Field: field, @@ -21087,40 +24972,27 @@ func (ec *executionContext) fieldContext_NavigatorNodeInfo_navigable(ctx context return fc, nil } -func (ec *executionContext) _NavigatorSettings_showSystemObjects(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_showSystemObjects(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ShowSystemObjects, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _NavigatorNodeInfo_filtered(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_filtered, + func(ctx context.Context) (any, error) { + return obj.Filtered, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorSettings_showSystemObjects(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_filtered(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "NavigatorSettings", + Object: "NavigatorNodeInfo", Field: field, IsMethod: false, IsResolver: false, @@ -21131,82 +25003,62 @@ func (ec *executionContext) fieldContext_NavigatorSettings_showSystemObjects(ctx return fc, nil } -func (ec *executionContext) _NavigatorSettings_showUtilityObjects(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_showUtilityObjects(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ShowUtilityObjects, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _NavigatorNodeInfo_filter(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorNodeInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorNodeInfo_filter, + func(ctx context.Context) (any, error) { + return obj.Filter, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalONavigatorNodeFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeFilter, + true, + false, + ) } -func (ec *executionContext) fieldContext_NavigatorSettings_showUtilityObjects(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorNodeInfo_filter(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "NavigatorSettings", + Object: "NavigatorNodeInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + switch field.Name { + case "include": + return ec.fieldContext_NavigatorNodeFilter_include(ctx, field) + case "exclude": + return ec.fieldContext_NavigatorNodeFilter_exclude(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeFilter", field.Name) }, } return fc, nil } -func (ec *executionContext) _NavigatorSettings_showOnlyEntities(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_showOnlyEntities(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ShowOnlyEntities, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _NavigatorSettings_showSystemObjects(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorSettings_showSystemObjects, + func(ctx context.Context) (any, error) { + return obj.ShowSystemObjects, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorSettings_showOnlyEntities(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorSettings_showSystemObjects(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorSettings", Field: field, @@ -21219,38 +25071,25 @@ func (ec *executionContext) fieldContext_NavigatorSettings_showOnlyEntities(ctx return fc, nil } -func (ec *executionContext) _NavigatorSettings_mergeEntities(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_mergeEntities(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MergeEntities, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _NavigatorSettings_showUtilityObjects(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorSettings_showUtilityObjects, + func(ctx context.Context) (any, error) { + return obj.ShowUtilityObjects, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorSettings_mergeEntities(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorSettings_showUtilityObjects(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorSettings", Field: field, @@ -21263,38 +25102,87 @@ func (ec *executionContext) fieldContext_NavigatorSettings_mergeEntities(ctx con return fc, nil } -func (ec *executionContext) _NavigatorSettings_hideFolders(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_hideFolders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HideFolders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _NavigatorSettings_showOnlyEntities(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorSettings_showOnlyEntities, + func(ctx context.Context) (any, error) { + return obj.ShowOnlyEntities, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_NavigatorSettings_showOnlyEntities(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorSettings", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _NavigatorSettings_mergeEntities(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorSettings_mergeEntities, + func(ctx context.Context) (any, error) { + return obj.MergeEntities, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_NavigatorSettings_mergeEntities(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NavigatorSettings", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _NavigatorSettings_hideFolders(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorSettings_hideFolders, + func(ctx context.Context) (any, error) { + return obj.HideFolders, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorSettings_hideFolders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorSettings_hideFolders(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorSettings", Field: field, @@ -21308,37 +25196,24 @@ func (ec *executionContext) fieldContext_NavigatorSettings_hideFolders(ctx conte } func (ec *executionContext) _NavigatorSettings_hideSchemas(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_hideSchemas(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HideSchemas, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorSettings_hideSchemas, + func(ctx context.Context) (any, error) { + return obj.HideSchemas, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorSettings_hideSchemas(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorSettings_hideSchemas(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorSettings", Field: field, @@ -21352,37 +25227,24 @@ func (ec *executionContext) fieldContext_NavigatorSettings_hideSchemas(ctx conte } func (ec *executionContext) _NavigatorSettings_hideVirtualModel(ctx context.Context, field graphql.CollectedField, obj *model.NavigatorSettings) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NavigatorSettings_hideVirtualModel(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HideVirtualModel, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NavigatorSettings_hideVirtualModel, + func(ctx context.Context) (any, error) { + return obj.HideVirtualModel, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NavigatorSettings_hideVirtualModel(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NavigatorSettings_hideVirtualModel(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NavigatorSettings", Field: field, @@ -21396,34 +25258,24 @@ func (ec *executionContext) fieldContext_NavigatorSettings_hideVirtualModel(ctx } func (ec *executionContext) _NetworkEndpointInfo_message(ctx context.Context, field graphql.CollectedField, obj *model.NetworkEndpointInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkEndpointInfo_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkEndpointInfo_message, + func(ctx context.Context) (any, error) { + return obj.Message, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkEndpointInfo_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkEndpointInfo_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkEndpointInfo", Field: field, @@ -21437,34 +25289,24 @@ func (ec *executionContext) fieldContext_NetworkEndpointInfo_message(ctx context } func (ec *executionContext) _NetworkEndpointInfo_clientVersion(ctx context.Context, field graphql.CollectedField, obj *model.NetworkEndpointInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkEndpointInfo_clientVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ClientVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkEndpointInfo_clientVersion, + func(ctx context.Context) (any, error) { + return obj.ClientVersion, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkEndpointInfo_clientVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkEndpointInfo_clientVersion(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkEndpointInfo", Field: field, @@ -21478,34 +25320,24 @@ func (ec *executionContext) fieldContext_NetworkEndpointInfo_clientVersion(ctx c } func (ec *executionContext) _NetworkEndpointInfo_serverVersion(ctx context.Context, field graphql.CollectedField, obj *model.NetworkEndpointInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkEndpointInfo_serverVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkEndpointInfo_serverVersion, + func(ctx context.Context) (any, error) { + return obj.ServerVersion, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkEndpointInfo_serverVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkEndpointInfo_serverVersion(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkEndpointInfo", Field: field, @@ -21519,37 +25351,24 @@ func (ec *executionContext) fieldContext_NetworkEndpointInfo_serverVersion(ctx c } func (ec *executionContext) _NetworkHandlerConfig_id(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21563,37 +25382,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_id(ctx context.Con } func (ec *executionContext) _NetworkHandlerConfig_enabled(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_enabled, + func(ctx context.Context) (any, error) { + return obj.Enabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_enabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21607,37 +25413,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_enabled(ctx contex } func (ec *executionContext) _NetworkHandlerConfig_authType(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_authType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.NetworkHandlerAuthType) - fc.Result = res - return ec.marshalNNetworkHandlerAuthType2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_authType, + func(ctx context.Context) (any, error) { + return obj.AuthType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNNetworkHandlerAuthType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_authType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_authType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21651,34 +25444,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_authType(ctx conte } func (ec *executionContext) _NetworkHandlerConfig_userName(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_userName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_userName, + func(ctx context.Context) (any, error) { + return obj.UserName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_userName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_userName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21692,34 +25475,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_userName(ctx conte } func (ec *executionContext) _NetworkHandlerConfig_password(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_password(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Password, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_password, + func(ctx context.Context) (any, error) { + return obj.Password, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_password(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_password(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21733,34 +25506,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_password(ctx conte } func (ec *executionContext) _NetworkHandlerConfig_key(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_key(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Key, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_key, + func(ctx context.Context) (any, error) { + return obj.Key, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_key(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_key(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21774,37 +25537,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_key(ctx context.Co } func (ec *executionContext) _NetworkHandlerConfig_savePassword(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_savePassword(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SavePassword, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_savePassword, + func(ctx context.Context) (any, error) { + return obj.SavePassword, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_savePassword(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_savePassword(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21818,37 +25568,55 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_savePassword(ctx c } func (ec *executionContext) _NetworkHandlerConfig_properties(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerConfig_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_NetworkHandlerConfig_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "NetworkHandlerConfig", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _NetworkHandlerConfig_secureProperties(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerConfig_secureProperties, + func(ctx context.Context) (any, error) { + return obj.SecureProperties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerConfig_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerConfig_secureProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerConfig", Field: field, @@ -21862,37 +25630,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerConfig_properties(ctx con } func (ec *executionContext) _NetworkHandlerDescriptor_id(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerDescriptor_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerDescriptor", Field: field, @@ -21906,37 +25661,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_id(ctx context } func (ec *executionContext) _NetworkHandlerDescriptor_codeName(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_codeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CodeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerDescriptor_codeName, + func(ctx context.Context) (any, error) { + return obj.CodeName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_codeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_codeName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerDescriptor", Field: field, @@ -21950,37 +25692,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_codeName(ctx c } func (ec *executionContext) _NetworkHandlerDescriptor_label(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerDescriptor_label, + func(ctx context.Context) (any, error) { + return obj.Label, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerDescriptor", Field: field, @@ -21994,34 +25723,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_label(ctx cont } func (ec *executionContext) _NetworkHandlerDescriptor_description(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerDescriptor_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerDescriptor", Field: field, @@ -22035,37 +25754,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_description(ct } func (ec *executionContext) _NetworkHandlerDescriptor_secured(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_secured(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Secured, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerDescriptor_secured, + func(ctx context.Context) (any, error) { + return obj.Secured, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_secured(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_secured(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerDescriptor", Field: field, @@ -22079,34 +25785,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_secured(ctx co } func (ec *executionContext) _NetworkHandlerDescriptor_type(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.NetworkHandlerType) - fc.Result = res - return ec.marshalONetworkHandlerType2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerDescriptor_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalONetworkHandlerType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerType, + true, + false, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerDescriptor", Field: field, @@ -22120,37 +25816,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_type(ctx conte } func (ec *executionContext) _NetworkHandlerDescriptor_properties(ctx context.Context, field graphql.CollectedField, obj *model.NetworkHandlerDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_NetworkHandlerDescriptor_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_NetworkHandlerDescriptor_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "NetworkHandlerDescriptor", Field: field, @@ -22164,6 +25847,8 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_properties(ctx return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -22180,6 +25865,14 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_properties(ctx return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -22188,34 +25881,24 @@ func (ec *executionContext) fieldContext_NetworkHandlerDescriptor_properties(ctx } func (ec *executionContext) _ObjectDescriptor_id(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDescriptor_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDescriptor_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDescriptor_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDescriptor", Field: field, @@ -22229,34 +25912,24 @@ func (ec *executionContext) fieldContext_ObjectDescriptor_id(ctx context.Context } func (ec *executionContext) _ObjectDescriptor_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDescriptor_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDescriptor_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDescriptor_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDescriptor", Field: field, @@ -22270,34 +25943,24 @@ func (ec *executionContext) fieldContext_ObjectDescriptor_displayName(ctx contex } func (ec *executionContext) _ObjectDescriptor_fullName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_fullName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDescriptor_fullName, + func(ctx context.Context) (any, error) { + return obj.FullName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDescriptor_fullName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDescriptor_fullName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDescriptor", Field: field, @@ -22311,34 +25974,24 @@ func (ec *executionContext) fieldContext_ObjectDescriptor_fullName(ctx context.C } func (ec *executionContext) _ObjectDescriptor_uniqueName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_uniqueName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UniqueName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDescriptor_uniqueName, + func(ctx context.Context) (any, error) { + return obj.UniqueName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDescriptor_uniqueName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDescriptor_uniqueName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDescriptor", Field: field, @@ -22352,34 +26005,24 @@ func (ec *executionContext) fieldContext_ObjectDescriptor_uniqueName(ctx context } func (ec *executionContext) _ObjectDescriptor_description(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDescriptor_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDescriptor_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDescriptor_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDescriptor", Field: field, @@ -22393,34 +26036,24 @@ func (ec *executionContext) fieldContext_ObjectDescriptor_description(ctx contex } func (ec *executionContext) _ObjectDescriptor_value(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDescriptor) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDescriptor_value(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Value, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDescriptor_value, + func(ctx context.Context) (any, error) { + return obj.Value, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDescriptor_value(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDescriptor_value(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDescriptor", Field: field, @@ -22434,34 +26067,24 @@ func (ec *executionContext) fieldContext_ObjectDescriptor_value(ctx context.Cont } func (ec *executionContext) _ObjectDetails_id(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDetails_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDetails_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDetails_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDetails", Field: field, @@ -22475,34 +26098,24 @@ func (ec *executionContext) fieldContext_ObjectDetails_id(ctx context.Context, f } func (ec *executionContext) _ObjectDetails_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDetails_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDetails_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDetails_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDetails", Field: field, @@ -22516,34 +26129,24 @@ func (ec *executionContext) fieldContext_ObjectDetails_displayName(ctx context.C } func (ec *executionContext) _ObjectDetails_description(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDetails_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDetails_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDetails_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDetails", Field: field, @@ -22557,34 +26160,24 @@ func (ec *executionContext) fieldContext_ObjectDetails_description(ctx context.C } func (ec *executionContext) _ObjectDetails_value(ctx context.Context, field graphql.CollectedField, obj *model.ObjectDetails) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectDetails_value(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Value, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectDetails_value, + func(ctx context.Context) (any, error) { + return obj.Value, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectDetails_value(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectDetails_value(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectDetails", Field: field, @@ -22598,37 +26191,24 @@ func (ec *executionContext) fieldContext_ObjectDetails_value(ctx context.Context } func (ec *executionContext) _ObjectOrigin_type(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectOrigin_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ObjectOrigin_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectOrigin_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectOrigin", Field: field, @@ -22642,34 +26222,24 @@ func (ec *executionContext) fieldContext_ObjectOrigin_type(ctx context.Context, } func (ec *executionContext) _ObjectOrigin_subType(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_subType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectOrigin_subType, + func(ctx context.Context) (any, error) { + return obj.SubType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectOrigin_subType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectOrigin_subType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectOrigin", Field: field, @@ -22683,37 +26253,24 @@ func (ec *executionContext) fieldContext_ObjectOrigin_subType(ctx context.Contex } func (ec *executionContext) _ObjectOrigin_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectOrigin_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ObjectOrigin_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectOrigin_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectOrigin", Field: field, @@ -22727,34 +26284,24 @@ func (ec *executionContext) fieldContext_ObjectOrigin_displayName(ctx context.Co } func (ec *executionContext) _ObjectOrigin_icon(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectOrigin_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectOrigin_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectOrigin_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectOrigin", Field: field, @@ -22768,34 +26315,24 @@ func (ec *executionContext) fieldContext_ObjectOrigin_icon(ctx context.Context, } func (ec *executionContext) _ObjectOrigin_configuration(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_configuration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Configuration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectOrigin_configuration, + func(ctx context.Context) (any, error) { + return obj.Configuration, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectOrigin_configuration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectOrigin_configuration(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectOrigin", Field: field, @@ -22809,34 +26346,24 @@ func (ec *executionContext) fieldContext_ObjectOrigin_configuration(ctx context. } func (ec *executionContext) _ObjectOrigin_details(ctx context.Context, field graphql.CollectedField, obj *model.ObjectOrigin) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectOrigin_details(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Details, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectOrigin_details, + func(ctx context.Context) (any, error) { + return obj.Details, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectOrigin_details(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectOrigin_details(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectOrigin", Field: field, @@ -22850,6 +26377,8 @@ func (ec *executionContext) fieldContext_ObjectOrigin_details(ctx context.Contex return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -22866,6 +26395,14 @@ func (ec *executionContext) fieldContext_ObjectOrigin_details(ctx context.Contex return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -22874,34 +26411,24 @@ func (ec *executionContext) fieldContext_ObjectOrigin_details(ctx context.Contex } func (ec *executionContext) _ObjectPropertyInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -22915,34 +26442,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_id(ctx context.Conte } func (ec *executionContext) _ObjectPropertyInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -22956,34 +26473,71 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_displayName(ctx cont } func (ec *executionContext) _ObjectPropertyInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ObjectPropertyInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ObjectPropertyInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _ObjectPropertyInfo_hint(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_hint, + func(ctx context.Context) (any, error) { + return obj.Hint, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.2.3") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_hint(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -22997,34 +26551,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_description(ctx cont } func (ec *executionContext) _ObjectPropertyInfo_category(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_category(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Category, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_category, + func(ctx context.Context) (any, error) { + return obj.Category, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_category(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_category(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23038,34 +26582,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_category(ctx context } func (ec *executionContext) _ObjectPropertyInfo_dataType(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_dataType, + func(ctx context.Context) (any, error) { + return obj.DataType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_dataType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_dataType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23079,34 +26613,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_dataType(ctx context } func (ec *executionContext) _ObjectPropertyInfo_value(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_value(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Value, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_value, + func(ctx context.Context) (any, error) { + return obj.Value, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_value(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_value(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23120,34 +26644,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_value(ctx context.Co } func (ec *executionContext) _ObjectPropertyInfo_validValues(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ValidValues, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]interface{}) - fc.Result = res - return ec.marshalOObject2ᚕinterface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_validValues, + func(ctx context.Context) (any, error) { + return obj.ValidValues, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2ᚕinterface, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_validValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_validValues(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23161,34 +26675,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_validValues(ctx cont } func (ec *executionContext) _ObjectPropertyInfo_defaultValue(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultValue, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_defaultValue, + func(ctx context.Context) (any, error) { + return obj.DefaultValue, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_defaultValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_defaultValue(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23202,37 +26706,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_defaultValue(ctx con } func (ec *executionContext) _ObjectPropertyInfo_length(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_length(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Length, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(model.ObjectPropertyLength) - fc.Result = res - return ec.marshalNObjectPropertyLength2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyLength(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_length, + func(ctx context.Context) (any, error) { + return obj.Length, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyLength2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyLength, + true, + true, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_length(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_length(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23246,37 +26737,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_length(ctx context.C } func (ec *executionContext) _ObjectPropertyInfo_features(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_features(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Features, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_features, + func(ctx context.Context) (any, error) { + return obj.Features, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_features(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_features(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23290,37 +26768,24 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_features(ctx context } func (ec *executionContext) _ObjectPropertyInfo_order(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ObjectPropertyInfo_order(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Order, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_order, + func(ctx context.Context) (any, error) { + return obj.Order, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_ObjectPropertyInfo_order(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_order(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ObjectPropertyInfo", Field: field, @@ -23333,128 +26798,105 @@ func (ec *executionContext) fieldContext_ObjectPropertyInfo_order(ctx context.Co return fc, nil } -func (ec *executionContext) _ProductInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _ObjectPropertyInfo_supportedConfigurationTypes(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes, + func(ctx context.Context) (any, error) { + return obj.SupportedConfigurationTypes, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕstringᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_ProductInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "ObjectPropertyInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ProductInfo_version(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_version(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Version, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _ObjectPropertyInfo_required(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_required, + func(ctx context.Context) (any, error) { + return obj.Required, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.1") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ProductInfo_version(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_required(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "ObjectPropertyInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ProductInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _ObjectPropertyInfo_scopes(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_scopes, + func(ctx context.Context) (any, error) { + return obj.Scopes, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚕstringᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_ProductInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_scopes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "ObjectPropertyInfo", Field: field, IsMethod: false, IsResolver: false, @@ -23465,936 +26907,1766 @@ func (ec *executionContext) fieldContext_ProductInfo_name(ctx context.Context, f return fc, nil } -func (ec *executionContext) _ProductInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _ObjectPropertyInfo_conditions(ctx context.Context, field graphql.CollectedField, obj *model.ObjectPropertyInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ObjectPropertyInfo_conditions, + func(ctx context.Context) (any, error) { + return obj.Conditions, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.1") + if err != nil { + var zeroVal []*model.Condition + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.Condition + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.1") + if err != nil { + var zeroVal []*model.Condition + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.Condition + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOCondition2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConditionᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_ProductInfo_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ObjectPropertyInfo_conditions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "ObjectPropertyInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + switch field.Name { + case "expression": + return ec.fieldContext_Condition_expression(ctx, field) + case "conditionType": + return ec.fieldContext_Condition_conditionType(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Condition", field.Name) }, } return fc, nil } -func (ec *executionContext) _ProductInfo_buildTime(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_buildTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.BuildTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _PasswordPolicyConfig_minLength(ctx context.Context, field graphql.CollectedField, obj *model.PasswordPolicyConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_PasswordPolicyConfig_minLength, + func(ctx context.Context) (any, error) { + return obj.MinLength, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal int + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal int + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_ProductInfo_buildTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_PasswordPolicyConfig_minLength(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "PasswordPolicyConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ProductInfo_releaseTime(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_releaseTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReleaseTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _PasswordPolicyConfig_minNumberCount(ctx context.Context, field graphql.CollectedField, obj *model.PasswordPolicyConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_PasswordPolicyConfig_minNumberCount, + func(ctx context.Context) (any, error) { + return obj.MinNumberCount, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal int + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal int + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_ProductInfo_releaseTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_PasswordPolicyConfig_minNumberCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "PasswordPolicyConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ProductInfo_licenseInfo(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_licenseInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseInfo, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _PasswordPolicyConfig_minSymbolCount(ctx context.Context, field graphql.CollectedField, obj *model.PasswordPolicyConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_PasswordPolicyConfig_minSymbolCount, + func(ctx context.Context) (any, error) { + return obj.MinSymbolCount, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal int + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal int + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_ProductInfo_licenseInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_PasswordPolicyConfig_minSymbolCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "PasswordPolicyConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ProductInfo_latestVersionInfo(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ProductInfo_latestVersionInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LatestVersionInfo, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _PasswordPolicyConfig_requireMixedCase(ctx context.Context, field graphql.CollectedField, obj *model.PasswordPolicyConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_PasswordPolicyConfig_requireMixedCase, + func(ctx context.Context) (any, error) { + return obj.RequireMixedCase, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ProductInfo_latestVersionInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_PasswordPolicyConfig_requireMixedCase(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ProductInfo", + Object: "PasswordPolicyConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _Query_listUsers(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listUsers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListUsers(rctx, fc.Args["userId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminUserInfo) - fc.Result = res - return ec.marshalNAdminUserInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfoᚄ(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_listUsers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "userId": - return ec.fieldContext_AdminUserInfo_userId(ctx, field) - case "metaParameters": - return ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) - case "configurationParameters": - return ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) - case "grantedRoles": - return ec.fieldContext_AdminUserInfo_grantedRoles(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) - case "origins": - return ec.fieldContext_AdminUserInfo_origins(ctx, field) - case "linkedAuthProviders": - return ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) - case "enabled": - return ec.fieldContext_AdminUserInfo_enabled(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminUserInfo", field.Name) + return nil, errors.New("field of type ID does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_listUsers_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_listRoles(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listRoles(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListRoles(rctx, fc.Args["roleId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminRoleInfo) - fc.Result = res - return ec.marshalNAdminRoleInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminRoleInfoᚄ(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_version(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_version, + func(ctx context.Context) (any, error) { + return obj.Version, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_listRoles(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_version(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "roleId": - return ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - case "roleName": - return ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - case "description": - return ec.fieldContext_AdminRoleInfo_description(ctx, field) - case "grantedUsers": - return ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - case "rolePermissions": - return ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminRoleInfo", field.Name) + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_listRoles_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_listPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listPermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListPermissions(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminPermissionInfo) - fc.Result = res - return ec.marshalNAdminPermissionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfoᚄ(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_listPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_AdminPermissionInfo_id(ctx, field) - case "label": - return ec.fieldContext_AdminPermissionInfo_label(ctx, field) - case "description": - return ec.fieldContext_AdminPermissionInfo_description(ctx, field) - case "provider": - return ec.fieldContext_AdminPermissionInfo_provider(ctx, field) - case "category": - return ec.fieldContext_AdminPermissionInfo_category(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminPermissionInfo", field.Name) + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _Query_createUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_createUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CreateUser(rctx, fc.Args["userId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminUserInfo) - fc.Result = res - return ec.marshalNAdminUserInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_createUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "userId": - return ec.fieldContext_AdminUserInfo_userId(ctx, field) - case "metaParameters": - return ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) - case "configurationParameters": - return ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) - case "grantedRoles": - return ec.fieldContext_AdminUserInfo_grantedRoles(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) - case "origins": - return ec.fieldContext_AdminUserInfo_origins(ctx, field) - case "linkedAuthProviders": - return ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) - case "enabled": - return ec.fieldContext_AdminUserInfo_enabled(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminUserInfo", field.Name) + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_createUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_deleteUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteUser(rctx, fc.Args["userId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_buildTime(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_buildTime, + func(ctx context.Context) (any, error) { + return obj.BuildTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_deleteUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_buildTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_createRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_createRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CreateRole(rctx, fc.Args["roleId"].(string), fc.Args["roleName"].(*string), fc.Args["description"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminRoleInfo) - fc.Result = res - return ec.marshalNAdminRoleInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminRoleInfo(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_releaseTime(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_releaseTime, + func(ctx context.Context) (any, error) { + return obj.ReleaseTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_createRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_releaseTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "roleId": - return ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - case "roleName": - return ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - case "description": - return ec.fieldContext_AdminRoleInfo_description(ctx, field) - case "grantedUsers": - return ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - case "rolePermissions": - return ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminRoleInfo", field.Name) + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_createRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_updateRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_updateRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().UpdateRole(rctx, fc.Args["roleId"].(string), fc.Args["roleName"].(*string), fc.Args["description"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminRoleInfo) - fc.Result = res - return ec.marshalNAdminRoleInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminRoleInfo(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_licenseInfo(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_licenseInfo, + func(ctx context.Context) (any, error) { + return obj.LicenseInfo, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_updateRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_licenseInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "roleId": - return ec.fieldContext_AdminRoleInfo_roleId(ctx, field) - case "roleName": - return ec.fieldContext_AdminRoleInfo_roleName(ctx, field) - case "description": - return ec.fieldContext_AdminRoleInfo_description(ctx, field) - case "grantedUsers": - return ec.fieldContext_AdminRoleInfo_grantedUsers(ctx, field) - case "grantedConnections": - return ec.fieldContext_AdminRoleInfo_grantedConnections(ctx, field) - case "rolePermissions": - return ec.fieldContext_AdminRoleInfo_rolePermissions(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminRoleInfo", field.Name) + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_updateRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_deleteRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteRole(rctx, fc.Args["roleId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_latestVersionInfo(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_latestVersionInfo, + func(ctx context.Context) (any, error) { + return obj.LatestVersionInfo, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_deleteRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_latestVersionInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_grantUserRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_grantUserRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().GrantUserRole(rctx, fc.Args["userId"].(string), fc.Args["roleId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ProductInfo_productPurchaseURL(ctx context.Context, field graphql.CollectedField, obj *model.ProductInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductInfo_productPurchaseURL, + func(ctx context.Context) (any, error) { + return obj.ProductPurchaseURL, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_grantUserRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductInfo_productPurchaseURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductInfo", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_grantUserRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_revokeUserRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_revokeUserRole(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RevokeUserRole(rctx, fc.Args["userId"].(string), fc.Args["roleId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ProductSettings_groups(ctx context.Context, field graphql.CollectedField, obj *model.ProductSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductSettings_groups, + func(ctx context.Context) (any, error) { + return obj.Groups, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal []*model.ProductSettingsGroup + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.ProductSettingsGroup + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal []*model.ProductSettingsGroup + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.ProductSettingsGroup + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNProductSettingsGroup2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductSettingsGroupᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_revokeUserRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductSettings_groups(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductSettings", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + switch field.Name { + case "id": + return ec.fieldContext_ProductSettingsGroup_id(ctx, field) + case "displayName": + return ec.fieldContext_ProductSettingsGroup_displayName(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ProductSettingsGroup", field.Name) }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_revokeUserRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } -func (ec *executionContext) _Query_setSubjectPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setSubjectPermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetSubjectPermissions(rctx, fc.Args["roleId"].(string), fc.Args["permissions"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminPermissionInfo) - fc.Result = res - return ec.marshalNAdminPermissionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfoᚄ(ctx, field.Selections, res) +func (ec *executionContext) _ProductSettings_settings(ctx context.Context, field graphql.CollectedField, obj *model.ProductSettings) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductSettings_settings, + func(ctx context.Context) (any, error) { + return obj.Settings, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_setSubjectPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ProductSettings_settings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "Query", + Object: "ProductSettings", Field: field, - IsMethod: true, - IsResolver: true, + IsMethod: false, + IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { case "id": - return ec.fieldContext_AdminPermissionInfo_id(ctx, field) - case "label": - return ec.fieldContext_AdminPermissionInfo_label(ctx, field) + return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) + case "displayName": + return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": - return ec.fieldContext_AdminPermissionInfo_description(ctx, field) - case "provider": - return ec.fieldContext_AdminPermissionInfo_provider(ctx, field) + return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": - return ec.fieldContext_AdminPermissionInfo_category(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminPermissionInfo", field.Name) - }, - } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() + return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) + case "dataType": + return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) + case "value": + return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) + case "validValues": + return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) + case "defaultValue": + return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) + case "length": + return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) + case "features": + return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) + case "order": + return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _ProductSettingsGroup_id(ctx context.Context, field graphql.CollectedField, obj *model.ProductSettingsGroup) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductSettingsGroup_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProductSettingsGroup_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProductSettingsGroup", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProductSettingsGroup_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ProductSettingsGroup) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProductSettingsGroup_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProductSettingsGroup_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProductSettingsGroup", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_global(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_global, + func(ctx context.Context) (any, error) { + return obj.Global, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_global(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_shared(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_shared, + func(ctx context.Context) (any, error) { + return obj.Shared, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_shared(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_description(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_canEditDataSources(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_canEditDataSources, + func(ctx context.Context) (any, error) { + return obj.CanEditDataSources, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_canEditDataSources(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_canViewDataSources(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_canViewDataSources, + func(ctx context.Context) (any, error) { + return obj.CanViewDataSources, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_canViewDataSources(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_canEditResources(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_canEditResources, + func(ctx context.Context) (any, error) { + return obj.CanEditResources, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_canEditResources(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_canViewResources(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_canViewResources, + func(ctx context.Context) (any, error) { + return obj.CanViewResources, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_canViewResources(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _ProjectInfo_resourceTypes(ctx context.Context, field graphql.CollectedField, obj *model.ProjectInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ProjectInfo_resourceTypes, + func(ctx context.Context) (any, error) { + return obj.ResourceTypes, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNRMResourceType2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceTypeᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ProjectInfo_resourceTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ProjectInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_RMResourceType_id(ctx, field) + case "displayName": + return ec.fieldContext_RMResourceType_displayName(ctx, field) + case "icon": + return ec.fieldContext_RMResourceType_icon(ctx, field) + case "fileExtensions": + return ec.fieldContext_RMResourceType_fileExtensions(ctx, field) + case "rootFolder": + return ec.fieldContext_RMResourceType_rootFolder(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type RMResourceType", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_adminUserInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_adminUserInfo, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().AdminUserInfo(ctx, fc.Args["userId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_adminUserInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "userId": + return ec.fieldContext_AdminUserInfo_userId(ctx, field) + case "metaParameters": + return ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) + case "configurationParameters": + return ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) + case "grantedTeams": + return ec.fieldContext_AdminUserInfo_grantedTeams(ctx, field) + case "grantedConnections": + return ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) + case "origins": + return ec.fieldContext_AdminUserInfo_origins(ctx, field) + case "linkedAuthProviders": + return ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) + case "enabled": + return ec.fieldContext_AdminUserInfo_enabled(ctx, field) + case "authRole": + return ec.fieldContext_AdminUserInfo_authRole(ctx, field) + case "disableDate": + return ec.fieldContext_AdminUserInfo_disableDate(ctx, field) + case "disabledBy": + return ec.fieldContext_AdminUserInfo_disabledBy(ctx, field) + case "disableReason": + return ec.fieldContext_AdminUserInfo_disableReason(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminUserInfo", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setSubjectPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_adminUserInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_setUserCredentials(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setUserCredentials(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_listUsers(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listUsers, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ListUsers(ctx, fc.Args["page"].(model.PageInput), fc.Args["filter"].(model.AdminUserFilterInput)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminUserInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_listUsers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "userId": + return ec.fieldContext_AdminUserInfo_userId(ctx, field) + case "metaParameters": + return ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) + case "configurationParameters": + return ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) + case "grantedTeams": + return ec.fieldContext_AdminUserInfo_grantedTeams(ctx, field) + case "grantedConnections": + return ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) + case "origins": + return ec.fieldContext_AdminUserInfo_origins(ctx, field) + case "linkedAuthProviders": + return ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) + case "enabled": + return ec.fieldContext_AdminUserInfo_enabled(ctx, field) + case "authRole": + return ec.fieldContext_AdminUserInfo_authRole(ctx, field) + case "disableDate": + return ec.fieldContext_AdminUserInfo_disableDate(ctx, field) + case "disabledBy": + return ec.fieldContext_AdminUserInfo_disabledBy(ctx, field) + case "disableReason": + return ec.fieldContext_AdminUserInfo_disableReason(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminUserInfo", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_listUsers_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_listTeams(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listTeams, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ListTeams(ctx, fc.Args["teamId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminTeamInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminTeamInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_listTeams(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "teamId": + return ec.fieldContext_AdminTeamInfo_teamId(ctx, field) + case "teamName": + return ec.fieldContext_AdminTeamInfo_teamName(ctx, field) + case "description": + return ec.fieldContext_AdminTeamInfo_description(ctx, field) + case "metaParameters": + return ec.fieldContext_AdminTeamInfo_metaParameters(ctx, field) + case "grantedUsers": + return ec.fieldContext_AdminTeamInfo_grantedUsers(ctx, field) + case "grantedUsersInfo": + return ec.fieldContext_AdminTeamInfo_grantedUsersInfo(ctx, field) + case "grantedConnections": + return ec.fieldContext_AdminTeamInfo_grantedConnections(ctx, field) + case "teamPermissions": + return ec.fieldContext_AdminTeamInfo_teamPermissions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminTeamInfo", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_listTeams_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_listPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listPermissions, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ListPermissions(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminPermissionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_listPermissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_AdminPermissionInfo_id(ctx, field) + case "label": + return ec.fieldContext_AdminPermissionInfo_label(ctx, field) + case "description": + return ec.fieldContext_AdminPermissionInfo_description(ctx, field) + case "provider": + return ec.fieldContext_AdminPermissionInfo_provider(ctx, field) + case "category": + return ec.fieldContext_AdminPermissionInfo_category(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminPermissionInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_listAuthRoles(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listAuthRoles, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ListAuthRoles(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_listAuthRoles(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_listTeamRoles(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listTeamRoles, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ListTeamRoles(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_listTeamRoles(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_listTeamMetaParameters(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listTeamMetaParameters, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ListTeamMetaParameters(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_listTeamMetaParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) + case "displayName": + return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) + case "description": + return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) + case "category": + return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) + case "dataType": + return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) + case "value": + return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) + case "validValues": + return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) + case "defaultValue": + return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) + case "length": + return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) + case "features": + return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) + case "order": + return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_createUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_createUser, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().CreateUser(ctx, fc.Args["userId"].(string), fc.Args["enabled"].(bool), fc.Args["authRole"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_createUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "userId": + return ec.fieldContext_AdminUserInfo_userId(ctx, field) + case "metaParameters": + return ec.fieldContext_AdminUserInfo_metaParameters(ctx, field) + case "configurationParameters": + return ec.fieldContext_AdminUserInfo_configurationParameters(ctx, field) + case "grantedTeams": + return ec.fieldContext_AdminUserInfo_grantedTeams(ctx, field) + case "grantedConnections": + return ec.fieldContext_AdminUserInfo_grantedConnections(ctx, field) + case "origins": + return ec.fieldContext_AdminUserInfo_origins(ctx, field) + case "linkedAuthProviders": + return ec.fieldContext_AdminUserInfo_linkedAuthProviders(ctx, field) + case "enabled": + return ec.fieldContext_AdminUserInfo_enabled(ctx, field) + case "authRole": + return ec.fieldContext_AdminUserInfo_authRole(ctx, field) + case "disableDate": + return ec.fieldContext_AdminUserInfo_disableDate(ctx, field) + case "disabledBy": + return ec.fieldContext_AdminUserInfo_disabledBy(ctx, field) + case "disableReason": + return ec.fieldContext_AdminUserInfo_disableReason(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminUserInfo", field.Name) + }, } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_createUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_deleteUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_deleteUser, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DeleteUser(ctx, fc.Args["userId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_deleteUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetUserCredentials(rctx, fc.Args["userId"].(string), fc.Args["providerId"].(string), - func() interface{} { - if fc.Args["credentials"] == nil { - return nil - } - return fc.Args["credentials"].(interface{}) - }()) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_deleteUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _Query_createTeam(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_createTeam, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().CreateTeam(ctx, fc.Args["teamId"].(string), fc.Args["teamName"].(*string), fc.Args["description"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminTeamInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminTeamInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_createTeam(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "teamId": + return ec.fieldContext_AdminTeamInfo_teamId(ctx, field) + case "teamName": + return ec.fieldContext_AdminTeamInfo_teamName(ctx, field) + case "description": + return ec.fieldContext_AdminTeamInfo_description(ctx, field) + case "metaParameters": + return ec.fieldContext_AdminTeamInfo_metaParameters(ctx, field) + case "grantedUsers": + return ec.fieldContext_AdminTeamInfo_grantedUsers(ctx, field) + case "grantedUsersInfo": + return ec.fieldContext_AdminTeamInfo_grantedUsersInfo(ctx, field) + case "grantedConnections": + return ec.fieldContext_AdminTeamInfo_grantedConnections(ctx, field) + case "teamPermissions": + return ec.fieldContext_AdminTeamInfo_teamPermissions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminTeamInfo", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_createTeam_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_updateTeam(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_updateTeam, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().UpdateTeam(ctx, fc.Args["teamId"].(string), fc.Args["teamName"].(*string), fc.Args["description"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminTeamInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminTeamInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_updateTeam(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "teamId": + return ec.fieldContext_AdminTeamInfo_teamId(ctx, field) + case "teamName": + return ec.fieldContext_AdminTeamInfo_teamName(ctx, field) + case "description": + return ec.fieldContext_AdminTeamInfo_description(ctx, field) + case "metaParameters": + return ec.fieldContext_AdminTeamInfo_metaParameters(ctx, field) + case "grantedUsers": + return ec.fieldContext_AdminTeamInfo_grantedUsers(ctx, field) + case "grantedUsersInfo": + return ec.fieldContext_AdminTeamInfo_grantedUsersInfo(ctx, field) + case "grantedConnections": + return ec.fieldContext_AdminTeamInfo_grantedConnections(ctx, field) + case "teamPermissions": + return ec.fieldContext_AdminTeamInfo_teamPermissions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminTeamInfo", field.Name) + }, } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_updateTeam_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_deleteTeam(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_deleteTeam, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DeleteTeam(ctx, fc.Args["teamId"].(string), fc.Args["force"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_deleteTeam(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_deleteTeam_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_grantUserTeam(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_grantUserTeam, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().GrantUserTeam(ctx, fc.Args["userId"].(string), fc.Args["teamId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_setUserCredentials(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_grantUserTeam(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -24411,42 +28683,33 @@ func (ec *executionContext) fieldContext_Query_setUserCredentials(ctx context.Co } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setUserCredentials_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_grantUserTeam_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_enableUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_enableUser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().EnableUser(rctx, fc.Args["userId"].(string), fc.Args["enabled"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _Query_revokeUserTeam(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_revokeUserTeam, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().RevokeUserTeam(ctx, fc.Args["userId"].(string), fc.Args["teamId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_enableUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_revokeUserTeam(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -24463,45 +28726,33 @@ func (ec *executionContext) fieldContext_Query_enableUser(ctx context.Context, f } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_enableUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_revokeUserTeam_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_allConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_allConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AllConnections(rctx, fc.Args["id"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) +func (ec *executionContext) _Query_setSubjectPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setSubjectPermissions, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetSubjectPermissions(ctx, fc.Args["subjectId"].(string), fc.Args["permissions"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminPermissionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_allConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_setSubjectPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -24510,69 +28761,17 @@ func (ec *executionContext) fieldContext_Query_allConnections(ctx context.Contex Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) + return ec.fieldContext_AdminPermissionInfo_id(ctx, field) + case "label": + return ec.fieldContext_AdminPermissionInfo_label(ctx, field) case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + return ec.fieldContext_AdminPermissionInfo_description(ctx, field) + case "provider": + return ec.fieldContext_AdminPermissionInfo_provider(ctx, field) + case "category": + return ec.fieldContext_AdminPermissionInfo_category(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type AdminPermissionInfo", field.Name) }, } defer func() { @@ -24582,64 +28781,89 @@ func (ec *executionContext) fieldContext_Query_allConnections(ctx context.Contex } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_allConnections_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_setSubjectPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_searchConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_searchConnections(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_setUserCredentials(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setUserCredentials, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetUserCredentials(ctx, fc.Args["userId"].(string), fc.Args["providerId"].(string), + func() any { + if fc.Args["credentials"] == nil { + return nil + } + return fc.Args["credentials"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_setUserCredentials(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SearchConnections(rctx, fc.Args["hostNames"].([]string)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_setUserCredentials_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.([]*model.AdminConnectionSearchInfo) - fc.Result = res - return ec.marshalNAdminConnectionSearchInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfoᚄ(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Query_searchConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Query_deleteUserCredentials(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_deleteUserCredentials, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DeleteUserCredentials(ctx, fc.Args["userId"].(string), fc.Args["providerId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_deleteUserCredentials(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, IsMethod: true, IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "displayName": - return ec.fieldContext_AdminConnectionSearchInfo_displayName(ctx, field) - case "host": - return ec.fieldContext_AdminConnectionSearchInfo_host(ctx, field) - case "port": - return ec.fieldContext_AdminConnectionSearchInfo_port(ctx, field) - case "possibleDrivers": - return ec.fieldContext_AdminConnectionSearchInfo_possibleDrivers(ctx, field) - case "defaultDriver": - return ec.fieldContext_AdminConnectionSearchInfo_defaultDriver(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminConnectionSearchInfo", field.Name) + return nil, errors.New("field of type Boolean does not have child fields") }, } defer func() { @@ -24649,116 +28873,83 @@ func (ec *executionContext) fieldContext_Query_searchConnections(ctx context.Con } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_searchConnections_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_deleteUserCredentials_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_createConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_createConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_enableUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_enableUser, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().EnableUser(ctx, fc.Args["userId"].(string), fc.Args["enabled"].(bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_enableUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CreateConnectionConfiguration(rctx, fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_enableUser_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_setUserAuthRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setUserAuthRole, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetUserAuthRole(ctx, fc.Args["userId"].(string), fc.Args["authRole"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_createConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_setUserAuthRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, IsMethod: true, IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) + return nil, errors.New("field of type Boolean does not have child fields") }, } defer func() { @@ -24768,45 +28959,92 @@ func (ec *executionContext) fieldContext_Query_createConnectionConfiguration(ctx } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_createConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_setUserAuthRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_copyConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_copyConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_setUserTeamRole(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setUserTeamRole, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetUserTeamRole(ctx, fc.Args["userId"].(string), fc.Args["teamId"].(string), fc.Args["teamRole"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.5") + if err != nil { + var zeroVal *bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_setUserTeamRole(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().CopyConnectionConfiguration(rctx, fc.Args["nodePath"].(string), fc.Args["config"].(*model.ConnectionConfig)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_setUserTeamRole_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_searchConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_searchConnections, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SearchConnections(ctx, fc.Args["hostNames"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminConnectionSearchInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_copyConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_searchConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -24814,70 +29052,18 @@ func (ec *executionContext) fieldContext_Query_copyConnectionConfiguration(ctx c IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) + case "displayName": + return ec.fieldContext_AdminConnectionSearchInfo_displayName(ctx, field) case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) + return ec.fieldContext_AdminConnectionSearchInfo_host(ctx, field) case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + return ec.fieldContext_AdminConnectionSearchInfo_port(ctx, field) + case "possibleDrivers": + return ec.fieldContext_AdminConnectionSearchInfo_possibleDrivers(ctx, field) + case "defaultDriver": + return ec.fieldContext_AdminConnectionSearchInfo_defaultDriver(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type AdminConnectionSearchInfo", field.Name) }, } defer func() { @@ -24887,45 +29073,33 @@ func (ec *executionContext) fieldContext_Query_copyConnectionConfiguration(ctx c } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_copyConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_searchConnections_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_updateConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_updateConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().UpdateConnectionConfiguration(rctx, fc.Args["id"].(string), fc.Args["config"].(model.ConnectionConfig)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) +func (ec *executionContext) _Query_getConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_getConnectionSubjectAccess, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().GetConnectionSubjectAccess(ctx, fc.Args["projectId"].(string), fc.Args["connectionId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_updateConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_getConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -24933,70 +29107,16 @@ func (ec *executionContext) fieldContext_Query_updateConnectionConfiguration(ctx IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "connectionId": + return ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) + case "dataSourceId": + return ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) + case "subjectId": + return ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) + case "subjectType": + return ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type AdminConnectionGrantInfo", field.Name) }, } defer func() { @@ -25006,42 +29126,33 @@ func (ec *executionContext) fieldContext_Query_updateConnectionConfiguration(ctx } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_updateConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_getConnectionSubjectAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_deleteConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteConnectionConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteConnectionConfiguration(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _Query_setConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setConnectionSubjectAccess, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetConnectionSubjectAccess(ctx, fc.Args["projectId"].(string), fc.Args["connectionId"].(string), fc.Args["subjects"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_deleteConnectionConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_setConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -25058,62 +29169,56 @@ func (ec *executionContext) fieldContext_Query_deleteConnectionConfiguration(ctx } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_deleteConnectionConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_setConnectionSubjectAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_getConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_getConnectionSubjectAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().GetConnectionSubjectAccess(rctx, fc.Args["connectionId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) +func (ec *executionContext) _Query_addConnectionsAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_addConnectionsAccess, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().AddConnectionsAccess(ctx, fc.Args["projectId"].(string), fc.Args["connectionIds"].([]string), fc.Args["subjects"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.2.2") + if err != nil { + var zeroVal *bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_getConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_addConnectionsAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, IsMethod: true, IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "connectionId": - return ec.fieldContext_AdminConnectionGrantInfo_connectionId(ctx, field) - case "dataSourceId": - return ec.fieldContext_AdminConnectionGrantInfo_dataSourceId(ctx, field) - case "subjectId": - return ec.fieldContext_AdminConnectionGrantInfo_subjectId(ctx, field) - case "subjectType": - return ec.fieldContext_AdminConnectionGrantInfo_subjectType(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type AdminConnectionGrantInfo", field.Name) + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") }, } defer func() { @@ -25123,42 +29228,49 @@ func (ec *executionContext) fieldContext_Query_getConnectionSubjectAccess(ctx co } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_getConnectionSubjectAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_addConnectionsAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_setConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setConnectionSubjectAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetConnectionSubjectAccess(rctx, fc.Args["connectionId"].(string), fc.Args["subjects"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _Query_deleteConnectionsAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_deleteConnectionsAccess, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DeleteConnectionsAccess(ctx, fc.Args["projectId"].(string), fc.Args["connectionIds"].([]string), fc.Args["subjects"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.2.2") + if err != nil { + var zeroVal *bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_setConnectionSubjectAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_deleteConnectionsAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -25175,42 +29287,30 @@ func (ec *executionContext) fieldContext_Query_setConnectionSubjectAccess(ctx co } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_setConnectionSubjectAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_deleteConnectionsAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_getSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_getSubjectConnectionAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().GetSubjectConnectionAccess(rctx, fc.Args["subjectId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminConnectionGrantInfo) - fc.Result = res - return ec.marshalNAdminConnectionGrantInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_getSubjectConnectionAccess, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().GetSubjectConnectionAccess(ctx, fc.Args["subjectId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_getSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25242,37 +29342,28 @@ func (ec *executionContext) fieldContext_Query_getSubjectConnectionAccess(ctx co ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_getSubjectConnectionAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_setSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setSubjectConnectionAccess(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetSubjectConnectionAccess(rctx, fc.Args["subjectId"].(string), fc.Args["connections"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setSubjectConnectionAccess, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetSubjectConnectionAccess(ctx, fc.Args["subjectId"].(string), fc.Args["connections"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } func (ec *executionContext) fieldContext_Query_setSubjectConnectionAccess(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25294,43 +29385,30 @@ func (ec *executionContext) fieldContext_Query_setSubjectConnectionAccess(ctx co ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_setSubjectConnectionAccess_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_listFeatureSets(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listFeatureSets(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListFeatureSets(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.WebFeatureSet) - fc.Result = res - return ec.marshalNWebFeatureSet2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSetᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listFeatureSets, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ListFeatureSets(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNWebFeatureSet2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSetᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_listFeatureSets(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_listFeatureSets(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -25356,34 +29434,22 @@ func (ec *executionContext) fieldContext_Query_listFeatureSets(ctx context.Conte } func (ec *executionContext) _Query_listAuthProviderConfigurationParameters(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listAuthProviderConfigurationParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListAuthProviderConfigurationParameters(rctx, fc.Args["providerId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listAuthProviderConfigurationParameters, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ListAuthProviderConfigurationParameters(ctx, fc.Args["providerId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurationParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25400,6 +29466,8 @@ func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurationPara return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -25416,6 +29484,14 @@ func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurationPara return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -25429,40 +29505,28 @@ func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurationPara ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_listAuthProviderConfigurationParameters_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_listAuthProviderConfigurations(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listAuthProviderConfigurations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListAuthProviderConfigurations(rctx, fc.Args["providerId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AdminAuthProviderConfiguration) - fc.Result = res - return ec.marshalNAdminAuthProviderConfiguration2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfigurationᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listAuthProviderConfigurations, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ListAuthProviderConfigurations(ctx, fc.Args["providerId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfigurationᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25495,6 +29559,10 @@ func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurations(ct return ec.fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx, field) case "metadataLink": return ec.fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx, field) + case "acsLink": + return ec.fieldContext_AdminAuthProviderConfiguration_acsLink(ctx, field) + case "entityIdLink": + return ec.fieldContext_AdminAuthProviderConfiguration_entityIdLink(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type AdminAuthProviderConfiguration", field.Name) }, @@ -25508,46 +29576,34 @@ func (ec *executionContext) fieldContext_Query_listAuthProviderConfigurations(ct ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_listAuthProviderConfigurations_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_saveAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_saveAuthProviderConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SaveAuthProviderConfiguration(rctx, fc.Args["providerId"].(string), fc.Args["id"].(string), fc.Args["displayName"].(*string), fc.Args["disabled"].(*bool), fc.Args["iconURL"].(*string), fc.Args["description"].(*string), - func() interface{} { - if fc.Args["parameters"] == nil { - return nil - } - return fc.Args["parameters"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AdminAuthProviderConfiguration) - fc.Result = res - return ec.marshalNAdminAuthProviderConfiguration2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_saveAuthProviderConfiguration, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SaveAuthProviderConfiguration(ctx, fc.Args["providerId"].(string), fc.Args["id"].(string), fc.Args["displayName"].(*string), fc.Args["disabled"].(*bool), fc.Args["iconURL"].(*string), fc.Args["description"].(*string), + func() any { + if fc.Args["parameters"] == nil { + return nil + } + return fc.Args["parameters"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_saveAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25580,6 +29636,10 @@ func (ec *executionContext) fieldContext_Query_saveAuthProviderConfiguration(ctx return ec.fieldContext_AdminAuthProviderConfiguration_redirectLink(ctx, field) case "metadataLink": return ec.fieldContext_AdminAuthProviderConfiguration_metadataLink(ctx, field) + case "acsLink": + return ec.fieldContext_AdminAuthProviderConfiguration_acsLink(ctx, field) + case "entityIdLink": + return ec.fieldContext_AdminAuthProviderConfiguration_entityIdLink(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type AdminAuthProviderConfiguration", field.Name) }, @@ -25593,40 +29653,28 @@ func (ec *executionContext) fieldContext_Query_saveAuthProviderConfiguration(ctx ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_saveAuthProviderConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_deleteAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteAuthProviderConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteAuthProviderConfiguration(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_deleteAuthProviderConfiguration, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DeleteAuthProviderConfiguration(ctx, fc.Args["id"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_deleteAuthProviderConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25648,40 +29696,28 @@ func (ec *executionContext) fieldContext_Query_deleteAuthProviderConfiguration(c ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_deleteAuthProviderConfiguration_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_saveUserMetaParameter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_saveUserMetaParameter(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SaveUserMetaParameter(rctx, fc.Args["id"].(string), fc.Args["displayName"].(string), fc.Args["description"].(*string), fc.Args["required"].(bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_saveUserMetaParameter, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SaveUserMetaParameter(ctx, fc.Args["id"].(string), fc.Args["displayName"].(string), fc.Args["description"].(*string), fc.Args["required"].(bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_saveUserMetaParameter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25698,6 +29734,8 @@ func (ec *executionContext) fieldContext_Query_saveUserMetaParameter(ctx context return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -25714,6 +29752,14 @@ func (ec *executionContext) fieldContext_Query_saveUserMetaParameter(ctx context return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -25727,40 +29773,28 @@ func (ec *executionContext) fieldContext_Query_saveUserMetaParameter(ctx context ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_saveUserMetaParameter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_deleteUserMetaParameter(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_deleteUserMetaParameter(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DeleteUserMetaParameter(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_deleteUserMetaParameter, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DeleteUserMetaParameter(ctx, fc.Args["id"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_deleteUserMetaParameter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25782,46 +29816,34 @@ func (ec *executionContext) fieldContext_Query_deleteUserMetaParameter(ctx conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_deleteUserMetaParameter_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_setUserMetaParameterValues(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setUserMetaParameterValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetUserMetaParameterValues(rctx, fc.Args["userId"].(string), - func() interface{} { - if fc.Args["parameters"] == nil { - return nil - } - return fc.Args["parameters"].(interface{}) - }()) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setUserMetaParameterValues, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetUserMetaParameterValues(ctx, fc.Args["userId"].(string), + func() any { + if fc.Args["parameters"] == nil { + return nil + } + return fc.Args["parameters"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_setUserMetaParameterValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25843,40 +29865,77 @@ func (ec *executionContext) fieldContext_Query_setUserMetaParameterValues(ctx co ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_setUserMetaParameterValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_configureServer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_configureServer(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_setTeamMetaParameterValues(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setTeamMetaParameterValues, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetTeamMetaParameterValues(ctx, fc.Args["teamId"].(string), + func() any { + if fc.Args["parameters"] == nil { + return nil + } + return fc.Args["parameters"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_setTeamMetaParameterValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConfigureServer(rctx, fc.Args["configuration"].(model.ServerConfigInput)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_setTeamMetaParameterValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_configureServer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_configureServer, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ConfigureServer(ctx, fc.Args["configuration"].(model.ServerConfigInput)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_configureServer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25898,40 +29957,28 @@ func (ec *executionContext) fieldContext_Query_configureServer(ctx context.Conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_configureServer_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_setDefaultNavigatorSettings(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_setDefaultNavigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SetDefaultNavigatorSettings(rctx, fc.Args["settings"].(model.NavigatorSettingsInput)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_setDefaultNavigatorSettings, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SetDefaultNavigatorSettings(ctx, fc.Args["settings"].(model.NavigatorSettingsInput)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_setDefaultNavigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -25953,46 +30000,34 @@ func (ec *executionContext) fieldContext_Query_setDefaultNavigatorSettings(ctx c ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_setDefaultNavigatorSettings_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_authLogin(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authLogin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthLogin(rctx, fc.Args["provider"].(string), fc.Args["configuration"].(*string), - func() interface{} { - if fc.Args["credentials"] == nil { - return nil - } - return fc.Args["credentials"].(interface{}) - }(), fc.Args["linkUser"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AuthInfo) - fc.Result = res - return ec.marshalNAuthInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_authLogin, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().AuthLogin(ctx, fc.Args["provider"].(string), fc.Args["configuration"].(*string), + func() any { + if fc.Args["credentials"] == nil { + return nil + } + return fc.Args["credentials"].(any) + }(), fc.Args["linkUser"].(*bool), fc.Args["forceSessionsLogout"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAuthInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_authLogin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -26024,40 +30059,103 @@ func (ec *executionContext) fieldContext_Query_authLogin(ctx context.Context, fi ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_authLogin_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_authUpdateStatus(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authUpdateStatus(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_federatedAuthTaskResult(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_federatedAuthTaskResult, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().FederatedAuthTaskResult(ctx, fc.Args["taskId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal *model.FederatedAuthResult + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.FederatedAuthResult + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.3") + if err != nil { + var zeroVal *model.FederatedAuthResult + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.FederatedAuthResult + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNFederatedAuthResult2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐFederatedAuthResult, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_federatedAuthTaskResult(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "userTokens": + return ec.fieldContext_FederatedAuthResult_userTokens(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type FederatedAuthResult", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthUpdateStatus(rctx, fc.Args["authId"].(string), fc.Args["linkUser"].(*bool)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_federatedAuthTaskResult_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, err } - res := resTmp.(*model.AuthInfo) - fc.Result = res - return ec.marshalNAuthInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_authUpdateStatus(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_authUpdateStatus, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().AuthUpdateStatus(ctx, fc.Args["authId"].(string), fc.Args["linkUser"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAuthInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_authUpdateStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -26089,37 +30187,28 @@ func (ec *executionContext) fieldContext_Query_authUpdateStatus(ctx context.Cont ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_authUpdateStatus_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_authLogout(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authLogout(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthLogout(rctx, fc.Args["provider"].(*string), fc.Args["configuration"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_authLogout, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().AuthLogout(ctx, fc.Args["provider"].(*string), fc.Args["configuration"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } func (ec *executionContext) fieldContext_Query_authLogout(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -26141,40 +30230,105 @@ func (ec *executionContext) fieldContext_Query_authLogout(ctx context.Context, f ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_authLogout_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_activeUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_activeUser(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_authLogoutExtended(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_authLogoutExtended, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().AuthLogoutExtended(ctx, fc.Args["provider"].(*string), fc.Args["configuration"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal *model.LogoutInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.LogoutInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.3") + if err != nil { + var zeroVal *model.LogoutInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.LogoutInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNLogoutInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogoutInfo, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_authLogoutExtended(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "redirectLinks": + return ec.fieldContext_LogoutInfo_redirectLinks(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type LogoutInfo", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ActiveUser(rctx) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_authLogoutExtended_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return fc, err } - res := resTmp.(*model.UserInfo) - fc.Result = res - return ec.marshalOUserInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_activeUser(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_activeUser, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ActiveUser(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserInfo, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query_activeUser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_activeUser(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26186,6 +30340,8 @@ func (ec *executionContext) fieldContext_Query_activeUser(ctx context.Context, f return ec.fieldContext_UserInfo_userId(ctx, field) case "displayName": return ec.fieldContext_UserInfo_displayName(ctx, field) + case "authRole": + return ec.fieldContext_UserInfo_authRole(ctx, field) case "authTokens": return ec.fieldContext_UserInfo_authTokens(ctx, field) case "linkedAuthProviders": @@ -26194,6 +30350,10 @@ func (ec *executionContext) fieldContext_Query_activeUser(ctx context.Context, f return ec.fieldContext_UserInfo_metaParameters(ctx, field) case "configurationParameters": return ec.fieldContext_UserInfo_configurationParameters(ctx, field) + case "teams": + return ec.fieldContext_UserInfo_teams(ctx, field) + case "isAnonymous": + return ec.fieldContext_UserInfo_isAnonymous(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type UserInfo", field.Name) }, @@ -26202,37 +30362,24 @@ func (ec *executionContext) fieldContext_Query_activeUser(ctx context.Context, f } func (ec *executionContext) _Query_authProviders(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthProviders(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.AuthProviderInfo) - fc.Result = res - return ec.marshalNAuthProviderInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_authProviders, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().AuthProviders(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAuthProviderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_authProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_authProviders(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26250,14 +30397,28 @@ func (ec *executionContext) fieldContext_Query_authProviders(ctx context.Context return ec.fieldContext_AuthProviderInfo_description(ctx, field) case "defaultProvider": return ec.fieldContext_AuthProviderInfo_defaultProvider(ctx, field) + case "trusted": + return ec.fieldContext_AuthProviderInfo_trusted(ctx, field) + case "private": + return ec.fieldContext_AuthProviderInfo_private(ctx, field) + case "authHidden": + return ec.fieldContext_AuthProviderInfo_authHidden(ctx, field) + case "supportProvisioning": + return ec.fieldContext_AuthProviderInfo_supportProvisioning(ctx, field) case "configurable": return ec.fieldContext_AuthProviderInfo_configurable(ctx, field) + case "federated": + return ec.fieldContext_AuthProviderInfo_federated(ctx, field) case "configurations": return ec.fieldContext_AuthProviderInfo_configurations(ctx, field) + case "templateConfiguration": + return ec.fieldContext_AuthProviderInfo_templateConfiguration(ctx, field) case "credentialProfiles": return ec.fieldContext_AuthProviderInfo_credentialProfiles(ctx, field) case "requiredFeatures": return ec.fieldContext_AuthProviderInfo_requiredFeatures(ctx, field) + case "required": + return ec.fieldContext_AuthProviderInfo_required(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type AuthProviderInfo", field.Name) }, @@ -26266,34 +30427,22 @@ func (ec *executionContext) fieldContext_Query_authProviders(ctx context.Context } func (ec *executionContext) _Query_authChangeLocalPassword(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authChangeLocalPassword(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthChangeLocalPassword(rctx, fc.Args["oldPassword"].(string), fc.Args["newPassword"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_authChangeLocalPassword, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().AuthChangeLocalPassword(ctx, fc.Args["oldPassword"].(string), fc.Args["newPassword"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_authChangeLocalPassword(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -26315,43 +30464,30 @@ func (ec *executionContext) fieldContext_Query_authChangeLocalPassword(ctx conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_authChangeLocalPassword_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_listUserProfileProperties(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_listUserProfileProperties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ListUserProfileProperties(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listUserProfileProperties, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ListUserProfileProperties(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_listUserProfileProperties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_listUserProfileProperties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26365,6 +30501,8 @@ func (ec *executionContext) fieldContext_Query_listUserProfileProperties(ctx con return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -26381,6 +30519,14 @@ func (ec *executionContext) fieldContext_Query_listUserProfileProperties(ctx con return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -26389,37 +30535,24 @@ func (ec *executionContext) fieldContext_Query_listUserProfileProperties(ctx con } func (ec *executionContext) _Query_serverConfig(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_serverConfig(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ServerConfig(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ServerConfig) - fc.Result = res - return ec.marshalNServerConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfig(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_serverConfig, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ServerConfig(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNServerConfig2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfig, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_serverConfig(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_serverConfig(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26433,24 +30566,14 @@ func (ec *executionContext) fieldContext_Query_serverConfig(ctx context.Context, return ec.fieldContext_ServerConfig_version(ctx, field) case "workspaceId": return ec.fieldContext_ServerConfig_workspaceId(ctx, field) - case "serverURL": - return ec.fieldContext_ServerConfig_serverURL(ctx, field) - case "rootURI": - return ec.fieldContext_ServerConfig_rootURI(ctx, field) - case "hostName": - return ec.fieldContext_ServerConfig_hostName(ctx, field) case "anonymousAccessEnabled": return ec.fieldContext_ServerConfig_anonymousAccessEnabled(ctx, field) - case "authenticationEnabled": - return ec.fieldContext_ServerConfig_authenticationEnabled(ctx, field) case "supportsCustomConnections": return ec.fieldContext_ServerConfig_supportsCustomConnections(ctx, field) - case "supportsConnectionBrowser": - return ec.fieldContext_ServerConfig_supportsConnectionBrowser(ctx, field) - case "supportsWorkspaces": - return ec.fieldContext_ServerConfig_supportsWorkspaces(ctx, field) case "resourceManagerEnabled": return ec.fieldContext_ServerConfig_resourceManagerEnabled(ctx, field) + case "secretManagerEnabled": + return ec.fieldContext_ServerConfig_secretManagerEnabled(ctx, field) case "publicCredentialsSaveEnabled": return ec.fieldContext_ServerConfig_publicCredentialsSaveEnabled(ctx, field) case "adminCredentialsSaveEnabled": @@ -26459,24 +30582,22 @@ func (ec *executionContext) fieldContext_Query_serverConfig(ctx context.Context, return ec.fieldContext_ServerConfig_licenseRequired(ctx, field) case "licenseValid": return ec.fieldContext_ServerConfig_licenseValid(ctx, field) - case "sessionExpireTime": - return ec.fieldContext_ServerConfig_sessionExpireTime(ctx, field) - case "localHostAddress": - return ec.fieldContext_ServerConfig_localHostAddress(ctx, field) + case "licenseStatus": + return ec.fieldContext_ServerConfig_licenseStatus(ctx, field) case "configurationMode": return ec.fieldContext_ServerConfig_configurationMode(ctx, field) case "developmentMode": return ec.fieldContext_ServerConfig_developmentMode(ctx, field) - case "redirectOnFederatedAuth": - return ec.fieldContext_ServerConfig_redirectOnFederatedAuth(ctx, field) + case "distributed": + return ec.fieldContext_ServerConfig_distributed(ctx, field) case "enabledFeatures": return ec.fieldContext_ServerConfig_enabledFeatures(ctx, field) - case "enabledAuthProviders": - return ec.fieldContext_ServerConfig_enabledAuthProviders(ctx, field) + case "disabledBetaFeatures": + return ec.fieldContext_ServerConfig_disabledBetaFeatures(ctx, field) + case "serverFeatures": + return ec.fieldContext_ServerConfig_serverFeatures(ctx, field) case "supportedLanguages": return ec.fieldContext_ServerConfig_supportedLanguages(ctx, field) - case "services": - return ec.fieldContext_ServerConfig_services(ctx, field) case "productConfiguration": return ec.fieldContext_ServerConfig_productConfiguration(ctx, field) case "productInfo": @@ -26488,44 +30609,177 @@ func (ec *executionContext) fieldContext_Query_serverConfig(ctx context.Context, case "resourceQuotas": return ec.fieldContext_ServerConfig_resourceQuotas(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ServerConfig", field.Name) + return nil, fmt.Errorf("no field named %q was found under type ServerConfig", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_systemInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_systemInfo, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().SystemInfo(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.5") + if err != nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.ObjectPropertyInfo + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_systemInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_ObjectPropertyInfo_id(ctx, field) + case "displayName": + return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) + case "description": + return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) + case "category": + return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) + case "dataType": + return ec.fieldContext_ObjectPropertyInfo_dataType(ctx, field) + case "value": + return ec.fieldContext_ObjectPropertyInfo_value(ctx, field) + case "validValues": + return ec.fieldContext_ObjectPropertyInfo_validValues(ctx, field) + case "defaultValue": + return ec.fieldContext_ObjectPropertyInfo_defaultValue(ctx, field) + case "length": + return ec.fieldContext_ObjectPropertyInfo_length(ctx, field) + case "features": + return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) + case "order": + return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_productSettings(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_productSettings, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ProductSettings(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal *model.ProductSettings + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.ProductSettings + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive0, version) + } + directive2 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.1") + if err != nil { + var zeroVal *model.ProductSettings + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *model.ProductSettings + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, nil, directive1, version) + } + + next = directive2 + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNProductSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductSettings, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_productSettings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "groups": + return ec.fieldContext_ProductSettings_groups(ctx, field) + case "settings": + return ec.fieldContext_ProductSettings_settings(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type ProductSettings", field.Name) }, } return fc, nil } func (ec *executionContext) _Query_sessionState(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sessionState(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SessionState(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SessionInfo) - fc.Result = res - return ec.marshalNSessionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sessionState, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().SessionState(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSessionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_sessionState(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_sessionState(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26541,12 +30795,14 @@ func (ec *executionContext) fieldContext_Query_sessionState(ctx context.Context, return ec.fieldContext_SessionInfo_locale(ctx, field) case "cacheExpired": return ec.fieldContext_SessionInfo_cacheExpired(ctx, field) - case "serverMessages": - return ec.fieldContext_SessionInfo_serverMessages(ctx, field) case "connections": return ec.fieldContext_SessionInfo_connections(ctx, field) case "actionParameters": return ec.fieldContext_SessionInfo_actionParameters(ctx, field) + case "valid": + return ec.fieldContext_SessionInfo_valid(ctx, field) + case "remainingTime": + return ec.fieldContext_SessionInfo_remainingTime(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type SessionInfo", field.Name) }, @@ -26555,37 +30811,24 @@ func (ec *executionContext) fieldContext_Query_sessionState(ctx context.Context, } func (ec *executionContext) _Query_sessionPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sessionPermissions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SessionPermissions(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNID2ᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sessionPermissions, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().SessionPermissions(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNID2ᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_sessionPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_sessionPermissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26599,34 +30842,22 @@ func (ec *executionContext) fieldContext_Query_sessionPermissions(ctx context.Co } func (ec *executionContext) _Query_driverList(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_driverList(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DriverList(rctx, fc.Args["id"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DriverInfo) - fc.Result = res - return ec.marshalNDriverInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_driverList, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DriverList(ctx, fc.Args["id"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDriverInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfoᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_driverList(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -26647,6 +30878,8 @@ func (ec *executionContext) fieldContext_Query_driverList(ctx context.Context, f return ec.fieldContext_DriverInfo_icon(ctx, field) case "iconBig": return ec.fieldContext_DriverInfo_iconBig(ctx, field) + case "driverId": + return ec.fieldContext_DriverInfo_driverId(ctx, field) case "providerId": return ec.fieldContext_DriverInfo_providerId(ctx, field) case "driverClassName": @@ -26673,8 +30906,10 @@ func (ec *executionContext) fieldContext_Query_driverList(ctx context.Context, f return ec.fieldContext_DriverInfo_enabled(ctx, field) case "requiresServerName": return ec.fieldContext_DriverInfo_requiresServerName(ctx, field) - case "allowsEmptyPassword": - return ec.fieldContext_DriverInfo_allowsEmptyPassword(ctx, field) + case "requiresDatabaseName": + return ec.fieldContext_DriverInfo_requiresDatabaseName(ctx, field) + case "useCustomPage": + return ec.fieldContext_DriverInfo_useCustomPage(ctx, field) case "licenseRequired": return ec.fieldContext_DriverInfo_licenseRequired(ctx, field) case "license": @@ -26687,8 +30922,12 @@ func (ec *executionContext) fieldContext_Query_driverList(ctx context.Context, f return ec.fieldContext_DriverInfo_driverProperties(ctx, field) case "driverParameters": return ec.fieldContext_DriverInfo_driverParameters(ctx, field) + case "mainProperties": + return ec.fieldContext_DriverInfo_mainProperties(ctx, field) case "providerProperties": return ec.fieldContext_DriverInfo_providerProperties(ctx, field) + case "expertSettingsProperties": + return ec.fieldContext_DriverInfo_expertSettingsProperties(ctx, field) case "anonymousAccess": return ec.fieldContext_DriverInfo_anonymousAccess(ctx, field) case "defaultAuthModel": @@ -26697,6 +30936,16 @@ func (ec *executionContext) fieldContext_Query_driverList(ctx context.Context, f return ec.fieldContext_DriverInfo_applicableAuthModels(ctx, field) case "applicableNetworkHandlers": return ec.fieldContext_DriverInfo_applicableNetworkHandlers(ctx, field) + case "configurationTypes": + return ec.fieldContext_DriverInfo_configurationTypes(ctx, field) + case "downloadable": + return ec.fieldContext_DriverInfo_downloadable(ctx, field) + case "driverInstalled": + return ec.fieldContext_DriverInfo_driverInstalled(ctx, field) + case "driverLibraries": + return ec.fieldContext_DriverInfo_driverLibraries(ctx, field) + case "safeEmbeddedDriver": + return ec.fieldContext_DriverInfo_safeEmbeddedDriver(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type DriverInfo", field.Name) }, @@ -26710,43 +30959,30 @@ func (ec *executionContext) fieldContext_Query_driverList(ctx context.Context, f ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_driverList_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_authModels(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_authModels(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().AuthModels(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DatabaseAuthModel) - fc.Result = res - return ec.marshalNDatabaseAuthModel2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModelᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_authModels, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().AuthModels(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDatabaseAuthModel2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModelᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_authModels(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_authModels(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26764,6 +31000,8 @@ func (ec *executionContext) fieldContext_Query_authModels(ctx context.Context, f return ec.fieldContext_DatabaseAuthModel_icon(ctx, field) case "requiresLocalConfiguration": return ec.fieldContext_DatabaseAuthModel_requiresLocalConfiguration(ctx, field) + case "requiredAuth": + return ec.fieldContext_DatabaseAuthModel_requiredAuth(ctx, field) case "properties": return ec.fieldContext_DatabaseAuthModel_properties(ctx, field) } @@ -26774,37 +31012,24 @@ func (ec *executionContext) fieldContext_Query_authModels(ctx context.Context, f } func (ec *executionContext) _Query_networkHandlers(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_networkHandlers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NetworkHandlers(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NetworkHandlerDescriptor) - fc.Result = res - return ec.marshalNNetworkHandlerDescriptor2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptorᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_networkHandlers, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().NetworkHandlers(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNNetworkHandlerDescriptor2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptorᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_networkHandlers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_networkHandlers(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -26834,34 +31059,22 @@ func (ec *executionContext) fieldContext_Query_networkHandlers(ctx context.Conte } func (ec *executionContext) _Query_userConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_userConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().UserConnections(rctx, fc.Args["id"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_userConnections, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().UserConnections(ctx, fc.Args["projectId"].(*string), fc.Args["id"].(*string), fc.Args["projectIds"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_userConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -26890,10 +31103,16 @@ func (ec *executionContext) fieldContext_Query_userConnections(ctx context.Conte return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -26904,6 +31123,14 @@ func (ec *executionContext) fieldContext_Query_userConnections(ctx context.Conte return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -26918,8 +31145,6 @@ func (ec *executionContext) fieldContext_Query_userConnections(ctx context.Conte return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -26934,6 +31159,24 @@ func (ec *executionContext) fieldContext_Query_userConnections(ctx context.Conte return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -26947,148 +31190,28 @@ func (ec *executionContext) fieldContext_Query_userConnections(ctx context.Conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_userConnections_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return - } - return fc, nil -} - -func (ec *executionContext) _Query_templateConnections(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_templateConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().TemplateConnections(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_Query_templateConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "Query", - Field: field, - IsMethod: true, - IsResolver: true, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) - case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) - case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) - }, + return fc, err } return fc, nil } func (ec *executionContext) _Query_connectionFolders(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_connectionFolders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConnectionFolders(rctx, fc.Args["path"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionFolderInfo) - fc.Result = res - return ec.marshalNConnectionFolderInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_connectionFolders, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ConnectionFolders(ctx, fc.Args["projectId"].(*string), fc.Args["path"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionFolderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfoᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_connectionFolders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27101,6 +31224,8 @@ func (ec *executionContext) fieldContext_Query_connectionFolders(ctx context.Con switch field.Name { case "id": return ec.fieldContext_ConnectionFolderInfo_id(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionFolderInfo_projectId(ctx, field) case "description": return ec.fieldContext_ConnectionFolderInfo_description(ctx, field) } @@ -27116,43 +31241,31 @@ func (ec *executionContext) fieldContext_Query_connectionFolders(ctx context.Con ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_connectionFolders_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_connectionState(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_connectionState(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConnectionState(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) +func (ec *executionContext) _Query_connectionInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_connectionInfo, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ConnectionInfo(ctx, fc.Args["projectId"].(string), fc.Args["id"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_connectionState(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_connectionInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -27178,10 +31291,16 @@ func (ec *executionContext) fieldContext_Query_connectionState(ctx context.Conte return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -27192,6 +31311,14 @@ func (ec *executionContext) fieldContext_Query_connectionState(ctx context.Conte return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -27206,8 +31333,6 @@ func (ec *executionContext) fieldContext_Query_connectionState(ctx context.Conte return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -27222,6 +31347,24 @@ func (ec *executionContext) fieldContext_Query_connectionState(ctx context.Conte return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -27233,45 +31376,32 @@ func (ec *executionContext) fieldContext_Query_connectionState(ctx context.Conte } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_connectionState_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_connectionInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query_connectionInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_connectionInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ConnectionInfo(rctx, fc.Args["id"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, field.Selections, res) +func (ec *executionContext) _Query_listProjects(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_listProjects, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().ListProjects(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNProjectInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProjectInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_connectionInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_listProjects(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -27280,114 +31410,49 @@ func (ec *executionContext) fieldContext_Query_connectionInfo(ctx context.Contex Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { case "id": - return ec.fieldContext_ConnectionInfo_id(ctx, field) - case "driverId": - return ec.fieldContext_ConnectionInfo_driverId(ctx, field) + return ec.fieldContext_ProjectInfo_id(ctx, field) + case "global": + return ec.fieldContext_ProjectInfo_global(ctx, field) + case "shared": + return ec.fieldContext_ProjectInfo_shared(ctx, field) case "name": - return ec.fieldContext_ConnectionInfo_name(ctx, field) + return ec.fieldContext_ProjectInfo_name(ctx, field) case "description": - return ec.fieldContext_ConnectionInfo_description(ctx, field) - case "host": - return ec.fieldContext_ConnectionInfo_host(ctx, field) - case "port": - return ec.fieldContext_ConnectionInfo_port(ctx, field) - case "serverName": - return ec.fieldContext_ConnectionInfo_serverName(ctx, field) - case "databaseName": - return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) - case "url": - return ec.fieldContext_ConnectionInfo_url(ctx, field) - case "properties": - return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) - case "connected": - return ec.fieldContext_ConnectionInfo_connected(ctx, field) - case "provided": - return ec.fieldContext_ConnectionInfo_provided(ctx, field) - case "readOnly": - return ec.fieldContext_ConnectionInfo_readOnly(ctx, field) - case "useUrl": - return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) - case "saveCredentials": - return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) - case "folder": - return ec.fieldContext_ConnectionInfo_folder(ctx, field) - case "nodePath": - return ec.fieldContext_ConnectionInfo_nodePath(ctx, field) - case "connectTime": - return ec.fieldContext_ConnectionInfo_connectTime(ctx, field) - case "connectionError": - return ec.fieldContext_ConnectionInfo_connectionError(ctx, field) - case "serverVersion": - return ec.fieldContext_ConnectionInfo_serverVersion(ctx, field) - case "clientVersion": - return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) - case "origin": - return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) - case "authModel": - return ec.fieldContext_ConnectionInfo_authModel(ctx, field) - case "authProperties": - return ec.fieldContext_ConnectionInfo_authProperties(ctx, field) - case "providerProperties": - return ec.fieldContext_ConnectionInfo_providerProperties(ctx, field) - case "networkHandlersConfig": - return ec.fieldContext_ConnectionInfo_networkHandlersConfig(ctx, field) - case "features": - return ec.fieldContext_ConnectionInfo_features(ctx, field) - case "navigatorSettings": - return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) - case "supportedDataFormats": - return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + return ec.fieldContext_ProjectInfo_description(ctx, field) + case "canEditDataSources": + return ec.fieldContext_ProjectInfo_canEditDataSources(ctx, field) + case "canViewDataSources": + return ec.fieldContext_ProjectInfo_canViewDataSources(ctx, field) + case "canEditResources": + return ec.fieldContext_ProjectInfo_canEditResources(ctx, field) + case "canViewResources": + return ec.fieldContext_ProjectInfo_canViewResources(ctx, field) + case "resourceTypes": + return ec.fieldContext_ProjectInfo_resourceTypes(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) + return nil, fmt.Errorf("no field named %q was found under type ProjectInfo", field.Name) }, } - defer func() { - if r := recover(); r != nil { - err = ec.Recover(ctx, r) - ec.Error(ctx, err) - } - }() - ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_connectionInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { - ec.Error(ctx, err) - return - } return fc, nil } func (ec *executionContext) _Query_readSessionLog(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_readSessionLog(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().ReadSessionLog(rctx, fc.Args["maxEntries"].(*int), fc.Args["clearEntries"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.LogEntry) - fc.Result = res - return ec.marshalNLogEntry2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntryᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_readSessionLog, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().ReadSessionLog(ctx, fc.Args["maxEntries"].(*int), fc.Args["clearEntries"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNLogEntry2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntryᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_readSessionLog(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27419,43 +31484,30 @@ func (ec *executionContext) fieldContext_Query_readSessionLog(ctx context.Contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_readSessionLog_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_dataTransferAvailableStreamProcessors(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferAvailableStreamProcessors(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferAvailableStreamProcessors(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DataTransferProcessorInfo) - fc.Result = res - return ec.marshalNDataTransferProcessorInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_dataTransferAvailableStreamProcessors, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().DataTransferAvailableStreamProcessors(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDataTransferProcessorInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_dataTransferAvailableStreamProcessors(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_dataTransferAvailableStreamProcessors(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -27492,35 +31544,115 @@ func (ec *executionContext) fieldContext_Query_dataTransferAvailableStreamProces return fc, nil } -func (ec *executionContext) _Query_dataTransferExportDataFromContainer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferExportDataFromContainer(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferExportDataFromContainer(rctx, fc.Args["connectionId"].(string), fc.Args["containerNodePath"].(string), fc.Args["parameters"].(model.DataTransferParameters)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _Query_dataTransferAvailableImportStreamProcessors(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_dataTransferAvailableImportStreamProcessors, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().DataTransferAvailableImportStreamProcessors(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDataTransferProcessorInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_dataTransferAvailableImportStreamProcessors(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_DataTransferProcessorInfo_id(ctx, field) + case "name": + return ec.fieldContext_DataTransferProcessorInfo_name(ctx, field) + case "description": + return ec.fieldContext_DataTransferProcessorInfo_description(ctx, field) + case "fileExtension": + return ec.fieldContext_DataTransferProcessorInfo_fileExtension(ctx, field) + case "appFileExtension": + return ec.fieldContext_DataTransferProcessorInfo_appFileExtension(ctx, field) + case "appName": + return ec.fieldContext_DataTransferProcessorInfo_appName(ctx, field) + case "order": + return ec.fieldContext_DataTransferProcessorInfo_order(ctx, field) + case "icon": + return ec.fieldContext_DataTransferProcessorInfo_icon(ctx, field) + case "properties": + return ec.fieldContext_DataTransferProcessorInfo_properties(ctx, field) + case "isBinary": + return ec.fieldContext_DataTransferProcessorInfo_isBinary(ctx, field) + case "isHTML": + return ec.fieldContext_DataTransferProcessorInfo_isHTML(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type DataTransferProcessorInfo", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _Query_dataTransferDefaultExportSettings(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_dataTransferDefaultExportSettings, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().DataTransferDefaultExportSettings(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDataTransferDefaultExportSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferDefaultExportSettings, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_dataTransferDefaultExportSettings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "outputSettings": + return ec.fieldContext_DataTransferDefaultExportSettings_outputSettings(ctx, field) + case "supportedEncodings": + return ec.fieldContext_DataTransferDefaultExportSettings_supportedEncodings(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type DataTransferDefaultExportSettings", field.Name) + }, } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_dataTransferExportDataFromContainer(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_dataTransferExportDataFromContainer, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DataTransferExportDataFromContainer(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["containerNodePath"].(string), fc.Args["parameters"].(model.DataTransferParameters)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromContainer(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27541,8 +31673,6 @@ func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromContain return ec.fieldContext_AsyncTaskInfo_status(ctx, field) case "error": return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) case "taskResult": return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) } @@ -27558,40 +31688,28 @@ func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromContain ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_dataTransferExportDataFromContainer_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_dataTransferExportDataFromResults(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferExportDataFromResults(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferExportDataFromResults(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["parameters"].(model.DataTransferParameters)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.AsyncTaskInfo) - fc.Result = res - return ec.marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_dataTransferExportDataFromResults, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DataTransferExportDataFromResults(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["parameters"].(model.DataTransferParameters)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromResults(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27612,8 +31730,6 @@ func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromResults return ec.fieldContext_AsyncTaskInfo_status(ctx, field) case "error": return ec.fieldContext_AsyncTaskInfo_error(ctx, field) - case "result": - return ec.fieldContext_AsyncTaskInfo_result(ctx, field) case "taskResult": return ec.fieldContext_AsyncTaskInfo_taskResult(ctx, field) } @@ -27629,37 +31745,28 @@ func (ec *executionContext) fieldContext_Query_dataTransferExportDataFromResults ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_dataTransferExportDataFromResults_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_dataTransferRemoveDataFile(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_dataTransferRemoveDataFile(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().DataTransferRemoveDataFile(rctx, fc.Args["dataFileId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_dataTransferRemoveDataFile, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().DataTransferRemoveDataFile(ctx, fc.Args["dataFileId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } func (ec *executionContext) fieldContext_Query_dataTransferRemoveDataFile(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27681,46 +31788,80 @@ func (ec *executionContext) fieldContext_Query_dataTransferRemoveDataFile(ctx co ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_dataTransferRemoveDataFile_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_metadataGetNodeDDL(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_metadataGetNodeDDL(ctx, field) - if err != nil { - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_metadataGetNodeDDL, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().MetadataGetNodeDdl(ctx, fc.Args["nodeId"].(string), + func() any { + if fc.Args["options"] == nil { + return nil + } + return fc.Args["options"].(any) + }()) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_metadataGetNodeDDL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().MetadataGetNodeDdl(rctx, fc.Args["nodeId"].(string), - func() interface{} { - if fc.Args["options"] == nil { - return nil - } - return fc.Args["options"].(interface{}) - }()) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_metadataGetNodeDDL_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return fc, err } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_Query_metadataGetNodeDDL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _Query_metadataGetNodeExtendedDDL(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_metadataGetNodeExtendedDDL, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().MetadataGetNodeExtendedDdl(ctx, fc.Args["nodeId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_Query_metadataGetNodeExtendedDDL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -27737,42 +31878,30 @@ func (ec *executionContext) fieldContext_Query_metadataGetNodeDDL(ctx context.Co } }() ctx = graphql.WithFieldContext(ctx, fc) - if fc.Args, err = ec.field_Query_metadataGetNodeDDL_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + if fc.Args, err = ec.field_Query_metadataGetNodeExtendedDDL_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_navNodeChildren(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navNodeChildren(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavNodeChildren(rctx, fc.Args["parentPath"].(string), fc.Args["offset"].(*int), fc.Args["limit"].(*int), fc.Args["onlyFolders"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_navNodeChildren, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().NavNodeChildren(ctx, fc.Args["parentPath"].(string), fc.Args["offset"].(*int), fc.Args["limit"].(*int), fc.Args["onlyFolders"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_navNodeChildren(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27785,10 +31914,14 @@ func (ec *executionContext) fieldContext_Query_navNodeChildren(ctx context.Conte switch field.Name { case "id": return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) case "name": return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) case "fullName": return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) case "icon": return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) case "description": @@ -27797,8 +31930,12 @@ func (ec *executionContext) fieldContext_Query_navNodeChildren(ctx context.Conte return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) case "hasChildren": return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) case "object": return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) case "features": return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) case "nodeDetails": @@ -27809,6 +31946,10 @@ func (ec *executionContext) fieldContext_Query_navNodeChildren(ctx context.Conte return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) case "navigable": return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) }, @@ -27822,40 +31963,28 @@ func (ec *executionContext) fieldContext_Query_navNodeChildren(ctx context.Conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_navNodeChildren_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_navNodeParents(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navNodeParents(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavNodeParents(rctx, fc.Args["nodePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_navNodeParents, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().NavNodeParents(ctx, fc.Args["nodePath"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_navNodeParents(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27868,10 +31997,14 @@ func (ec *executionContext) fieldContext_Query_navNodeParents(ctx context.Contex switch field.Name { case "id": return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) case "name": return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) case "fullName": return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) case "icon": return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) case "description": @@ -27880,8 +32013,12 @@ func (ec *executionContext) fieldContext_Query_navNodeParents(ctx context.Contex return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) case "hasChildren": return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) case "object": return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) case "features": return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) case "nodeDetails": @@ -27892,6 +32029,10 @@ func (ec *executionContext) fieldContext_Query_navNodeParents(ctx context.Contex return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) case "navigable": return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) }, @@ -27905,40 +32046,28 @@ func (ec *executionContext) fieldContext_Query_navNodeParents(ctx context.Contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_navNodeParents_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_navNodeInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navNodeInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavNodeInfo(rctx, fc.Args["nodePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorNodeInfo) - fc.Result = res - return ec.marshalNNavigatorNodeInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_navNodeInfo, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().NavNodeInfo(ctx, fc.Args["nodePath"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_navNodeInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -27951,10 +32080,14 @@ func (ec *executionContext) fieldContext_Query_navNodeInfo(ctx context.Context, switch field.Name { case "id": return ec.fieldContext_NavigatorNodeInfo_id(ctx, field) + case "uri": + return ec.fieldContext_NavigatorNodeInfo_uri(ctx, field) case "name": return ec.fieldContext_NavigatorNodeInfo_name(ctx, field) case "fullName": return ec.fieldContext_NavigatorNodeInfo_fullName(ctx, field) + case "plainName": + return ec.fieldContext_NavigatorNodeInfo_plainName(ctx, field) case "icon": return ec.fieldContext_NavigatorNodeInfo_icon(ctx, field) case "description": @@ -27963,8 +32096,12 @@ func (ec *executionContext) fieldContext_Query_navNodeInfo(ctx context.Context, return ec.fieldContext_NavigatorNodeInfo_nodeType(ctx, field) case "hasChildren": return ec.fieldContext_NavigatorNodeInfo_hasChildren(ctx, field) + case "projectId": + return ec.fieldContext_NavigatorNodeInfo_projectId(ctx, field) case "object": return ec.fieldContext_NavigatorNodeInfo_object(ctx, field) + case "objectId": + return ec.fieldContext_NavigatorNodeInfo_objectId(ctx, field) case "features": return ec.fieldContext_NavigatorNodeInfo_features(ctx, field) case "nodeDetails": @@ -27975,6 +32112,10 @@ func (ec *executionContext) fieldContext_Query_navNodeInfo(ctx context.Context, return ec.fieldContext_NavigatorNodeInfo_inline(ctx, field) case "navigable": return ec.fieldContext_NavigatorNodeInfo_navigable(ctx, field) + case "filtered": + return ec.fieldContext_NavigatorNodeInfo_filtered(ctx, field) + case "filter": + return ec.fieldContext_NavigatorNodeInfo_filter(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type NavigatorNodeInfo", field.Name) }, @@ -27988,37 +32129,28 @@ func (ec *executionContext) fieldContext_Query_navNodeInfo(ctx context.Context, ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_navNodeInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_navRefreshNode(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navRefreshNode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavRefreshNode(rctx, fc.Args["nodePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_navRefreshNode, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().NavRefreshNode(ctx, fc.Args["nodePath"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) } func (ec *executionContext) fieldContext_Query_navRefreshNode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28040,40 +32172,28 @@ func (ec *executionContext) fieldContext_Query_navRefreshNode(ctx context.Contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_navRefreshNode_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_navGetStructContainers(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_navGetStructContainers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().NavGetStructContainers(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(*string), fc.Args["catalog"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.DatabaseStructContainers) - fc.Result = res - return ec.marshalNDatabaseStructContainers2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseStructContainers(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_navGetStructContainers, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().NavGetStructContainers(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(*string), fc.Args["catalog"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDatabaseStructContainers2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseStructContainers, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_navGetStructContainers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28084,6 +32204,8 @@ func (ec *executionContext) fieldContext_Query_navGetStructContainers(ctx contex IsResolver: true, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { + case "parentNode": + return ec.fieldContext_DatabaseStructContainers_parentNode(ctx, field) case "catalogList": return ec.fieldContext_DatabaseStructContainers_catalogList(ctx, field) case "schemaList": @@ -28105,43 +32227,81 @@ func (ec *executionContext) fieldContext_Query_navGetStructContainers(ctx contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_navGetStructContainers_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_rmListProjects(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_rmListProjects(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RmListProjects(rctx) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmListProjects, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().RmListProjects(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNRMProject2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_rmListProjects(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_RMProject_id(ctx, field) + case "name": + return ec.fieldContext_RMProject_name(ctx, field) + case "description": + return ec.fieldContext_RMProject_description(ctx, field) + case "shared": + return ec.fieldContext_RMProject_shared(ctx, field) + case "global": + return ec.fieldContext_RMProject_global(ctx, field) + case "createTime": + return ec.fieldContext_RMProject_createTime(ctx, field) + case "creator": + return ec.fieldContext_RMProject_creator(ctx, field) + case "projectPermissions": + return ec.fieldContext_RMProject_projectPermissions(ctx, field) + case "resourceTypes": + return ec.fieldContext_RMProject_resourceTypes(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type RMProject", field.Name) + }, } - res := resTmp.([]*model.RMProject) - fc.Result = res - return ec.marshalNRMProject2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_rmListSharedProjects(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmListSharedProjects, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().RmListSharedProjects(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNRMProject2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_Query_rmListProjects(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query_rmListSharedProjects(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -28157,10 +32317,16 @@ func (ec *executionContext) fieldContext_Query_rmListProjects(ctx context.Contex return ec.fieldContext_RMProject_description(ctx, field) case "shared": return ec.fieldContext_RMProject_shared(ctx, field) + case "global": + return ec.fieldContext_RMProject_global(ctx, field) case "createTime": return ec.fieldContext_RMProject_createTime(ctx, field) case "creator": return ec.fieldContext_RMProject_creator(ctx, field) + case "projectPermissions": + return ec.fieldContext_RMProject_projectPermissions(ctx, field) + case "resourceTypes": + return ec.fieldContext_RMProject_resourceTypes(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type RMProject", field.Name) }, @@ -28168,35 +32334,231 @@ func (ec *executionContext) fieldContext_Query_rmListProjects(ctx context.Contex return fc, nil } -func (ec *executionContext) _Query_rmListResources(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_rmListResources(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_rmProject(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmProject, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().RmProject(ctx, fc.Args["projectId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNRMProject2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProject, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_rmProject(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_RMProject_id(ctx, field) + case "name": + return ec.fieldContext_RMProject_name(ctx, field) + case "description": + return ec.fieldContext_RMProject_description(ctx, field) + case "shared": + return ec.fieldContext_RMProject_shared(ctx, field) + case "global": + return ec.fieldContext_RMProject_global(ctx, field) + case "createTime": + return ec.fieldContext_RMProject_createTime(ctx, field) + case "creator": + return ec.fieldContext_RMProject_creator(ctx, field) + case "projectPermissions": + return ec.fieldContext_RMProject_projectPermissions(ctx, field) + case "resourceTypes": + return ec.fieldContext_RMProject_resourceTypes(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type RMProject", field.Name) + }, } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_rmProject_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_rmListProjectPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmListProjectPermissions, + func(ctx context.Context) (any, error) { + return ec.resolvers.Query().RmListProjectPermissions(ctx) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminPermissionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_rmListProjectPermissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_AdminPermissionInfo_id(ctx, field) + case "label": + return ec.fieldContext_AdminPermissionInfo_label(ctx, field) + case "description": + return ec.fieldContext_AdminPermissionInfo_description(ctx, field) + case "provider": + return ec.fieldContext_AdminPermissionInfo_provider(ctx, field) + case "category": + return ec.fieldContext_AdminPermissionInfo_category(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminPermissionInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_rmListProjectGrantedPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmListProjectGrantedPermissions, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().RmListProjectGrantedPermissions(ctx, fc.Args["projectId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminObjectGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminObjectGrantInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_rmListProjectGrantedPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "subjectId": + return ec.fieldContext_AdminObjectGrantInfo_subjectId(ctx, field) + case "subjectType": + return ec.fieldContext_AdminObjectGrantInfo_subjectType(ctx, field) + case "objectPermissions": + return ec.fieldContext_AdminObjectGrantInfo_objectPermissions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminObjectGrantInfo", field.Name) + }, + } defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RmListResources(rctx, fc.Args["projectId"].(string), fc.Args["folder"].(*string), fc.Args["nameMask"].(*string), fc.Args["readProperties"].(*bool), fc.Args["readHistory"].(*bool)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_rmListProjectGrantedPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_rmListSubjectProjectsPermissionGrants(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmListSubjectProjectsPermissionGrants, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().RmListSubjectProjectsPermissionGrants(ctx, fc.Args["subjectId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNAdminObjectGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminObjectGrantInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_rmListSubjectProjectsPermissionGrants(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "subjectId": + return ec.fieldContext_AdminObjectGrantInfo_subjectId(ctx, field) + case "subjectType": + return ec.fieldContext_AdminObjectGrantInfo_subjectType(ctx, field) + case "objectPermissions": + return ec.fieldContext_AdminObjectGrantInfo_objectPermissions(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AdminObjectGrantInfo", field.Name) + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } - return graphql.Null + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_rmListSubjectProjectsPermissionGrants_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err } - res := resTmp.([]*model.RMResource) - fc.Result = res - return ec.marshalNRMResource2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query_rmListResources(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmListResources, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().RmListResources(ctx, fc.Args["projectId"].(string), fc.Args["folder"].(*string), fc.Args["nameMask"].(*string), fc.Args["readProperties"].(*bool), fc.Args["readHistory"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNRMResource2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_rmListResources(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28213,6 +32575,8 @@ func (ec *executionContext) fieldContext_Query_rmListResources(ctx context.Conte return ec.fieldContext_RMResource_folder(ctx, field) case "length": return ec.fieldContext_RMResource_length(ctx, field) + case "properties": + return ec.fieldContext_RMResource_properties(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type RMResource", field.Name) }, @@ -28226,40 +32590,28 @@ func (ec *executionContext) fieldContext_Query_rmListResources(ctx context.Conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_rmListResources_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_rmReadResourceAsString(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_rmReadResourceAsString(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().RmReadResourceAsString(rctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_rmReadResourceAsString, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().RmReadResourceAsString(ctx, fc.Args["projectId"].(string), fc.Args["resourcePath"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_rmReadResourceAsString(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28281,37 +32633,28 @@ func (ec *executionContext) fieldContext_Query_rmReadResourceAsString(ctx contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_rmReadResourceAsString_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlDialectInfo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlDialectInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLDialectInfo(rctx, fc.Args["connectionId"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.SQLDialectInfo) - fc.Result = res - return ec.marshalOSQLDialectInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDialectInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlDialectInfo, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLDialectInfo(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOSQLDialectInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDialectInfo, + true, + false, + ) } func (ec *executionContext) fieldContext_Query_sqlDialectInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28357,40 +32700,28 @@ func (ec *executionContext) fieldContext_Query_sqlDialectInfo(ctx context.Contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlDialectInfo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlListContexts(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlListContexts(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLListContexts(rctx, fc.Args["connectionId"].(*string), fc.Args["contextId"].(*string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLContextInfo) - fc.Result = res - return ec.marshalNSQLContextInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlListContexts, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLListContexts(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(*string), fc.Args["contextId"].(*string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLContextInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_sqlListContexts(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28403,8 +32734,12 @@ func (ec *executionContext) fieldContext_Query_sqlListContexts(ctx context.Conte switch field.Name { case "id": return ec.fieldContext_SQLContextInfo_id(ctx, field) + case "projectId": + return ec.fieldContext_SQLContextInfo_projectId(ctx, field) case "connectionId": return ec.fieldContext_SQLContextInfo_connectionId(ctx, field) + case "autoCommit": + return ec.fieldContext_SQLContextInfo_autoCommit(ctx, field) case "defaultCatalog": return ec.fieldContext_SQLContextInfo_defaultCatalog(ctx, field) case "defaultSchema": @@ -28422,37 +32757,28 @@ func (ec *executionContext) fieldContext_Query_sqlListContexts(ctx context.Conte ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlListContexts_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlCompletionProposals(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlCompletionProposals(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLCompletionProposals(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string), fc.Args["position"].(int), fc.Args["maxResults"].(*int), fc.Args["simpleMode"].(*bool)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.SQLCompletionProposal) - fc.Result = res - return ec.marshalOSQLCompletionProposal2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlCompletionProposals, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLCompletionProposals(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string), fc.Args["position"].(int), fc.Args["maxResults"].(*int), fc.Args["simpleMode"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalOSQLCompletionProposal2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal, + true, + false, + ) } func (ec *executionContext) fieldContext_Query_sqlCompletionProposals(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28494,40 +32820,28 @@ func (ec *executionContext) fieldContext_Query_sqlCompletionProposals(ctx contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlCompletionProposals_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlFormatQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlFormatQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLFormatQuery(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlFormatQuery, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLFormatQuery(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["query"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_sqlFormatQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28549,40 +32863,28 @@ func (ec *executionContext) fieldContext_Query_sqlFormatQuery(ctx context.Contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlFormatQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlSupportedOperations(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlSupportedOperations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLSupportedOperations(rctx, fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["attributeIndex"].(int)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DataTypeLogicalOperation) - fc.Result = res - return ec.marshalNDataTypeLogicalOperation2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperationᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlSupportedOperations, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLSupportedOperations(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["contextId"].(string), fc.Args["resultsId"].(string), fc.Args["attributeIndex"].(int)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNDataTypeLogicalOperation2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperationᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_sqlSupportedOperations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28612,40 +32914,28 @@ func (ec *executionContext) fieldContext_Query_sqlSupportedOperations(ctx contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlSupportedOperations_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlEntityQueryGenerators(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlEntityQueryGenerators(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLEntityQueryGenerators(rctx, fc.Args["nodePathList"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLQueryGenerator) - fc.Result = res - return ec.marshalNSQLQueryGenerator2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGeneratorᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlEntityQueryGenerators, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLEntityQueryGenerators(ctx, fc.Args["nodePathList"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLQueryGenerator2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGeneratorᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_sqlEntityQueryGenerators(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28679,46 +32969,34 @@ func (ec *executionContext) fieldContext_Query_sqlEntityQueryGenerators(ctx cont ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlEntityQueryGenerators_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlGenerateEntityQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlGenerateEntityQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLGenerateEntityQuery(rctx, fc.Args["generatorId"].(string), - func() interface{} { - if fc.Args["options"] == nil { - return nil - } - return fc.Args["options"].(interface{}) - }(), fc.Args["nodePathList"].([]string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlGenerateEntityQuery, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLGenerateEntityQuery(ctx, fc.Args["generatorId"].(string), + func() any { + if fc.Args["options"] == nil { + return nil + } + return fc.Args["options"].(any) + }(), fc.Args["nodePathList"].([]string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_sqlGenerateEntityQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28740,40 +33018,28 @@ func (ec *executionContext) fieldContext_Query_sqlGenerateEntityQuery(ctx contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlGenerateEntityQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlParseScript(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlParseScript(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLParseScript(rctx, fc.Args["connectionId"].(string), fc.Args["script"].(string)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLScriptInfo) - fc.Result = res - return ec.marshalNSQLScriptInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlParseScript, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLParseScript(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["script"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLScriptInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptInfo, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_sqlParseScript(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28799,40 +33065,28 @@ func (ec *executionContext) fieldContext_Query_sqlParseScript(ctx context.Contex ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlParseScript_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query_sqlParseQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query_sqlParseQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.resolvers.Query().SQLParseQuery(rctx, fc.Args["connectionId"].(string), fc.Args["script"].(string), fc.Args["position"].(int)) - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.SQLScriptQuery) - fc.Result = res - return ec.marshalNSQLScriptQuery2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlParseQuery, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLParseQuery(ctx, fc.Args["projectId"].(*string), fc.Args["connectionId"].(string), fc.Args["script"].(string), fc.Args["position"].(int)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNSQLScriptQuery2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery, + true, + true, + ) } func (ec *executionContext) fieldContext_Query_sqlParseQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28860,37 +33114,71 @@ func (ec *executionContext) fieldContext_Query_sqlParseQuery(ctx context.Context ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query_sqlParseQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } -func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query___type(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _Query_sqlGenerateGroupingQuery(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query_sqlGenerateGroupingQuery, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.resolvers.Query().SQLGenerateGroupingQuery(ctx, fc.Args["projectId"].(*string), fc.Args["contextId"].(string), fc.Args["connectionId"].(string), fc.Args["resultsId"].(string), fc.Args["columnNames"].([]string), fc.Args["functions"].([]string), fc.Args["showDuplicatesOnly"].(*bool)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_Query_sqlGenerateGroupingQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.introspectType(fc.Args["name"].(string)) - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_sqlGenerateGroupingQuery_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return fc, err } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query___type, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return ec.introspectType(fc.Args["name"].(string)) + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType, + true, + false, + ) } func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -28907,6 +33195,8 @@ func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -28919,8 +33209,8 @@ func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -28934,40 +33224,30 @@ func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field_Query___type_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Query___schema(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return ec.introspectSchema() - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Schema) - fc.Result = res - return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_Query___schema, + func(ctx context.Context) (any, error) { + return ec.introspectSchema() + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, nil, next) + }, + ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema, + true, + false, + ) } -func (ec *executionContext) fieldContext_Query___schema(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Query___schema(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Query", Field: field, @@ -28986,90 +33266,64 @@ func (ec *executionContext) fieldContext_Query___schema(ctx context.Context, fie case "subscriptionType": return ec.fieldContext___Schema_subscriptionType(ctx, field) case "directives": - return ec.fieldContext___Schema_directives(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type __Schema", field.Name) - }, - } - return fc, nil -} - -func (ec *executionContext) _RMProject_id(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return ec.fieldContext___Schema_directives(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Schema", field.Name) + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _RMProject_id(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMProject_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMProject_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMProject", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type ID does not have child fields") }, } return fc, nil } func (ec *executionContext) _RMProject_name(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMProject_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMProject_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMProject", Field: field, @@ -29083,34 +33337,24 @@ func (ec *executionContext) fieldContext_RMProject_name(ctx context.Context, fie } func (ec *executionContext) _RMProject_description(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_RMProject_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMProject_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMProject", Field: field, @@ -29124,37 +33368,55 @@ func (ec *executionContext) fieldContext_RMProject_description(ctx context.Conte } func (ec *executionContext) _RMProject_shared(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_shared(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Shared, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_shared, + func(ctx context.Context) (any, error) { + return obj.Shared, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_RMProject_shared(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMProject", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _RMProject_global(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_global, + func(ctx context.Context) (any, error) { + return obj.Global, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMProject_shared(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMProject_global(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMProject", Field: field, @@ -29168,37 +33430,24 @@ func (ec *executionContext) fieldContext_RMProject_shared(ctx context.Context, f } func (ec *executionContext) _RMProject_createTime(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_createTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CreateTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(time.Time) - fc.Result = res - return ec.marshalNDateTime2timeᚐTime(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_createTime, + func(ctx context.Context) (any, error) { + return obj.CreateTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDateTime2timeᚐTime, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMProject_createTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMProject_createTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMProject", Field: field, @@ -29212,37 +33461,24 @@ func (ec *executionContext) fieldContext_RMProject_createTime(ctx context.Contex } func (ec *executionContext) _RMProject_creator(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMProject_creator(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Creator, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_creator, + func(ctx context.Context) (any, error) { + return obj.Creator, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMProject_creator(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMProject_creator(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMProject", Field: field, @@ -29255,38 +33491,99 @@ func (ec *executionContext) fieldContext_RMProject_creator(ctx context.Context, return fc, nil } -func (ec *executionContext) _RMResource_name(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMResource_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) _RMProject_projectPermissions(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_projectPermissions, + func(ctx context.Context) (any, error) { + return obj.ProjectPermissions, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_RMProject_projectPermissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMProject", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _RMProject_resourceTypes(ctx context.Context, field graphql.CollectedField, obj *model.RMProject) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMProject_resourceTypes, + func(ctx context.Context) (any, error) { + return obj.ResourceTypes, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNRMResourceType2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceTypeᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_RMProject_resourceTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMProject", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_RMResourceType_id(ctx, field) + case "displayName": + return ec.fieldContext_RMResourceType_displayName(ctx, field) + case "icon": + return ec.fieldContext_RMResourceType_icon(ctx, field) + case "fileExtensions": + return ec.fieldContext_RMResourceType_fileExtensions(ctx, field) + case "rootFolder": + return ec.fieldContext_RMResourceType_rootFolder(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type RMResourceType", field.Name) + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _RMResource_name(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResource_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMResource_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMResource_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMResource", Field: field, @@ -29300,37 +33597,24 @@ func (ec *executionContext) fieldContext_RMResource_name(ctx context.Context, fi } func (ec *executionContext) _RMResource_folder(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMResource_folder(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Folder, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResource_folder, + func(ctx context.Context) (any, error) { + return obj.Folder, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMResource_folder(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMResource_folder(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMResource", Field: field, @@ -29344,37 +33628,24 @@ func (ec *executionContext) fieldContext_RMResource_folder(ctx context.Context, } func (ec *executionContext) _RMResource_length(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_RMResource_length(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Length, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResource_length, + func(ctx context.Context) (any, error) { + return obj.Length, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_RMResource_length(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMResource_length(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "RMResource", Field: field, @@ -29387,40 +33658,120 @@ func (ec *executionContext) fieldContext_RMResource_length(ctx context.Context, return fc, nil } -func (ec *executionContext) _SQLCompletionProposal_displayString(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_displayString(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _RMResource_properties(ctx context.Context, field graphql.CollectedField, obj *model.RMResource) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResource_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_RMResource_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMResource", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayString, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _RMResourceType_id(ctx context.Context, field graphql.CollectedField, obj *model.RMResourceType) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResourceType_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_RMResourceType_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMResourceType", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _RMResourceType_displayName(ctx context.Context, field graphql.CollectedField, obj *model.RMResourceType) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResourceType_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_RMResourceType_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMResourceType", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _RMResourceType_icon(ctx context.Context, field graphql.CollectedField, obj *model.RMResourceType) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResourceType_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_displayString(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_RMResourceType_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "SQLCompletionProposal", + Object: "RMResourceType", Field: field, IsMethod: false, IsResolver: false, @@ -29431,38 +33782,118 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_displayString(ctx return fc, nil } -func (ec *executionContext) _SQLCompletionProposal_type(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_type(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _RMResourceType_fileExtensions(ctx context.Context, field graphql.CollectedField, obj *model.RMResourceType) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResourceType_fileExtensions, + func(ctx context.Context) (any, error) { + return obj.FileExtensions, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_RMResourceType_fileExtensions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMResourceType", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _RMResourceType_rootFolder(ctx context.Context, field graphql.CollectedField, obj *model.RMResourceType) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_RMResourceType_rootFolder, + func(ctx context.Context) (any, error) { + return obj.RootFolder, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_RMResourceType_rootFolder(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "RMResourceType", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _SQLCompletionProposal_displayString(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_displayString, + func(ctx context.Context) (any, error) { + return obj.DisplayString, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SQLCompletionProposal_displayString(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLCompletionProposal", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SQLCompletionProposal_type(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29476,34 +33907,24 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_type(ctx context. } func (ec *executionContext) _SQLCompletionProposal_score(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_score(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Score, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_score, + func(ctx context.Context) (any, error) { + return obj.Score, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_score(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_score(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29517,37 +33938,24 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_score(ctx context } func (ec *executionContext) _SQLCompletionProposal_replacementString(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_replacementString(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReplacementString, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_replacementString, + func(ctx context.Context) (any, error) { + return obj.ReplacementString, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementString(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementString(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29561,37 +33969,24 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementString } func (ec *executionContext) _SQLCompletionProposal_replacementOffset(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_replacementOffset(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReplacementOffset, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_replacementOffset, + func(ctx context.Context) (any, error) { + return obj.ReplacementOffset, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementOffset(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementOffset(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29605,37 +34000,24 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementOffset } func (ec *executionContext) _SQLCompletionProposal_replacementLength(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_replacementLength(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReplacementLength, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_replacementLength, + func(ctx context.Context) (any, error) { + return obj.ReplacementLength, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementLength(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementLength(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29649,34 +34031,24 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_replacementLength } func (ec *executionContext) _SQLCompletionProposal_cursorPosition(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_cursorPosition(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CursorPosition, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_cursorPosition, + func(ctx context.Context) (any, error) { + return obj.CursorPosition, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_cursorPosition(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_cursorPosition(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29690,34 +34062,24 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_cursorPosition(ct } func (ec *executionContext) _SQLCompletionProposal_icon(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29731,34 +34093,24 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_icon(ctx context. } func (ec *executionContext) _SQLCompletionProposal_nodePath(ctx context.Context, field graphql.CollectedField, obj *model.SQLCompletionProposal) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLCompletionProposal_nodePath(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NodePath, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLCompletionProposal_nodePath, + func(ctx context.Context) (any, error) { + return obj.NodePath, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLCompletionProposal_nodePath(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLCompletionProposal_nodePath(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLCompletionProposal", Field: field, @@ -29772,37 +34124,55 @@ func (ec *executionContext) fieldContext_SQLCompletionProposal_nodePath(ctx cont } func (ec *executionContext) _SQLContextInfo_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLContextInfo_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SQLContextInfo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLContextInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_SQLContextInfo_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _SQLContextInfo_projectId(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLContextInfo_projectId, + func(ctx context.Context) (any, error) { + return obj.ProjectID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SQLContextInfo_projectId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLContextInfo", Field: field, @@ -29816,37 +34186,24 @@ func (ec *executionContext) fieldContext_SQLContextInfo_id(ctx context.Context, } func (ec *executionContext) _SQLContextInfo_connectionId(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_connectionId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConnectionID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLContextInfo_connectionId, + func(ctx context.Context) (any, error) { + return obj.ConnectionID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLContextInfo_connectionId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLContextInfo_connectionId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLContextInfo", Field: field, @@ -29859,35 +34216,56 @@ func (ec *executionContext) fieldContext_SQLContextInfo_connectionId(ctx context return fc, nil } -func (ec *executionContext) _SQLContextInfo_defaultCatalog(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_defaultCatalog(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultCatalog, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null +func (ec *executionContext) _SQLContextInfo_autoCommit(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLContextInfo_autoCommit, + func(ctx context.Context) (any, error) { + return obj.AutoCommit, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2ᚖbool, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_SQLContextInfo_autoCommit(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLContextInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SQLContextInfo_defaultCatalog(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLContextInfo_defaultCatalog, + func(ctx context.Context) (any, error) { + return obj.DefaultCatalog, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLContextInfo_defaultCatalog(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLContextInfo_defaultCatalog(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLContextInfo", Field: field, @@ -29901,34 +34279,24 @@ func (ec *executionContext) fieldContext_SQLContextInfo_defaultCatalog(ctx conte } func (ec *executionContext) _SQLContextInfo_defaultSchema(ctx context.Context, field graphql.CollectedField, obj *model.SQLContextInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLContextInfo_defaultSchema(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultSchema, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLContextInfo_defaultSchema, + func(ctx context.Context) (any, error) { + return obj.DefaultSchema, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLContextInfo_defaultSchema(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLContextInfo_defaultSchema(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLContextInfo", Field: field, @@ -29942,37 +34310,24 @@ func (ec *executionContext) fieldContext_SQLContextInfo_defaultSchema(ctx contex } func (ec *executionContext) _SQLDialectInfo_name(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -29986,37 +34341,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_name(ctx context.Context } func (ec *executionContext) _SQLDialectInfo_dataTypes(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_dataTypes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataTypes, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_dataTypes, + func(ctx context.Context) (any, error) { + return obj.DataTypes, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_dataTypes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_dataTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30030,37 +34372,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_dataTypes(ctx context.Co } func (ec *executionContext) _SQLDialectInfo_functions(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_functions(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Functions, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_functions, + func(ctx context.Context) (any, error) { + return obj.Functions, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_functions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_functions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30074,37 +34403,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_functions(ctx context.Co } func (ec *executionContext) _SQLDialectInfo_reservedWords(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_reservedWords(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReservedWords, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_reservedWords, + func(ctx context.Context) (any, error) { + return obj.ReservedWords, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_reservedWords(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_reservedWords(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30118,37 +34434,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_reservedWords(ctx contex } func (ec *executionContext) _SQLDialectInfo_quoteStrings(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_quoteStrings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.QuoteStrings, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([][]*string) - fc.Result = res - return ec.marshalNString2ᚕᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_quoteStrings, + func(ctx context.Context) (any, error) { + return obj.QuoteStrings, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_quoteStrings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_quoteStrings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30162,37 +34465,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_quoteStrings(ctx context } func (ec *executionContext) _SQLDialectInfo_singleLineComments(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_singleLineComments(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SingleLineComments, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*string) - fc.Result = res - return ec.marshalNString2ᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_singleLineComments, + func(ctx context.Context) (any, error) { + return obj.SingleLineComments, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_singleLineComments(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_singleLineComments(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30206,37 +34496,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_singleLineComments(ctx c } func (ec *executionContext) _SQLDialectInfo_multiLineComments(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_multiLineComments(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MultiLineComments, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([][]*string) - fc.Result = res - return ec.marshalNString2ᚕᚕᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_multiLineComments, + func(ctx context.Context) (any, error) { + return obj.MultiLineComments, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕᚕᚖstring, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_multiLineComments(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_multiLineComments(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30250,34 +34527,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_multiLineComments(ctx co } func (ec *executionContext) _SQLDialectInfo_catalogSeparator(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_catalogSeparator(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CatalogSeparator, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_catalogSeparator, + func(ctx context.Context) (any, error) { + return obj.CatalogSeparator, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_catalogSeparator(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_catalogSeparator(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30291,34 +34558,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_catalogSeparator(ctx con } func (ec *executionContext) _SQLDialectInfo_structSeparator(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_structSeparator(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StructSeparator, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_structSeparator, + func(ctx context.Context) (any, error) { + return obj.StructSeparator, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_structSeparator(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_structSeparator(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30332,34 +34589,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_structSeparator(ctx cont } func (ec *executionContext) _SQLDialectInfo_scriptDelimiter(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_scriptDelimiter(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ScriptDelimiter, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_scriptDelimiter, + func(ctx context.Context) (any, error) { + return obj.ScriptDelimiter, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_scriptDelimiter(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_scriptDelimiter(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30373,37 +34620,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_scriptDelimiter(ctx cont } func (ec *executionContext) _SQLDialectInfo_supportsExplainExecutionPlan(ctx context.Context, field graphql.CollectedField, obj *model.SQLDialectInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLDialectInfo_supportsExplainExecutionPlan(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsExplainExecutionPlan, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLDialectInfo_supportsExplainExecutionPlan, + func(ctx context.Context) (any, error) { + return obj.SupportsExplainExecutionPlan, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLDialectInfo_supportsExplainExecutionPlan(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLDialectInfo_supportsExplainExecutionPlan(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLDialectInfo", Field: field, @@ -30417,34 +34651,24 @@ func (ec *executionContext) fieldContext_SQLDialectInfo_supportsExplainExecution } func (ec *executionContext) _SQLExecuteInfo_statusMessage(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_statusMessage(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StatusMessage, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecuteInfo_statusMessage, + func(ctx context.Context) (any, error) { + return obj.StatusMessage, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLExecuteInfo_statusMessage(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecuteInfo_statusMessage(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecuteInfo", Field: field, @@ -30458,37 +34682,24 @@ func (ec *executionContext) fieldContext_SQLExecuteInfo_statusMessage(ctx contex } func (ec *executionContext) _SQLExecuteInfo_duration(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_duration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Duration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecuteInfo_duration, + func(ctx context.Context) (any, error) { + return obj.Duration, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecuteInfo_duration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecuteInfo_duration(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecuteInfo", Field: field, @@ -30502,34 +34713,55 @@ func (ec *executionContext) fieldContext_SQLExecuteInfo_duration(ctx context.Con } func (ec *executionContext) _SQLExecuteInfo_filterText(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_filterText(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FilterText, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecuteInfo_filterText, + func(ctx context.Context) (any, error) { + return obj.FilterText, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_SQLExecuteInfo_filterText(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLExecuteInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SQLExecuteInfo_fullQuery(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecuteInfo_fullQuery, + func(ctx context.Context) (any, error) { + return obj.FullQuery, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLExecuteInfo_filterText(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecuteInfo_fullQuery(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecuteInfo", Field: field, @@ -30543,37 +34775,24 @@ func (ec *executionContext) fieldContext_SQLExecuteInfo_filterText(ctx context.C } func (ec *executionContext) _SQLExecuteInfo_results(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecuteInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecuteInfo_results(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Results, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLQueryResults) - fc.Result = res - return ec.marshalNSQLQueryResults2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResultsᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecuteInfo_results, + func(ctx context.Context) (any, error) { + return obj.Results, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNSQLQueryResults2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResultsᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecuteInfo_results(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecuteInfo_results(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecuteInfo", Field: field, @@ -30599,37 +34818,24 @@ func (ec *executionContext) fieldContext_SQLExecuteInfo_results(ctx context.Cont } func (ec *executionContext) _SQLExecutionPlan_query(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlan) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlan_query(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Query, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlan_query, + func(ctx context.Context) (any, error) { + return obj.Query, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlan_query(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlan_query(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlan", Field: field, @@ -30643,37 +34849,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlan_query(ctx context.Cont } func (ec *executionContext) _SQLExecutionPlan_nodes(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlan) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlan_nodes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Nodes, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLExecutionPlanNode) - fc.Result = res - return ec.marshalNSQLExecutionPlanNode2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNodeᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlan_nodes, + func(ctx context.Context) (any, error) { + return obj.Nodes, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNSQLExecutionPlanNode2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNodeᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlan_nodes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlan_nodes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlan", Field: field, @@ -30705,37 +34898,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlan_nodes(ctx context.Cont } func (ec *executionContext) _SQLExecutionPlanNode_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -30749,34 +34929,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_id(ctx context.Con } func (ec *executionContext) _SQLExecutionPlanNode_parentId(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_parentId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ParentID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_parentId, + func(ctx context.Context) (any, error) { + return obj.ParentID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_parentId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_parentId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -30790,37 +34960,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_parentId(ctx conte } func (ec *executionContext) _SQLExecutionPlanNode_kind(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_kind(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Kind, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_kind, + func(ctx context.Context) (any, error) { + return obj.Kind, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_kind(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_kind(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -30834,34 +34991,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_kind(ctx context.C } func (ec *executionContext) _SQLExecutionPlanNode_name(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -30875,37 +35022,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_name(ctx context.C } func (ec *executionContext) _SQLExecutionPlanNode_type(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -30919,34 +35053,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_type(ctx context.C } func (ec *executionContext) _SQLExecutionPlanNode_condition(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_condition(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Condition, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_condition, + func(ctx context.Context) (any, error) { + return obj.Condition, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_condition(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_condition(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -30960,34 +35084,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_condition(ctx cont } func (ec *executionContext) _SQLExecutionPlanNode_description(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -31001,37 +35115,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_description(ctx co } func (ec *executionContext) _SQLExecutionPlanNode_properties(ctx context.Context, field graphql.CollectedField, obj *model.SQLExecutionPlanNode) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLExecutionPlanNode_properties(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Properties, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ObjectPropertyInfo) - fc.Result = res - return ec.marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLExecutionPlanNode_properties, + func(ctx context.Context) (any, error) { + return obj.Properties, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLExecutionPlanNode_properties(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLExecutionPlanNode_properties(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLExecutionPlanNode", Field: field, @@ -31045,6 +35146,8 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_properties(ctx con return ec.fieldContext_ObjectPropertyInfo_displayName(ctx, field) case "description": return ec.fieldContext_ObjectPropertyInfo_description(ctx, field) + case "hint": + return ec.fieldContext_ObjectPropertyInfo_hint(ctx, field) case "category": return ec.fieldContext_ObjectPropertyInfo_category(ctx, field) case "dataType": @@ -31061,6 +35164,14 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_properties(ctx con return ec.fieldContext_ObjectPropertyInfo_features(ctx, field) case "order": return ec.fieldContext_ObjectPropertyInfo_order(ctx, field) + case "supportedConfigurationTypes": + return ec.fieldContext_ObjectPropertyInfo_supportedConfigurationTypes(ctx, field) + case "required": + return ec.fieldContext_ObjectPropertyInfo_required(ctx, field) + case "scopes": + return ec.fieldContext_ObjectPropertyInfo_scopes(ctx, field) + case "conditions": + return ec.fieldContext_ObjectPropertyInfo_conditions(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ObjectPropertyInfo", field.Name) }, @@ -31069,37 +35180,24 @@ func (ec *executionContext) fieldContext_SQLExecutionPlanNode_properties(ctx con } func (ec *executionContext) _SQLQueryGenerator_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryGenerator_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLQueryGenerator_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryGenerator_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryGenerator", Field: field, @@ -31113,78 +35211,55 @@ func (ec *executionContext) fieldContext_SQLQueryGenerator_id(ctx context.Contex } func (ec *executionContext) _SQLQueryGenerator_label(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryGenerator_label, + func(ctx context.Context) (any, error) { + return obj.Label, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLQueryGenerator_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryGenerator_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryGenerator", Field: field, IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SQLQueryGenerator_description(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SQLQueryGenerator_description(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryGenerator_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLQueryGenerator_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryGenerator_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryGenerator", Field: field, @@ -31198,37 +35273,24 @@ func (ec *executionContext) fieldContext_SQLQueryGenerator_description(ctx conte } func (ec *executionContext) _SQLQueryGenerator_order(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_order(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Order, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryGenerator_order, + func(ctx context.Context) (any, error) { + return obj.Order, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLQueryGenerator_order(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryGenerator_order(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryGenerator", Field: field, @@ -31242,37 +35304,24 @@ func (ec *executionContext) fieldContext_SQLQueryGenerator_order(ctx context.Con } func (ec *executionContext) _SQLQueryGenerator_multiObject(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryGenerator) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryGenerator_multiObject(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MultiObject, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryGenerator_multiObject, + func(ctx context.Context) (any, error) { + return obj.MultiObject, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLQueryGenerator_multiObject(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryGenerator_multiObject(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryGenerator", Field: field, @@ -31286,34 +35335,24 @@ func (ec *executionContext) fieldContext_SQLQueryGenerator_multiObject(ctx conte } func (ec *executionContext) _SQLQueryResults_title(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_title(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Title, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryResults_title, + func(ctx context.Context) (any, error) { + return obj.Title, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLQueryResults_title(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryResults_title(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryResults", Field: field, @@ -31327,34 +35366,24 @@ func (ec *executionContext) fieldContext_SQLQueryResults_title(ctx context.Conte } func (ec *executionContext) _SQLQueryResults_updateRowCount(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_updateRowCount(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UpdateRowCount, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*float64) - fc.Result = res - return ec.marshalOFloat2ᚖfloat64(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryResults_updateRowCount, + func(ctx context.Context) (any, error) { + return obj.UpdateRowCount, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOFloat2ᚖfloat64, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLQueryResults_updateRowCount(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryResults_updateRowCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryResults", Field: field, @@ -31368,34 +35397,24 @@ func (ec *executionContext) fieldContext_SQLQueryResults_updateRowCount(ctx cont } func (ec *executionContext) _SQLQueryResults_sourceQuery(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_sourceQuery(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SourceQuery, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryResults_sourceQuery, + func(ctx context.Context) (any, error) { + return obj.SourceQuery, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLQueryResults_sourceQuery(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryResults_sourceQuery(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryResults", Field: field, @@ -31409,34 +35428,24 @@ func (ec *executionContext) fieldContext_SQLQueryResults_sourceQuery(ctx context } func (ec *executionContext) _SQLQueryResults_dataFormat(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_dataFormat(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataFormat, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ResultDataFormat) - fc.Result = res - return ec.marshalOResultDataFormat2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryResults_dataFormat, + func(ctx context.Context) (any, error) { + return obj.DataFormat, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLQueryResults_dataFormat(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryResults_dataFormat(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryResults", Field: field, @@ -31450,34 +35459,24 @@ func (ec *executionContext) fieldContext_SQLQueryResults_dataFormat(ctx context. } func (ec *executionContext) _SQLQueryResults_resultSet(ctx context.Context, field graphql.CollectedField, obj *model.SQLQueryResults) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLQueryResults_resultSet(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ResultSet, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.SQLResultSet) - fc.Result = res - return ec.marshalOSQLResultSet2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultSet(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLQueryResults_resultSet, + func(ctx context.Context) (any, error) { + return obj.ResultSet, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOSQLResultSet2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultSet, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLQueryResults_resultSet(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLQueryResults_resultSet(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLQueryResults", Field: field, @@ -31491,12 +35490,24 @@ func (ec *executionContext) fieldContext_SQLQueryResults_resultSet(ctx context.C return ec.fieldContext_SQLResultSet_columns(ctx, field) case "rows": return ec.fieldContext_SQLResultSet_rows(ctx, field) + case "rowsWithMetaData": + return ec.fieldContext_SQLResultSet_rowsWithMetaData(ctx, field) case "singleEntity": return ec.fieldContext_SQLResultSet_singleEntity(ctx, field) case "hasMoreData": return ec.fieldContext_SQLResultSet_hasMoreData(ctx, field) case "hasRowIdentifier": return ec.fieldContext_SQLResultSet_hasRowIdentifier(ctx, field) + case "hasChildrenCollection": + return ec.fieldContext_SQLResultSet_hasChildrenCollection(ctx, field) + case "hasDynamicTrace": + return ec.fieldContext_SQLResultSet_hasDynamicTrace(ctx, field) + case "isSupportsDataFilter": + return ec.fieldContext_SQLResultSet_isSupportsDataFilter(ctx, field) + case "readOnly": + return ec.fieldContext_SQLResultSet_readOnly(ctx, field) + case "readOnlyStatus": + return ec.fieldContext_SQLResultSet_readOnlyStatus(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type SQLResultSet", field.Name) }, @@ -31505,37 +35516,24 @@ func (ec *executionContext) fieldContext_SQLQueryResults_resultSet(ctx context.C } func (ec *executionContext) _SQLResultColumn_position(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_position(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Position, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_position, + func(ctx context.Context) (any, error) { + return obj.Position, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_position(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_position(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31549,34 +35547,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_position(ctx context.Co } func (ec *executionContext) _SQLResultColumn_name(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31590,34 +35578,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_name(ctx context.Contex } func (ec *executionContext) _SQLResultColumn_label(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_label, + func(ctx context.Context) (any, error) { + return obj.Label, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31631,34 +35609,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_label(ctx context.Conte } func (ec *executionContext) _SQLResultColumn_icon(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31672,34 +35640,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_icon(ctx context.Contex } func (ec *executionContext) _SQLResultColumn_entityName(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_entityName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EntityName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_entityName, + func(ctx context.Context) (any, error) { + return obj.EntityName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_entityName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_entityName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31713,34 +35671,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_entityName(ctx context. } func (ec *executionContext) _SQLResultColumn_dataKind(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_dataKind(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DataKind, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_dataKind, + func(ctx context.Context) (any, error) { + return obj.DataKind, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_dataKind(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_dataKind(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31754,34 +35702,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_dataKind(ctx context.Co } func (ec *executionContext) _SQLResultColumn_typeName(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_typeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.TypeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_typeName, + func(ctx context.Context) (any, error) { + return obj.TypeName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_typeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_typeName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31795,34 +35733,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_typeName(ctx context.Co } func (ec *executionContext) _SQLResultColumn_fullTypeName(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_fullTypeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.FullTypeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_fullTypeName, + func(ctx context.Context) (any, error) { + return obj.FullTypeName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_fullTypeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_fullTypeName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31836,34 +35764,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_fullTypeName(ctx contex } func (ec *executionContext) _SQLResultColumn_maxLength(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_maxLength(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MaxLength, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*float64) - fc.Result = res - return ec.marshalOFloat2ᚖfloat64(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_maxLength, + func(ctx context.Context) (any, error) { + return obj.MaxLength, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOFloat2ᚖfloat64, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_maxLength(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_maxLength(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31877,34 +35795,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_maxLength(ctx context.C } func (ec *executionContext) _SQLResultColumn_scale(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_scale(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Scale, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_scale, + func(ctx context.Context) (any, error) { + return obj.Scale, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_scale(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_scale(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31918,34 +35826,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_scale(ctx context.Conte } func (ec *executionContext) _SQLResultColumn_precision(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_precision(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Precision, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_precision, + func(ctx context.Context) (any, error) { + return obj.Precision, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOInt2ᚖint, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_precision(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_precision(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -31959,37 +35857,55 @@ func (ec *executionContext) fieldContext_SQLResultColumn_precision(ctx context.C } func (ec *executionContext) _SQLResultColumn_required(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_required(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Required, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_required, + func(ctx context.Context) (any, error) { + return obj.Required, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SQLResultColumn_required(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLResultColumn", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SQLResultColumn_autoGenerated(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_autoGenerated, + func(ctx context.Context) (any, error) { + return obj.AutoGenerated, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_required(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_autoGenerated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -32003,37 +35919,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_required(ctx context.Co } func (ec *executionContext) _SQLResultColumn_readOnly(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_readOnly(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReadOnly, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_readOnly, + func(ctx context.Context) (any, error) { + return obj.ReadOnly, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_readOnly(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_readOnly(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -32047,34 +35950,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_readOnly(ctx context.Co } func (ec *executionContext) _SQLResultColumn_readOnlyStatus(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_readOnlyStatus(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ReadOnlyStatus, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_readOnlyStatus, + func(ctx context.Context) (any, error) { + return obj.ReadOnlyStatus, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_readOnlyStatus(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_readOnlyStatus(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -32088,37 +35981,24 @@ func (ec *executionContext) fieldContext_SQLResultColumn_readOnlyStatus(ctx cont } func (ec *executionContext) _SQLResultColumn_supportedOperations(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultColumn_supportedOperations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportedOperations, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.DataTypeLogicalOperation) - fc.Result = res - return ec.marshalNDataTypeLogicalOperation2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperationᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_supportedOperations, + func(ctx context.Context) (any, error) { + return obj.SupportedOperations, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDataTypeLogicalOperation2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperationᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLResultColumn_supportedOperations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultColumn_supportedOperations(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultColumn", Field: field, @@ -32139,38 +36019,134 @@ func (ec *executionContext) fieldContext_SQLResultColumn_supportedOperations(ctx return fc, nil } -func (ec *executionContext) _SQLResultSet_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_id(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _SQLResultColumn_description(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultColumn) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultColumn_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.1.3") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_SQLResultColumn_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLResultColumn", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _SQLResultRowMetaData_data(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultRowMetaData) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultRowMetaData_data, + func(ctx context.Context) (any, error) { + return obj.Data, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2ᚕinterface, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SQLResultRowMetaData_data(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLResultRowMetaData", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _SQLResultRowMetaData_metaData(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultRowMetaData) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultRowMetaData_metaData, + func(ctx context.Context) (any, error) { + return obj.MetaData, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_SQLResultRowMetaData_metaData(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLResultRowMetaData", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SQLResultSet_id(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLResultSet_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultSet", Field: field, @@ -32184,34 +36160,24 @@ func (ec *executionContext) fieldContext_SQLResultSet_id(ctx context.Context, fi } func (ec *executionContext) _SQLResultSet_columns(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_columns(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Columns, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.SQLResultColumn) - fc.Result = res - return ec.marshalOSQLResultColumn2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_columns, + func(ctx context.Context) (any, error) { + return obj.Columns, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOSQLResultColumn2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultSet_columns(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_columns(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultSet", Field: field, @@ -32243,12 +36209,16 @@ func (ec *executionContext) fieldContext_SQLResultSet_columns(ctx context.Contex return ec.fieldContext_SQLResultColumn_precision(ctx, field) case "required": return ec.fieldContext_SQLResultColumn_required(ctx, field) + case "autoGenerated": + return ec.fieldContext_SQLResultColumn_autoGenerated(ctx, field) case "readOnly": return ec.fieldContext_SQLResultColumn_readOnly(ctx, field) case "readOnlyStatus": return ec.fieldContext_SQLResultColumn_readOnlyStatus(ctx, field) case "supportedOperations": return ec.fieldContext_SQLResultColumn_supportedOperations(ctx, field) + case "description": + return ec.fieldContext_SQLResultColumn_description(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type SQLResultColumn", field.Name) }, @@ -32257,34 +36227,24 @@ func (ec *executionContext) fieldContext_SQLResultSet_columns(ctx context.Contex } func (ec *executionContext) _SQLResultSet_rows(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_rows(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Rows, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([][]interface{}) - fc.Result = res - return ec.marshalOObject2ᚕᚕinterface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_rows, + func(ctx context.Context) (any, error) { + return obj.Rows, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2ᚕᚕinterface, + true, + false, + ) } -func (ec *executionContext) fieldContext_SQLResultSet_rows(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_rows(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultSet", Field: field, @@ -32297,38 +36257,78 @@ func (ec *executionContext) fieldContext_SQLResultSet_rows(ctx context.Context, return fc, nil } -func (ec *executionContext) _SQLResultSet_singleEntity(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_singleEntity(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SingleEntity, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null +func (ec *executionContext) _SQLResultSet_rowsWithMetaData(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_rowsWithMetaData, + func(ctx context.Context) (any, error) { + return obj.RowsWithMetaData, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.5") + if err != nil { + var zeroVal []*model.SQLResultRowMetaData + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []*model.SQLResultRowMetaData + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOSQLResultRowMetaData2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowMetaData, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_SQLResultSet_rowsWithMetaData(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SQLResultSet", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "data": + return ec.fieldContext_SQLResultRowMetaData_data(ctx, field) + case "metaData": + return ec.fieldContext_SQLResultRowMetaData_metaData(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type SQLResultRowMetaData", field.Name) + }, } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return fc, nil } -func (ec *executionContext) fieldContext_SQLResultSet_singleEntity(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) _SQLResultSet_singleEntity(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_singleEntity, + func(ctx context.Context) (any, error) { + return obj.SingleEntity, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SQLResultSet_singleEntity(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultSet", Field: field, @@ -32342,37 +36342,24 @@ func (ec *executionContext) fieldContext_SQLResultSet_singleEntity(ctx context.C } func (ec *executionContext) _SQLResultSet_hasMoreData(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_hasMoreData(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HasMoreData, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_hasMoreData, + func(ctx context.Context) (any, error) { + return obj.HasMoreData, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLResultSet_hasMoreData(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_hasMoreData(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultSet", Field: field, @@ -32386,37 +36373,24 @@ func (ec *executionContext) fieldContext_SQLResultSet_hasMoreData(ctx context.Co } func (ec *executionContext) _SQLResultSet_hasRowIdentifier(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLResultSet_hasRowIdentifier(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HasRowIdentifier, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_hasRowIdentifier, + func(ctx context.Context) (any, error) { + return obj.HasRowIdentifier, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLResultSet_hasRowIdentifier(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_hasRowIdentifier(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SQLResultSet", Field: field, @@ -32429,222 +36403,199 @@ func (ec *executionContext) fieldContext_SQLResultSet_hasRowIdentifier(ctx conte return fc, nil } -func (ec *executionContext) _SQLScriptInfo_queries(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLScriptInfo_queries(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Queries, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.SQLScriptQuery) - fc.Result = res - return ec.marshalNSQLScriptQuery2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQueryᚄ(ctx, field.Selections, res) +func (ec *executionContext) _SQLResultSet_hasChildrenCollection(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_hasChildrenCollection, + func(ctx context.Context) (any, error) { + return obj.HasChildrenCollection, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLScriptInfo_queries(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_hasChildrenCollection(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "SQLScriptInfo", + Object: "SQLResultSet", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "start": - return ec.fieldContext_SQLScriptQuery_start(ctx, field) - case "end": - return ec.fieldContext_SQLScriptQuery_end(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type SQLScriptQuery", field.Name) + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _SQLScriptQuery_start(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptQuery) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLScriptQuery_start(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Start, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) +func (ec *executionContext) _SQLResultSet_hasDynamicTrace(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_hasDynamicTrace, + func(ctx context.Context) (any, error) { + return obj.HasDynamicTrace, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.2") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLScriptQuery_start(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_hasDynamicTrace(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "SQLScriptQuery", + Object: "SQLResultSet", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _SQLScriptQuery_end(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptQuery) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SQLScriptQuery_end(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.End, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(int) - fc.Result = res - return ec.marshalNInt2int(ctx, field.Selections, res) +func (ec *executionContext) _SQLResultSet_isSupportsDataFilter(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_isSupportsDataFilter, + func(ctx context.Context) (any, error) { + return obj.IsSupportsDataFilter, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SQLScriptQuery_end(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_isSupportsDataFilter(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "SQLScriptQuery", + Object: "SQLResultSet", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_name(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _SQLResultSet_readOnly(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_readOnly, + func(ctx context.Context) (any, error) { + return obj.ReadOnly, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.1") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_readOnly(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ServerConfig", + Object: "SQLResultSet", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_version(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_version(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Version, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _SQLResultSet_readOnlyStatus(ctx context.Context, field graphql.CollectedField, obj *model.SQLResultSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLResultSet_readOnlyStatus, + func(ctx context.Context) (any, error) { + return obj.ReadOnlyStatus, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.1") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerConfig_version(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLResultSet_readOnlyStatus(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ServerConfig", + Object: "SQLResultSet", Field: field, IsMethod: false, IsResolver: false, @@ -32655,172 +36606,126 @@ func (ec *executionContext) fieldContext_ServerConfig_version(ctx context.Contex return fc, nil } -func (ec *executionContext) _ServerConfig_workspaceId(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_workspaceId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.WorkspaceID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) +func (ec *executionContext) _SQLScriptInfo_queries(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLScriptInfo_queries, + func(ctx context.Context) (any, error) { + return obj.Queries, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNSQLScriptQuery2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQueryᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_workspaceId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLScriptInfo_queries(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ServerConfig", + Object: "SQLScriptInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + switch field.Name { + case "start": + return ec.fieldContext_SQLScriptQuery_start(ctx, field) + case "end": + return ec.fieldContext_SQLScriptQuery_end(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type SQLScriptQuery", field.Name) }, } return fc, nil } -func (ec *executionContext) _ServerConfig_serverURL(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_serverURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerURL, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _SQLScriptQuery_start(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptQuery) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLScriptQuery_start, + func(ctx context.Context) (any, error) { + return obj.Start, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_serverURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLScriptQuery_start(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ServerConfig", + Object: "SQLScriptQuery", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_rootURI(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_rootURI(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RootURI, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _SQLScriptQuery_end(ctx context.Context, field graphql.CollectedField, obj *model.SQLScriptQuery) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SQLScriptQuery_end, + func(ctx context.Context) (any, error) { + return obj.End, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_rootURI(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SQLScriptQuery_end(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ServerConfig", + Object: "SQLScriptQuery", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_hostName(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_hostName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.HostName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _SecretInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.SecretInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SecretInfo_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_hostName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SecretInfo_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ServerConfig", + Object: "SecretInfo", Field: field, IsMethod: false, IsResolver: false, @@ -32831,199 +36736,149 @@ func (ec *executionContext) fieldContext_ServerConfig_hostName(ctx context.Conte return fc, nil } -func (ec *executionContext) _ServerConfig_anonymousAccessEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_anonymousAccessEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AnonymousAccessEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _SecretInfo_secretId(ctx context.Context, field graphql.CollectedField, obj *model.SecretInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SecretInfo_secretId, + func(ctx context.Context) (any, error) { + return obj.SecretID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_anonymousAccessEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SecretInfo_secretId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "ServerConfig", + Object: "SecretInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_authenticationEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_authenticationEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthenticationEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_name(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_authenticationEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_supportsCustomConnections(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportsCustomConnections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsCustomConnections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_version(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_version, + func(ctx context.Context) (any, error) { + return obj.Version, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_supportsCustomConnections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_version(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_supportsConnectionBrowser(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportsConnectionBrowser(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsConnectionBrowser, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_workspaceId(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_workspaceId, + func(ctx context.Context) (any, error) { + return obj.WorkspaceID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_supportsConnectionBrowser(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_workspaceId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type ID does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_supportsWorkspaces(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportsWorkspaces(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportsWorkspaces, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_anonymousAccessEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_anonymousAccessEnabled, + func(ctx context.Context) (any, error) { + return obj.AnonymousAccessEnabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_supportsWorkspaces(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_anonymousAccessEnabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33036,35 +36891,25 @@ func (ec *executionContext) fieldContext_ServerConfig_supportsWorkspaces(ctx con return fc, nil } -func (ec *executionContext) _ServerConfig_resourceManagerEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_resourceManagerEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ResourceManagerEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_supportsCustomConnections(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_supportsCustomConnections, + func(ctx context.Context) (any, error) { + return obj.SupportsCustomConnections, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_resourceManagerEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_supportsCustomConnections(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33077,35 +36922,25 @@ func (ec *executionContext) fieldContext_ServerConfig_resourceManagerEnabled(ctx return fc, nil } -func (ec *executionContext) _ServerConfig_publicCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_publicCredentialsSaveEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PublicCredentialsSaveEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_resourceManagerEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_resourceManagerEnabled, + func(ctx context.Context) (any, error) { + return obj.ResourceManagerEnabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_publicCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_resourceManagerEnabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33118,35 +36953,41 @@ func (ec *executionContext) fieldContext_ServerConfig_publicCredentialsSaveEnabl return fc, nil } -func (ec *executionContext) _ServerConfig_adminCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_adminCredentialsSaveEnabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AdminCredentialsSaveEnabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_secretManagerEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_secretManagerEnabled, + func(ctx context.Context) (any, error) { + return obj.SecretManagerEnabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.2") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_adminCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_secretManagerEnabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33159,38 +37000,25 @@ func (ec *executionContext) fieldContext_ServerConfig_adminCredentialsSaveEnable return fc, nil } -func (ec *executionContext) _ServerConfig_licenseRequired(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_licenseRequired(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseRequired, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_publicCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_publicCredentialsSaveEnabled, + func(ctx context.Context) (any, error) { + return obj.PublicCredentialsSaveEnabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_licenseRequired(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_publicCredentialsSaveEnabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33203,38 +37031,25 @@ func (ec *executionContext) fieldContext_ServerConfig_licenseRequired(ctx contex return fc, nil } -func (ec *executionContext) _ServerConfig_licenseValid(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_licenseValid(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LicenseValid, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_adminCredentialsSaveEnabled(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_adminCredentialsSaveEnabled, + func(ctx context.Context) (any, error) { + return obj.AdminCredentialsSaveEnabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_licenseValid(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_adminCredentialsSaveEnabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33247,76 +37062,103 @@ func (ec *executionContext) fieldContext_ServerConfig_licenseValid(ctx context.C return fc, nil } -func (ec *executionContext) _ServerConfig_sessionExpireTime(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_sessionExpireTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SessionExpireTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*int) - fc.Result = res - return ec.marshalOInt2ᚖint(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_licenseRequired(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_licenseRequired, + func(ctx context.Context) (any, error) { + return obj.LicenseRequired, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_sessionExpireTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_licenseRequired(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Int does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_localHostAddress(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_localHostAddress(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LocalHostAddress, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null +func (ec *executionContext) _ServerConfig_licenseValid(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_licenseValid, + func(ctx context.Context) (any, error) { + return obj.LicenseValid, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_ServerConfig_licenseValid(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "ServerConfig", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _ServerConfig_licenseStatus(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_licenseStatus, + func(ctx context.Context) (any, error) { + return obj.LicenseStatus, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.5") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerConfig_localHostAddress(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_licenseStatus(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33330,34 +37172,24 @@ func (ec *executionContext) fieldContext_ServerConfig_localHostAddress(ctx conte } func (ec *executionContext) _ServerConfig_configurationMode(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_configurationMode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConfigurationMode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_configurationMode, + func(ctx context.Context) (any, error) { + return obj.ConfigurationMode, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_configurationMode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_configurationMode(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33371,34 +37203,24 @@ func (ec *executionContext) fieldContext_ServerConfig_configurationMode(ctx cont } func (ec *executionContext) _ServerConfig_developmentMode(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_developmentMode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DevelopmentMode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_developmentMode, + func(ctx context.Context) (any, error) { + return obj.DevelopmentMode, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_developmentMode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_developmentMode(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33411,35 +37233,25 @@ func (ec *executionContext) fieldContext_ServerConfig_developmentMode(ctx contex return fc, nil } -func (ec *executionContext) _ServerConfig_redirectOnFederatedAuth(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_redirectOnFederatedAuth(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.RedirectOnFederatedAuth, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*bool) - fc.Result = res - return ec.marshalOBoolean2ᚖbool(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_distributed(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_distributed, + func(ctx context.Context) (any, error) { + return obj.Distributed, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_redirectOnFederatedAuth(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_distributed(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33453,37 +37265,24 @@ func (ec *executionContext) fieldContext_ServerConfig_redirectOnFederatedAuth(ct } func (ec *executionContext) _ServerConfig_enabledFeatures(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_enabledFeatures(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EnabledFeatures, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_enabledFeatures, + func(ctx context.Context) (any, error) { + return obj.EnabledFeatures, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_enabledFeatures(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_enabledFeatures(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33496,38 +37295,41 @@ func (ec *executionContext) fieldContext_ServerConfig_enabledFeatures(ctx contex return fc, nil } -func (ec *executionContext) _ServerConfig_enabledAuthProviders(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_enabledAuthProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EnabledAuthProviders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_disabledBetaFeatures(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_disabledBetaFeatures, + func(ctx context.Context) (any, error) { + return obj.DisabledBetaFeatures, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.0.5") + if err != nil { + var zeroVal []string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚕstringᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerConfig_enabledAuthProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_disabledBetaFeatures(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33540,87 +37342,72 @@ func (ec *executionContext) fieldContext_ServerConfig_enabledAuthProviders(ctx c return fc, nil } -func (ec *executionContext) _ServerConfig_supportedLanguages(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_supportedLanguages(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SupportedLanguages, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ServerLanguage) - fc.Result = res - return ec.marshalNServerLanguage2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguageᚄ(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_serverFeatures(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_serverFeatures, + func(ctx context.Context) (any, error) { + return obj.ServerFeatures, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.0") + if err != nil { + var zeroVal []string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚕstringᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerConfig_supportedLanguages(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_serverFeatures(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "isoCode": - return ec.fieldContext_ServerLanguage_isoCode(ctx, field) - case "displayName": - return ec.fieldContext_ServerLanguage_displayName(ctx, field) - case "nativeName": - return ec.fieldContext_ServerLanguage_nativeName(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerLanguage", field.Name) + return nil, errors.New("field of type ID does not have child fields") }, } return fc, nil } -func (ec *executionContext) _ServerConfig_services(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_services(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Services, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]*model.WebServiceConfig) - fc.Result = res - return ec.marshalOWebServiceConfig2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebServiceConfig(ctx, field.Selections, res) +func (ec *executionContext) _ServerConfig_supportedLanguages(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_supportedLanguages, + func(ctx context.Context) (any, error) { + return obj.SupportedLanguages, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNServerLanguage2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguageᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_services(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_supportedLanguages(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33628,53 +37415,38 @@ func (ec *executionContext) fieldContext_ServerConfig_services(ctx context.Conte IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { - case "id": - return ec.fieldContext_WebServiceConfig_id(ctx, field) - case "name": - return ec.fieldContext_WebServiceConfig_name(ctx, field) - case "description": - return ec.fieldContext_WebServiceConfig_description(ctx, field) - case "bundleVersion": - return ec.fieldContext_WebServiceConfig_bundleVersion(ctx, field) + case "isoCode": + return ec.fieldContext_ServerLanguage_isoCode(ctx, field) + case "displayName": + return ec.fieldContext_ServerLanguage_displayName(ctx, field) + case "nativeName": + return ec.fieldContext_ServerLanguage_nativeName(ctx, field) } - return nil, fmt.Errorf("no field named %q was found under type WebServiceConfig", field.Name) + return nil, fmt.Errorf("no field named %q was found under type ServerLanguage", field.Name) }, } return fc, nil } func (ec *executionContext) _ServerConfig_productConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_productConfiguration(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProductConfiguration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_productConfiguration, + func(ctx context.Context) (any, error) { + return obj.ProductConfiguration, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_productConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_productConfiguration(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33688,37 +37460,24 @@ func (ec *executionContext) fieldContext_ServerConfig_productConfiguration(ctx c } func (ec *executionContext) _ServerConfig_productInfo(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_productInfo(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ProductInfo, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ProductInfo) - fc.Result = res - return ec.marshalNProductInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductInfo(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_productInfo, + func(ctx context.Context) (any, error) { + return obj.ProductInfo, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNProductInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductInfo, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_productInfo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_productInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33742,6 +37501,8 @@ func (ec *executionContext) fieldContext_ServerConfig_productInfo(ctx context.Co return ec.fieldContext_ProductInfo_licenseInfo(ctx, field) case "latestVersionInfo": return ec.fieldContext_ProductInfo_latestVersionInfo(ctx, field) + case "productPurchaseURL": + return ec.fieldContext_ProductInfo_productPurchaseURL(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ProductInfo", field.Name) }, @@ -33750,37 +37511,24 @@ func (ec *executionContext) fieldContext_ServerConfig_productInfo(ctx context.Co } func (ec *executionContext) _ServerConfig_defaultNavigatorSettings(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_defaultNavigatorSettings(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultNavigatorSettings, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.NavigatorSettings) - fc.Result = res - return ec.marshalNNavigatorSettings2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettings(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_defaultNavigatorSettings, + func(ctx context.Context) (any, error) { + return obj.DefaultNavigatorSettings, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNNavigatorSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettings, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_defaultNavigatorSettings(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_defaultNavigatorSettings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33810,37 +37558,24 @@ func (ec *executionContext) fieldContext_ServerConfig_defaultNavigatorSettings(c } func (ec *executionContext) _ServerConfig_disabledDrivers(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_disabledDrivers(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisabledDrivers, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNID2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_disabledDrivers, + func(ctx context.Context) (any, error) { + return obj.DisabledDrivers, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_disabledDrivers(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_disabledDrivers(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33854,37 +37589,24 @@ func (ec *executionContext) fieldContext_ServerConfig_disabledDrivers(ctx contex } func (ec *executionContext) _ServerConfig_resourceQuotas(ctx context.Context, field graphql.CollectedField, obj *model.ServerConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerConfig_resourceQuotas(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ResourceQuotas, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerConfig_resourceQuotas, + func(ctx context.Context) (any, error) { + return obj.ResourceQuotas, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerConfig_resourceQuotas(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerConfig_resourceQuotas(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerConfig", Field: field, @@ -33898,34 +37620,24 @@ func (ec *executionContext) fieldContext_ServerConfig_resourceQuotas(ctx context } func (ec *executionContext) _ServerError_message(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerError_message, + func(ctx context.Context) (any, error) { + return obj.Message, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerError_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerError_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerError", Field: field, @@ -33939,34 +37651,24 @@ func (ec *executionContext) fieldContext_ServerError_message(ctx context.Context } func (ec *executionContext) _ServerError_errorCode(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_errorCode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ErrorCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerError_errorCode, + func(ctx context.Context) (any, error) { + return obj.ErrorCode, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerError_errorCode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerError_errorCode(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerError", Field: field, @@ -33980,34 +37682,24 @@ func (ec *executionContext) fieldContext_ServerError_errorCode(ctx context.Conte } func (ec *executionContext) _ServerError_errorType(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_errorType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ErrorType, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerError_errorType, + func(ctx context.Context) (any, error) { + return obj.ErrorType, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerError_errorType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerError_errorType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerError", Field: field, @@ -34021,34 +37713,24 @@ func (ec *executionContext) fieldContext_ServerError_errorType(ctx context.Conte } func (ec *executionContext) _ServerError_stackTrace(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_stackTrace(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.StackTrace, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerError_stackTrace, + func(ctx context.Context) (any, error) { + return obj.StackTrace, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerError_stackTrace(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerError_stackTrace(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerError", Field: field, @@ -34062,34 +37744,24 @@ func (ec *executionContext) fieldContext_ServerError_stackTrace(ctx context.Cont } func (ec *executionContext) _ServerError_causedBy(ctx context.Context, field graphql.CollectedField, obj *model.ServerError) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerError_causedBy(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CausedBy, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*model.ServerError) - fc.Result = res - return ec.marshalOServerError2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerError_causedBy, + func(ctx context.Context) (any, error) { + return obj.CausedBy, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerError_causedBy(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerError_causedBy(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerError", Field: field, @@ -34115,37 +37787,24 @@ func (ec *executionContext) fieldContext_ServerError_causedBy(ctx context.Contex } func (ec *executionContext) _ServerLanguage_isoCode(ctx context.Context, field graphql.CollectedField, obj *model.ServerLanguage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerLanguage_isoCode(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsoCode, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerLanguage_isoCode, + func(ctx context.Context) (any, error) { + return obj.IsoCode, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_ServerLanguage_isoCode(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerLanguage_isoCode(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerLanguage", Field: field, @@ -34159,34 +37818,24 @@ func (ec *executionContext) fieldContext_ServerLanguage_isoCode(ctx context.Cont } func (ec *executionContext) _ServerLanguage_displayName(ctx context.Context, field graphql.CollectedField, obj *model.ServerLanguage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerLanguage_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerLanguage_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerLanguage_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerLanguage_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerLanguage", Field: field, @@ -34200,34 +37849,24 @@ func (ec *executionContext) fieldContext_ServerLanguage_displayName(ctx context. } func (ec *executionContext) _ServerLanguage_nativeName(ctx context.Context, field graphql.CollectedField, obj *model.ServerLanguage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerLanguage_nativeName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.NativeName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerLanguage_nativeName, + func(ctx context.Context) (any, error) { + return obj.NativeName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerLanguage_nativeName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerLanguage_nativeName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerLanguage", Field: field, @@ -34241,34 +37880,24 @@ func (ec *executionContext) fieldContext_ServerLanguage_nativeName(ctx context.C } func (ec *executionContext) _ServerMessage_time(ctx context.Context, field graphql.CollectedField, obj *model.ServerMessage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerMessage_time(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Time, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerMessage_time, + func(ctx context.Context) (any, error) { + return obj.Time, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerMessage_time(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerMessage_time(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerMessage", Field: field, @@ -34282,34 +37911,24 @@ func (ec *executionContext) fieldContext_ServerMessage_time(ctx context.Context, } func (ec *executionContext) _ServerMessage_message(ctx context.Context, field graphql.CollectedField, obj *model.ServerMessage) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_ServerMessage_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_ServerMessage_message, + func(ctx context.Context) (any, error) { + return obj.Message, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_ServerMessage_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_ServerMessage_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "ServerMessage", Field: field, @@ -34323,37 +37942,24 @@ func (ec *executionContext) fieldContext_ServerMessage_message(ctx context.Conte } func (ec *executionContext) _SessionInfo_createTime(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_createTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CreateTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_createTime, + func(ctx context.Context) (any, error) { + return obj.CreateTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SessionInfo_createTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SessionInfo_createTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SessionInfo", Field: field, @@ -34367,216 +37973,117 @@ func (ec *executionContext) fieldContext_SessionInfo_createTime(ctx context.Cont } func (ec *executionContext) _SessionInfo_lastAccessTime(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_lastAccessTime(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LastAccessTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_lastAccessTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_locale(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_locale(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Locale, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext_SessionInfo_locale(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "SessionInfo", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") - }, - } - return fc, nil -} - -func (ec *executionContext) _SessionInfo_cacheExpired(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_cacheExpired(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.CacheExpired, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_lastAccessTime, + func(ctx context.Context) (any, error) { + return obj.LastAccessTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_SessionInfo_cacheExpired(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SessionInfo_lastAccessTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SessionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _SessionInfo_serverMessages(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_serverMessages(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ServerMessages, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null +func (ec *executionContext) _SessionInfo_locale(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_locale, + func(ctx context.Context) (any, error) { + return obj.Locale, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SessionInfo_locale(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SessionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.([]*model.ServerMessage) - fc.Result = res - return ec.marshalOServerMessage2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerMessage(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SessionInfo_cacheExpired(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_cacheExpired, + func(ctx context.Context) (any, error) { + return obj.CacheExpired, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_SessionInfo_serverMessages(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SessionInfo_cacheExpired(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SessionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "time": - return ec.fieldContext_ServerMessage_time(ctx, field) - case "message": - return ec.fieldContext_ServerMessage_message(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type ServerMessage", field.Name) + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } func (ec *executionContext) _SessionInfo_connections(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_connections(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Connections, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]*model.ConnectionInfo) - fc.Result = res - return ec.marshalNConnectionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_connections, + func(ctx context.Context) (any, error) { + return obj.Connections, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_SessionInfo_connections(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SessionInfo_connections(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SessionInfo", Field: field, @@ -34602,10 +38109,16 @@ func (ec *executionContext) fieldContext_SessionInfo_connections(ctx context.Con return ec.fieldContext_ConnectionInfo_databaseName(ctx, field) case "url": return ec.fieldContext_ConnectionInfo_url(ctx, field) + case "mainPropertyValues": + return ec.fieldContext_ConnectionInfo_mainPropertyValues(ctx, field) + case "expertSettingsValues": + return ec.fieldContext_ConnectionInfo_expertSettingsValues(ctx, field) + case "keepAliveInterval": + return ec.fieldContext_ConnectionInfo_keepAliveInterval(ctx, field) + case "autocommit": + return ec.fieldContext_ConnectionInfo_autocommit(ctx, field) case "properties": return ec.fieldContext_ConnectionInfo_properties(ctx, field) - case "template": - return ec.fieldContext_ConnectionInfo_template(ctx, field) case "connected": return ec.fieldContext_ConnectionInfo_connected(ctx, field) case "provided": @@ -34616,6 +38129,14 @@ func (ec *executionContext) fieldContext_SessionInfo_connections(ctx context.Con return ec.fieldContext_ConnectionInfo_useUrl(ctx, field) case "saveCredentials": return ec.fieldContext_ConnectionInfo_saveCredentials(ctx, field) + case "sharedCredentials": + return ec.fieldContext_ConnectionInfo_sharedCredentials(ctx, field) + case "sharedSecrets": + return ec.fieldContext_ConnectionInfo_sharedSecrets(ctx, field) + case "credentialsSaved": + return ec.fieldContext_ConnectionInfo_credentialsSaved(ctx, field) + case "authNeeded": + return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "folder": return ec.fieldContext_ConnectionInfo_folder(ctx, field) case "nodePath": @@ -34630,8 +38151,6 @@ func (ec *executionContext) fieldContext_SessionInfo_connections(ctx context.Con return ec.fieldContext_ConnectionInfo_clientVersion(ctx, field) case "origin": return ec.fieldContext_ConnectionInfo_origin(ctx, field) - case "authNeeded": - return ec.fieldContext_ConnectionInfo_authNeeded(ctx, field) case "authModel": return ec.fieldContext_ConnectionInfo_authModel(ctx, field) case "authProperties": @@ -34646,6 +38165,24 @@ func (ec *executionContext) fieldContext_SessionInfo_connections(ctx context.Con return ec.fieldContext_ConnectionInfo_navigatorSettings(ctx, field) case "supportedDataFormats": return ec.fieldContext_ConnectionInfo_supportedDataFormats(ctx, field) + case "configurationType": + return ec.fieldContext_ConnectionInfo_configurationType(ctx, field) + case "canViewSettings": + return ec.fieldContext_ConnectionInfo_canViewSettings(ctx, field) + case "canEdit": + return ec.fieldContext_ConnectionInfo_canEdit(ctx, field) + case "canDelete": + return ec.fieldContext_ConnectionInfo_canDelete(ctx, field) + case "projectId": + return ec.fieldContext_ConnectionInfo_projectId(ctx, field) + case "requiredAuth": + return ec.fieldContext_ConnectionInfo_requiredAuth(ctx, field) + case "defaultCatalogName": + return ec.fieldContext_ConnectionInfo_defaultCatalogName(ctx, field) + case "defaultSchemaName": + return ec.fieldContext_ConnectionInfo_defaultSchemaName(ctx, field) + case "tools": + return ec.fieldContext_ConnectionInfo_tools(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type ConnectionInfo", field.Name) }, @@ -34654,163 +38191,474 @@ func (ec *executionContext) fieldContext_SessionInfo_connections(ctx context.Con } func (ec *executionContext) _SessionInfo_actionParameters(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_SessionInfo_actionParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ActionParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_actionParameters, + func(ctx context.Context) (any, error) { + return obj.ActionParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOObject2interface, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_SessionInfo_actionParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SessionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _SessionInfo_valid(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_valid, + func(ctx context.Context) (any, error) { + return obj.Valid, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_SessionInfo_valid(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "SessionInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalOObject2interface(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _SessionInfo_remainingTime(ctx context.Context, field graphql.CollectedField, obj *model.SessionInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_SessionInfo_remainingTime, + func(ctx context.Context) (any, error) { + return obj.RemainingTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_SessionInfo_actionParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_SessionInfo_remainingTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "SessionInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _UserAuthToken_authProvider(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_authProvider(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _TransactionLogInfoItem_id(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfoItem) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfoItem_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_TransactionLogInfoItem_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TransactionLogInfoItem", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthProvider, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _TransactionLogInfoItem_time(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfoItem) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfoItem_time, + func(ctx context.Context) (any, error) { + return obj.Time, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDateTime2timeᚐTime, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_TransactionLogInfoItem_time(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TransactionLogInfoItem", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type DateTime does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _TransactionLogInfoItem_type(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfoItem) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfoItem_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_TransactionLogInfoItem_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TransactionLogInfoItem", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _TransactionLogInfoItem_queryString(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfoItem) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfoItem_queryString, + func(ctx context.Context) (any, error) { + return obj.QueryString, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserAuthToken_authProvider(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_TransactionLogInfoItem_queryString(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "UserAuthToken", + Object: "TransactionLogInfoItem", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _UserAuthToken_authConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_authConfiguration(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _TransactionLogInfoItem_durationMs(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfoItem) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfoItem_durationMs, + func(ctx context.Context) (any, error) { + return obj.DurationMs, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_TransactionLogInfoItem_durationMs(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TransactionLogInfoItem", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthConfiguration, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _TransactionLogInfoItem_rows(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfoItem) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfoItem_rows, + func(ctx context.Context) (any, error) { + return obj.Rows, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_TransactionLogInfoItem_rows(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TransactionLogInfoItem", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _TransactionLogInfoItem_result(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfoItem) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfoItem_result, + func(ctx context.Context) (any, error) { + return obj.Result, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_TransactionLogInfoItem_result(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TransactionLogInfoItem", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOID2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _TransactionLogInfos_count(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfos) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfos_count, + func(ctx context.Context) (any, error) { + return obj.Count, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNInt2int, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserAuthToken_authConfiguration(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_TransactionLogInfos_count(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "UserAuthToken", + Object: "TransactionLogInfos", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type ID does not have child fields") + return nil, errors.New("field of type Int does not have child fields") }, } return fc, nil } -func (ec *executionContext) _UserAuthToken_loginTime(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_loginTime(ctx, field) - if err != nil { - return graphql.Null +func (ec *executionContext) _TransactionLogInfos_transactionLogInfos(ctx context.Context, field graphql.CollectedField, obj *model.TransactionLogInfos) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_TransactionLogInfos_transactionLogInfos, + func(ctx context.Context) (any, error) { + return obj.TransactionLogInfos, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNTransactionLogInfoItem2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐTransactionLogInfoItemᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_TransactionLogInfos_transactionLogInfos(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TransactionLogInfos", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_TransactionLogInfoItem_id(ctx, field) + case "time": + return ec.fieldContext_TransactionLogInfoItem_time(ctx, field) + case "type": + return ec.fieldContext_TransactionLogInfoItem_type(ctx, field) + case "queryString": + return ec.fieldContext_TransactionLogInfoItem_queryString(ctx, field) + case "durationMs": + return ec.fieldContext_TransactionLogInfoItem_durationMs(ctx, field) + case "rows": + return ec.fieldContext_TransactionLogInfoItem_rows(ctx, field) + case "result": + return ec.fieldContext_TransactionLogInfoItem_result(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TransactionLogInfoItem", field.Name) + }, } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LoginTime, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _UserAuthToken_authProvider(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserAuthToken_authProvider, + func(ctx context.Context) (any, error) { + return obj.AuthProvider, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_UserAuthToken_authProvider(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserAuthToken", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _UserAuthToken_authConfiguration(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserAuthToken_authConfiguration, + func(ctx context.Context) (any, error) { + return obj.AuthConfiguration, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_UserAuthToken_authConfiguration(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserAuthToken", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.(time.Time) - fc.Result = res - return ec.marshalNDateTime2timeᚐTime(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _UserAuthToken_loginTime(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserAuthToken_loginTime, + func(ctx context.Context) (any, error) { + return obj.LoginTime, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNDateTime2timeᚐTime, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserAuthToken_loginTime(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserAuthToken_loginTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserAuthToken", Field: field, @@ -34824,37 +38672,24 @@ func (ec *executionContext) fieldContext_UserAuthToken_loginTime(ctx context.Con } func (ec *executionContext) _UserAuthToken_userId(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_userId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserAuthToken_userId, + func(ctx context.Context) (any, error) { + return obj.UserID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserAuthToken_userId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserAuthToken_userId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserAuthToken", Field: field, @@ -34868,37 +38703,24 @@ func (ec *executionContext) fieldContext_UserAuthToken_userId(ctx context.Contex } func (ec *executionContext) _UserAuthToken_displayName(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserAuthToken_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserAuthToken_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserAuthToken_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserAuthToken", Field: field, @@ -34912,34 +38734,24 @@ func (ec *executionContext) fieldContext_UserAuthToken_displayName(ctx context.C } func (ec *executionContext) _UserAuthToken_message(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_message(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Message, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserAuthToken_message, + func(ctx context.Context) (any, error) { + return obj.Message, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_UserAuthToken_message(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserAuthToken_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserAuthToken", Field: field, @@ -34953,37 +38765,24 @@ func (ec *executionContext) fieldContext_UserAuthToken_message(ctx context.Conte } func (ec *executionContext) _UserAuthToken_origin(ctx context.Context, field graphql.CollectedField, obj *model.UserAuthToken) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserAuthToken_origin(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Origin, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*model.ObjectOrigin) - fc.Result = res - return ec.marshalNObjectOrigin2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserAuthToken_origin, + func(ctx context.Context) (any, error) { + return obj.Origin, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserAuthToken_origin(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserAuthToken_origin(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserAuthToken", Field: field, @@ -35011,37 +38810,24 @@ func (ec *executionContext) fieldContext_UserAuthToken_origin(ctx context.Contex } func (ec *executionContext) _UserInfo_userId(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_userId(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.UserID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNID2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_userId, + func(ctx context.Context) (any, error) { + return obj.UserID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNID2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserInfo_userId(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserInfo_userId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserInfo", Field: field, @@ -35055,34 +38841,24 @@ func (ec *executionContext) fieldContext_UserInfo_userId(ctx context.Context, fi } func (ec *executionContext) _UserInfo_displayName(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_displayName(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DisplayName, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_displayName, + func(ctx context.Context) (any, error) { + return obj.DisplayName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_UserInfo_displayName(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserInfo_displayName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserInfo", Field: field, @@ -35095,38 +38871,56 @@ func (ec *executionContext) fieldContext_UserInfo_displayName(ctx context.Contex return fc, nil } -func (ec *executionContext) _UserInfo_authTokens(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_authTokens(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.AuthTokens, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null +func (ec *executionContext) _UserInfo_authRole(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_authRole, + func(ctx context.Context) (any, error) { + return obj.AuthRole, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOID2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext_UserInfo_authRole(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, } - res := resTmp.([]*model.UserAuthToken) - fc.Result = res - return ec.marshalNUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _UserInfo_authTokens(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_authTokens, + func(ctx context.Context) (any, error) { + return obj.AuthTokens, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserInfo_authTokens(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserInfo_authTokens(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserInfo", Field: field, @@ -35156,37 +38950,24 @@ func (ec *executionContext) fieldContext_UserInfo_authTokens(ctx context.Context } func (ec *executionContext) _UserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_linkedAuthProviders(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.LinkedAuthProviders, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalNString2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_linkedAuthProviders, + func(ctx context.Context) (any, error) { + return obj.LinkedAuthProviders, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserInfo_linkedAuthProviders(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserInfo_linkedAuthProviders(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserInfo", Field: field, @@ -35200,37 +38981,24 @@ func (ec *executionContext) fieldContext_UserInfo_linkedAuthProviders(ctx contex } func (ec *executionContext) _UserInfo_metaParameters(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_metaParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MetaParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_metaParameters, + func(ctx context.Context) (any, error) { + return obj.MetaParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserInfo_metaParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserInfo_metaParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserInfo", Field: field, @@ -35244,83 +39012,143 @@ func (ec *executionContext) fieldContext_UserInfo_metaParameters(ctx context.Con } func (ec *executionContext) _UserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_UserInfo_configurationParameters(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ConfigurationParameters, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_configurationParameters, + func(ctx context.Context) (any, error) { + return obj.ConfigurationParameters, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNObject2interface, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_UserInfo_configurationParameters(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Object does not have child fields") + }, } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null + return fc, nil +} + +func (ec *executionContext) _UserInfo_teams(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_teams, + func(ctx context.Context) (any, error) { + return obj.Teams, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNUserTeamInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserTeamInfoᚄ, + true, + true, + ) +} + +func (ec *executionContext) fieldContext_UserInfo_teams(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "teamId": + return ec.fieldContext_UserTeamInfo_teamId(ctx, field) + case "teamName": + return ec.fieldContext_UserTeamInfo_teamName(ctx, field) + case "teamRole": + return ec.fieldContext_UserTeamInfo_teamRole(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type UserTeamInfo", field.Name) + }, } - res := resTmp.(interface{}) - fc.Result = res - return ec.marshalNObject2interface(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) _UserInfo_isAnonymous(ctx context.Context, field graphql.CollectedField, obj *model.UserInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserInfo_isAnonymous, + func(ctx context.Context) (any, error) { + return obj.IsAnonymous, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + directive0 := next + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.2.3") + if err != nil { + var zeroVal bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + next = directive1 + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_UserInfo_configurationParameters(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserInfo_isAnonymous(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "UserInfo", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Object does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _WebFeatureSet_id(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _UserTeamInfo_teamId(ctx context.Context, field graphql.CollectedField, obj *model.UserTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserTeamInfo_teamId, + func(ctx context.Context) (any, error) { + return obj.TeamID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_WebFeatureSet_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserTeamInfo_teamId(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "WebFeatureSet", + Object: "UserTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -35331,40 +39159,27 @@ func (ec *executionContext) fieldContext_WebFeatureSet_id(ctx context.Context, f return fc, nil } -func (ec *executionContext) _WebFeatureSet_label(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_label(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Label, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _UserTeamInfo_teamName(ctx context.Context, field graphql.CollectedField, obj *model.UserTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserTeamInfo_teamName, + func(ctx context.Context) (any, error) { + return obj.TeamName, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_WebFeatureSet_label(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserTeamInfo_teamName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "WebFeatureSet", + Object: "UserTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -35375,37 +39190,27 @@ func (ec *executionContext) fieldContext_WebFeatureSet_label(ctx context.Context return fc, nil } -func (ec *executionContext) _WebFeatureSet_description(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _UserTeamInfo_teamRole(ctx context.Context, field graphql.CollectedField, obj *model.UserTeamInfo) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_UserTeamInfo_teamRole, + func(ctx context.Context) (any, error) { + return obj.TeamRole, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_WebFeatureSet_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_UserTeamInfo_teamRole(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "WebFeatureSet", + Object: "UserTeamInfo", Field: field, IsMethod: false, IsResolver: false, @@ -35416,35 +39221,25 @@ func (ec *executionContext) fieldContext_WebFeatureSet_description(ctx context.C return fc, nil } -func (ec *executionContext) _WebFeatureSet_icon(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_icon(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Icon, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) _WebFeatureSet_id(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_WebFeatureSet_id, + func(ctx context.Context) (any, error) { + return obj.ID, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_WebFeatureSet_icon(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_WebFeatureSet_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "WebFeatureSet", Field: field, @@ -35457,84 +39252,58 @@ func (ec *executionContext) fieldContext_WebFeatureSet_icon(ctx context.Context, return fc, nil } -func (ec *executionContext) _WebFeatureSet_enabled(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebFeatureSet_enabled(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Enabled, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) +func (ec *executionContext) _WebFeatureSet_label(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_WebFeatureSet_label, + func(ctx context.Context) (any, error) { + return obj.Label, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_WebFeatureSet_enabled(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_WebFeatureSet_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "WebFeatureSet", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") + return nil, errors.New("field of type String does not have child fields") }, } return fc, nil } -func (ec *executionContext) _WebServiceConfig_id(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_id(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.ID, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _WebFeatureSet_description(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_WebFeatureSet_description, + func(ctx context.Context) (any, error) { + return obj.Description, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_WebServiceConfig_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_WebFeatureSet_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "WebServiceConfig", + Object: "WebFeatureSet", Field: field, IsMethod: false, IsResolver: false, @@ -35545,40 +39314,27 @@ func (ec *executionContext) fieldContext_WebServiceConfig_id(ctx context.Context return fc, nil } -func (ec *executionContext) _WebServiceConfig_name(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _WebFeatureSet_icon(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_WebFeatureSet_icon, + func(ctx context.Context) (any, error) { + return obj.Icon, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext_WebServiceConfig_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_WebFeatureSet_icon(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "WebServiceConfig", + Object: "WebFeatureSet", Field: field, IsMethod: false, IsResolver: false, @@ -35589,84 +39345,58 @@ func (ec *executionContext) fieldContext_WebServiceConfig_name(ctx context.Conte return fc, nil } -func (ec *executionContext) _WebServiceConfig_description(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) _WebFeatureSet_enabled(ctx context.Context, field graphql.CollectedField, obj *model.WebFeatureSet) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext_WebFeatureSet_enabled, + func(ctx context.Context) (any, error) { + return obj.Enabled, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext_WebServiceConfig_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_WebFeatureSet_enabled(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "WebServiceConfig", + Object: "WebFeatureSet", Field: field, IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } -func (ec *executionContext) _WebServiceConfig_bundleVersion(ctx context.Context, field graphql.CollectedField, obj *model.WebServiceConfig) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_WebServiceConfig_bundleVersion(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.BundleVersion, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Directive_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext_WebServiceConfig_bundleVersion(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Directive_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ - Object: "WebServiceConfig", + Object: "__Directive", Field: field, IsMethod: false, IsResolver: false, @@ -35677,42 +39407,29 @@ func (ec *executionContext) fieldContext_WebServiceConfig_bundleVersion(ctx cont return fc, nil } -func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) +func (ec *executionContext) ___Directive_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Directive_description, + func(ctx context.Context) (any, error) { + return obj.Description(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___Directive_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Directive_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Directive", Field: field, - IsMethod: false, + IsMethod: true, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { return nil, errors.New("field of type String does not have child fields") @@ -35721,79 +39438,56 @@ func (ec *executionContext) fieldContext___Directive_name(ctx context.Context, f return fc, nil } -func (ec *executionContext) ___Directive_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) ___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Directive_isRepeatable, + func(ctx context.Context) (any, error) { + return obj.IsRepeatable, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext___Directive_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Directive_isRepeatable(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Directive", Field: field, - IsMethod: true, + IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil } func (ec *executionContext) ___Directive_locations(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_locations(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Locations, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]string) - fc.Result = res - return ec.marshalN__DirectiveLocation2ᚕstringᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Directive_locations, + func(ctx context.Context) (any, error) { + return obj.Locations, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__DirectiveLocation2ᚕstringᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext___Directive_locations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Directive_locations(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Directive", Field: field, @@ -35807,34 +39501,21 @@ func (ec *executionContext) fieldContext___Directive_locations(ctx context.Conte } func (ec *executionContext) ___Directive_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_args(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Args, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Directive_args, + func(ctx context.Context) (any, error) { + return obj.Args, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext___Directive_args(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -35853,89 +39534,47 @@ func (ec *executionContext) fieldContext___Directive_args(ctx context.Context, f return ec.fieldContext___InputValue_type(ctx, field) case "defaultValue": return ec.fieldContext___InputValue_defaultValue(ctx, field) + case "isDeprecated": + return ec.fieldContext___InputValue_isDeprecated(ctx, field) + case "deprecationReason": + return ec.fieldContext___InputValue_deprecationReason(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) }, } - return fc, nil -} - -func (ec *executionContext) ___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Directive_isRepeatable(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsRepeatable, nil - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field___Directive_args_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "__Directive", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Boolean does not have child fields") - }, + return fc, err } return fc, nil } func (ec *executionContext) ___EnumValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___EnumValue_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext___EnumValue_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___EnumValue_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__EnumValue", Field: field, @@ -35949,34 +39588,24 @@ func (ec *executionContext) fieldContext___EnumValue_name(ctx context.Context, f } func (ec *executionContext) ___EnumValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___EnumValue_description, + func(ctx context.Context) (any, error) { + return obj.Description(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___EnumValue_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___EnumValue_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__EnumValue", Field: field, @@ -35990,37 +39619,24 @@ func (ec *executionContext) fieldContext___EnumValue_description(ctx context.Con } func (ec *executionContext) ___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_isDeprecated(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsDeprecated(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___EnumValue_isDeprecated, + func(ctx context.Context) (any, error) { + return obj.IsDeprecated(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___EnumValue_isDeprecated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__EnumValue", Field: field, @@ -36034,34 +39650,24 @@ func (ec *executionContext) fieldContext___EnumValue_isDeprecated(ctx context.Co } func (ec *executionContext) ___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___EnumValue_deprecationReason(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeprecationReason(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___EnumValue_deprecationReason, + func(ctx context.Context) (any, error) { + return obj.DeprecationReason(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___EnumValue_deprecationReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__EnumValue", Field: field, @@ -36075,37 +39681,24 @@ func (ec *executionContext) fieldContext___EnumValue_deprecationReason(ctx conte } func (ec *executionContext) ___Field_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Field_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext___Field_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Field_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Field", Field: field, @@ -36119,34 +39712,24 @@ func (ec *executionContext) fieldContext___Field_name(ctx context.Context, field } func (ec *executionContext) ___Field_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Field_description, + func(ctx context.Context) (any, error) { + return obj.Description(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___Field_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Field_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Field", Field: field, @@ -36160,34 +39743,21 @@ func (ec *executionContext) fieldContext___Field_description(ctx context.Context } func (ec *executionContext) ___Field_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_args(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Args, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Field_args, + func(ctx context.Context) (any, error) { + return obj.Args, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ, + true, + true, + ) } func (ec *executionContext) fieldContext___Field_args(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -36206,45 +39776,47 @@ func (ec *executionContext) fieldContext___Field_args(ctx context.Context, field return ec.fieldContext___InputValue_type(ctx, field) case "defaultValue": return ec.fieldContext___InputValue_defaultValue(ctx, field) + case "isDeprecated": + return ec.fieldContext___InputValue_isDeprecated(ctx, field) + case "deprecationReason": + return ec.fieldContext___InputValue_deprecationReason(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) }, } - return fc, nil -} - -func (ec *executionContext) ___Field_type(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) defer func() { if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null + err = ec.Recover(ctx, r) + ec.Error(ctx, err) } }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field___Field_args_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return graphql.Null + return fc, err } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) ___Field_type(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Field_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType, + true, + true, + ) } -func (ec *executionContext) fieldContext___Field_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Field_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Field", Field: field, @@ -36258,6 +39830,8 @@ func (ec *executionContext) fieldContext___Field_type(ctx context.Context, field return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -36270,8 +39844,8 @@ func (ec *executionContext) fieldContext___Field_type(ctx context.Context, field return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -36280,37 +39854,24 @@ func (ec *executionContext) fieldContext___Field_type(ctx context.Context, field } func (ec *executionContext) ___Field_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_isDeprecated(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.IsDeprecated(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(bool) - fc.Result = res - return ec.marshalNBoolean2bool(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Field_isDeprecated, + func(ctx context.Context) (any, error) { + return obj.IsDeprecated(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) } -func (ec *executionContext) fieldContext___Field_isDeprecated(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Field_isDeprecated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Field", Field: field, @@ -36324,34 +39885,24 @@ func (ec *executionContext) fieldContext___Field_isDeprecated(ctx context.Contex } func (ec *executionContext) ___Field_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Field_deprecationReason(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DeprecationReason(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Field_deprecationReason, + func(ctx context.Context) (any, error) { + return obj.DeprecationReason(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___Field_deprecationReason(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Field_deprecationReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Field", Field: field, @@ -36365,37 +39916,24 @@ func (ec *executionContext) fieldContext___Field_deprecationReason(ctx context.C } func (ec *executionContext) ___InputValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalNString2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___InputValue_name, + func(ctx context.Context) (any, error) { + return obj.Name, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNString2string, + true, + true, + ) } -func (ec *executionContext) fieldContext___InputValue_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___InputValue_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__InputValue", Field: field, @@ -36408,35 +39946,25 @@ func (ec *executionContext) fieldContext___InputValue_name(ctx context.Context, return fc, nil } -func (ec *executionContext) ___InputValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) -} - -func (ec *executionContext) fieldContext___InputValue_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) ___InputValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___InputValue_description, + func(ctx context.Context) (any, error) { + return obj.Description(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext___InputValue_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__InputValue", Field: field, @@ -36450,37 +39978,24 @@ func (ec *executionContext) fieldContext___InputValue_description(ctx context.Co } func (ec *executionContext) ___InputValue_type(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_type(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Type, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___InputValue_type, + func(ctx context.Context) (any, error) { + return obj.Type, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType, + true, + true, + ) } -func (ec *executionContext) fieldContext___InputValue_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___InputValue_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__InputValue", Field: field, @@ -36494,6 +40009,8 @@ func (ec *executionContext) fieldContext___InputValue_type(ctx context.Context, return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -36506,8 +40023,8 @@ func (ec *executionContext) fieldContext___InputValue_type(ctx context.Context, return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -36516,34 +40033,24 @@ func (ec *executionContext) fieldContext___InputValue_type(ctx context.Context, } func (ec *executionContext) ___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___InputValue_defaultValue(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.DefaultValue, nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___InputValue_defaultValue, + func(ctx context.Context) (any, error) { + return obj.DefaultValue, nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___InputValue_defaultValue(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__InputValue", Field: field, @@ -36556,35 +40063,87 @@ func (ec *executionContext) fieldContext___InputValue_defaultValue(ctx context.C return fc, nil } -func (ec *executionContext) ___Schema_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null +func (ec *executionContext) ___InputValue_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___InputValue_isDeprecated, + func(ctx context.Context) (any, error) { + return obj.IsDeprecated(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalNBoolean2bool, + true, + true, + ) +} + +func (ec *executionContext) fieldContext___InputValue_isDeprecated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, } - if resTmp == nil { - return graphql.Null + return fc, nil +} + +func (ec *executionContext) ___InputValue_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___InputValue_deprecationReason, + func(ctx context.Context) (any, error) { + return obj.DeprecationReason(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext___InputValue_deprecationReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) ___Schema_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Schema_description, + func(ctx context.Context) (any, error) { + return obj.Description(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___Schema_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Schema_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Schema", Field: field, @@ -36598,37 +40157,24 @@ func (ec *executionContext) fieldContext___Schema_description(ctx context.Contex } func (ec *executionContext) ___Schema_types(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_types(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Types(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Schema_types, + func(ctx context.Context) (any, error) { + return obj.Types(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext___Schema_types(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Schema_types(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Schema", Field: field, @@ -36642,6 +40188,8 @@ func (ec *executionContext) fieldContext___Schema_types(ctx context.Context, fie return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -36654,8 +40202,8 @@ func (ec *executionContext) fieldContext___Schema_types(ctx context.Context, fie return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -36664,37 +40212,24 @@ func (ec *executionContext) fieldContext___Schema_types(ctx context.Context, fie } func (ec *executionContext) ___Schema_queryType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_queryType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.QueryType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Schema_queryType, + func(ctx context.Context) (any, error) { + return obj.QueryType(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType, + true, + true, + ) } -func (ec *executionContext) fieldContext___Schema_queryType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Schema_queryType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Schema", Field: field, @@ -36708,6 +40243,8 @@ func (ec *executionContext) fieldContext___Schema_queryType(ctx context.Context, return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -36720,8 +40257,8 @@ func (ec *executionContext) fieldContext___Schema_queryType(ctx context.Context, return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -36730,34 +40267,24 @@ func (ec *executionContext) fieldContext___Schema_queryType(ctx context.Context, } func (ec *executionContext) ___Schema_mutationType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_mutationType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.MutationType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Schema_mutationType, + func(ctx context.Context) (any, error) { + return obj.MutationType(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType, + true, + false, + ) } -func (ec *executionContext) fieldContext___Schema_mutationType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Schema_mutationType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Schema", Field: field, @@ -36771,6 +40298,8 @@ func (ec *executionContext) fieldContext___Schema_mutationType(ctx context.Conte return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -36783,8 +40312,8 @@ func (ec *executionContext) fieldContext___Schema_mutationType(ctx context.Conte return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -36793,34 +40322,24 @@ func (ec *executionContext) fieldContext___Schema_mutationType(ctx context.Conte } func (ec *executionContext) ___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_subscriptionType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SubscriptionType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Schema_subscriptionType, + func(ctx context.Context) (any, error) { + return obj.SubscriptionType(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType, + true, + false, + ) } -func (ec *executionContext) fieldContext___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Schema_subscriptionType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Schema", Field: field, @@ -36834,6 +40353,8 @@ func (ec *executionContext) fieldContext___Schema_subscriptionType(ctx context.C return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -36846,8 +40367,8 @@ func (ec *executionContext) fieldContext___Schema_subscriptionType(ctx context.C return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -36856,37 +40377,24 @@ func (ec *executionContext) fieldContext___Schema_subscriptionType(ctx context.C } func (ec *executionContext) ___Schema_directives(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Schema_directives(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Directives(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.([]introspection.Directive) - fc.Result = res - return ec.marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Schema_directives, + func(ctx context.Context) (any, error) { + return obj.Directives(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ, + true, + true, + ) } -func (ec *executionContext) fieldContext___Schema_directives(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Schema_directives(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Schema", Field: field, @@ -36898,12 +40406,12 @@ func (ec *executionContext) fieldContext___Schema_directives(ctx context.Context return ec.fieldContext___Directive_name(ctx, field) case "description": return ec.fieldContext___Directive_description(ctx, field) + case "isRepeatable": + return ec.fieldContext___Directive_isRepeatable(ctx, field) case "locations": return ec.fieldContext___Directive_locations(ctx, field) case "args": return ec.fieldContext___Directive_args(ctx, field) - case "isRepeatable": - return ec.fieldContext___Directive_isRepeatable(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Directive", field.Name) }, @@ -36912,37 +40420,24 @@ func (ec *executionContext) fieldContext___Schema_directives(ctx context.Context } func (ec *executionContext) ___Type_kind(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_kind(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Kind(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") - } - return graphql.Null - } - res := resTmp.(string) - fc.Result = res - return ec.marshalN__TypeKind2string(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_kind, + func(ctx context.Context) (any, error) { + return obj.Kind(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalN__TypeKind2string, + true, + true, + ) } -func (ec *executionContext) fieldContext___Type_kind(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_kind(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, @@ -36956,34 +40451,24 @@ func (ec *executionContext) fieldContext___Type_kind(ctx context.Context, field } func (ec *executionContext) ___Type_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_name(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Name(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_name, + func(ctx context.Context) (any, error) { + return obj.Name(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___Type_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, @@ -36997,34 +40482,55 @@ func (ec *executionContext) fieldContext___Type_name(ctx context.Context, field } func (ec *executionContext) ___Type_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_description(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Description(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_description, + func(ctx context.Context) (any, error) { + return obj.Description(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) +} + +func (ec *executionContext) fieldContext___Type_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) + return fc, nil +} + +func (ec *executionContext) ___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_specifiedByURL, + func(ctx context.Context) (any, error) { + return obj.SpecifiedByURL(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOString2ᚖstring, + true, + false, + ) } -func (ec *executionContext) fieldContext___Type_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_specifiedByURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, @@ -37038,31 +40544,22 @@ func (ec *executionContext) fieldContext___Type_description(ctx context.Context, } func (ec *executionContext) ___Type_fields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_fields(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Fields(fc.Args["includeDeprecated"].(bool)), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Field) - fc.Result = res - return ec.marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_fields, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return obj.Fields(fc.Args["includeDeprecated"].(bool)), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ, + true, + false, + ) } func (ec *executionContext) fieldContext___Type_fields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -37098,40 +40595,30 @@ func (ec *executionContext) fieldContext___Type_fields(ctx context.Context, fiel ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field___Type_fields_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) ___Type_interfaces(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_interfaces(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.Interfaces(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_interfaces, + func(ctx context.Context) (any, error) { + return obj.Interfaces(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext___Type_interfaces(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_interfaces(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, @@ -37145,6 +40632,8 @@ func (ec *executionContext) fieldContext___Type_interfaces(ctx context.Context, return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -37157,8 +40646,8 @@ func (ec *executionContext) fieldContext___Type_interfaces(ctx context.Context, return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -37167,34 +40656,24 @@ func (ec *executionContext) fieldContext___Type_interfaces(ctx context.Context, } func (ec *executionContext) ___Type_possibleTypes(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_possibleTypes(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.PossibleTypes(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_possibleTypes, + func(ctx context.Context) (any, error) { + return obj.PossibleTypes(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext___Type_possibleTypes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_possibleTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, @@ -37208,6 +40687,8 @@ func (ec *executionContext) fieldContext___Type_possibleTypes(ctx context.Contex return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -37220,8 +40701,8 @@ func (ec *executionContext) fieldContext___Type_possibleTypes(ctx context.Contex return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -37230,31 +40711,22 @@ func (ec *executionContext) fieldContext___Type_possibleTypes(ctx context.Contex } func (ec *executionContext) ___Type_enumValues(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_enumValues(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.EnumValues(fc.Args["includeDeprecated"].(bool)), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.EnumValue) - fc.Result = res - return ec.marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_enumValues, + func(ctx context.Context) (any, error) { + fc := graphql.GetFieldContext(ctx) + return obj.EnumValues(fc.Args["includeDeprecated"].(bool)), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ, + true, + false, + ) } func (ec *executionContext) fieldContext___Type_enumValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -37286,40 +40758,30 @@ func (ec *executionContext) fieldContext___Type_enumValues(ctx context.Context, ctx = graphql.WithFieldContext(ctx, fc) if fc.Args, err = ec.field___Type_enumValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { ec.Error(ctx, err) - return + return fc, err } return fc, nil } func (ec *executionContext) ___Type_inputFields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_inputFields(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.InputFields(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.([]introspection.InputValue) - fc.Result = res - return ec.marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_inputFields, + func(ctx context.Context) (any, error) { + return obj.InputFields(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ, + true, + false, + ) } -func (ec *executionContext) fieldContext___Type_inputFields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_inputFields(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, @@ -37335,6 +40797,10 @@ func (ec *executionContext) fieldContext___Type_inputFields(ctx context.Context, return ec.fieldContext___InputValue_type(ctx, field) case "defaultValue": return ec.fieldContext___InputValue_defaultValue(ctx, field) + case "isDeprecated": + return ec.fieldContext___InputValue_isDeprecated(ctx, field) + case "deprecationReason": + return ec.fieldContext___InputValue_deprecationReason(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) }, @@ -37343,34 +40809,24 @@ func (ec *executionContext) fieldContext___Type_inputFields(ctx context.Context, } func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_ofType(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.OfType(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*introspection.Type) - fc.Result = res - return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_ofType, + func(ctx context.Context) (any, error) { + return obj.OfType(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType, + true, + false, + ) } -func (ec *executionContext) fieldContext___Type_ofType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_ofType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, @@ -37384,6 +40840,8 @@ func (ec *executionContext) fieldContext___Type_ofType(ctx context.Context, fiel return ec.fieldContext___Type_name(ctx, field) case "description": return ec.fieldContext___Type_description(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) case "fields": return ec.fieldContext___Type_fields(ctx, field) case "interfaces": @@ -37396,8 +40854,8 @@ func (ec *executionContext) fieldContext___Type_ofType(ctx context.Context, fiel return ec.fieldContext___Type_inputFields(ctx, field) case "ofType": return ec.fieldContext___Type_ofType(ctx, field) - case "specifiedByURL": - return ec.fieldContext___Type_specifiedByURL(ctx, field) + case "isOneOf": + return ec.fieldContext___Type_isOneOf(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) }, @@ -37405,42 +40863,32 @@ func (ec *executionContext) fieldContext___Type_ofType(ctx context.Context, fiel return fc, nil } -func (ec *executionContext) ___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { - fc, err := ec.fieldContext___Type_specifiedByURL(ctx, field) - if err != nil { - return graphql.Null - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = graphql.Null - } - }() - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - return obj.SpecifiedByURL(), nil - }) - if err != nil { - ec.Error(ctx, err) - return graphql.Null - } - if resTmp == nil { - return graphql.Null - } - res := resTmp.(*string) - fc.Result = res - return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +func (ec *executionContext) ___Type_isOneOf(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + return graphql.ResolveField( + ctx, + ec.OperationContext, + field, + ec.fieldContext___Type_isOneOf, + func(ctx context.Context) (any, error) { + return obj.IsOneOf(), nil + }, + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + return ec._fieldMiddleware(ctx, obj, next) + }, + ec.marshalOBoolean2bool, + true, + false, + ) } -func (ec *executionContext) fieldContext___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext___Type_isOneOf(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "__Type", Field: field, IsMethod: true, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type String does not have child fields") + return nil, errors.New("field of type Boolean does not have child fields") }, } return fc, nil @@ -37450,14 +40898,48 @@ func (ec *executionContext) fieldContext___Type_specifiedByURL(ctx context.Conte // region **************************** input.gotpl ***************************** -func (ec *executionContext) unmarshalInputConnectionConfig(ctx context.Context, obj interface{}) (model.ConnectionConfig, error) { +func (ec *executionContext) unmarshalInputAdminUserFilterInput(ctx context.Context, obj any) (model.AdminUserFilterInput, error) { + var it model.AdminUserFilterInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"userIdMask", "enabledState"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "userIdMask": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIdMask")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDMask = data + case "enabledState": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabledState")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.EnabledState = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputConnectionConfig(ctx context.Context, obj any) (model.ConnectionConfig, error) { var it model.ConnectionConfig - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } - fieldsInOrder := [...]string{"connectionId", "name", "description", "templateId", "driverId", "host", "port", "serverName", "databaseName", "url", "properties", "template", "readOnly", "saveCredentials", "authModelId", "credentials", "providerProperties", "networkHandlersConfig", "dataSourceId", "userName", "userPassword", "folder"} + fieldsInOrder := [...]string{"connectionId", "name", "description", "driverId", "host", "port", "serverName", "databaseName", "mainPropertyValues", "expertSettingsValues", "url", "properties", "keepAliveInterval", "autocommit", "readOnly", "saveCredentials", "sharedCredentials", "authModelId", "selectedSecretId", "credentials", "providerProperties", "networkHandlersConfig", "dataSourceId", "userName", "userPassword", "folder", "configurationType", "defaultCatalogName", "defaultSchemaName"} for _, k := range fieldsInOrder { v, ok := asMap[k] if !ok { @@ -37465,195 +40947,387 @@ func (ec *executionContext) unmarshalInputConnectionConfig(ctx context.Context, } switch k { case "connectionId": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("connectionId")) - it.ConnectionID, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.ConnectionID = data case "name": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) - it.Name, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Name = data case "description": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) - it.Description, err = ec.unmarshalOString2ᚖstring(ctx, v) - if err != nil { - return it, err - } - case "templateId": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("templateId")) - it.TemplateID, err = ec.unmarshalOID2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Description = data case "driverId": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("driverId")) - it.DriverID, err = ec.unmarshalOID2ᚖstring(ctx, v) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) if err != nil { return it, err } + it.DriverID = data case "host": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("host")) - it.Host, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Host = data case "port": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("port")) - it.Port, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Port = data case "serverName": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("serverName")) - it.ServerName, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.ServerName = data case "databaseName": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("databaseName")) - it.DatabaseName, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } - case "url": - var err error + it.DatabaseName = data + case "mainPropertyValues": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("mainPropertyValues")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOObject2interface(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.1.2") + if err != nil { + var zeroVal any + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal any + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(any); ok { + it.MainPropertyValues = data + } else if tmp == nil { + it.MainPropertyValues = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be any`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "expertSettingsValues": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("expertSettingsValues")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOObject2interface(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.2.1") + if err != nil { + var zeroVal any + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal any + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(any); ok { + it.ExpertSettingsValues = data + } else if tmp == nil { + it.ExpertSettingsValues = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be any`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "url": ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("url")) - it.URL, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.URL = data case "properties": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("properties")) - it.Properties, err = ec.unmarshalOObject2interface(ctx, v) + data, err := ec.unmarshalOObject2interface(ctx, v) if err != nil { return it, err } - case "template": - var err error - - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("template")) - it.Template, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + it.Properties = data + case "keepAliveInterval": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("keepAliveInterval")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.KeepAliveInterval = data + case "autocommit": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("autocommit")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.Autocommit = data case "readOnly": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("readOnly")) - it.ReadOnly, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.ReadOnly = data case "saveCredentials": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("saveCredentials")) - it.SaveCredentials, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.SaveCredentials = data + case "sharedCredentials": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("sharedCredentials")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.SharedCredentials = data case "authModelId": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authModelId")) - it.AuthModelID, err = ec.unmarshalOID2ᚖstring(ctx, v) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) if err != nil { return it, err } - case "credentials": - var err error + it.AuthModelID = data + case "selectedSecretId": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("selectedSecretId")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOID2ᚖstring(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "23.3.5") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*string); ok { + it.SelectedSecretID = data + } else if tmp == nil { + it.SelectedSecretID = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *string`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "credentials": ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("credentials")) - it.Credentials, err = ec.unmarshalOObject2interface(ctx, v) + data, err := ec.unmarshalOObject2interface(ctx, v) if err != nil { return it, err } + it.Credentials = data case "providerProperties": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("providerProperties")) - it.ProviderProperties, err = ec.unmarshalOObject2interface(ctx, v) + data, err := ec.unmarshalOObject2interface(ctx, v) if err != nil { return it, err } + it.ProviderProperties = data case "networkHandlersConfig": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("networkHandlersConfig")) - it.NetworkHandlersConfig, err = ec.unmarshalONetworkHandlerConfigInput2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx, v) + data, err := ec.unmarshalONetworkHandlerConfigInput2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx, v) if err != nil { return it, err } + it.NetworkHandlersConfig = data case "dataSourceId": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataSourceId")) - it.DataSourceID, err = ec.unmarshalOID2ᚖstring(ctx, v) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) if err != nil { return it, err } + it.DataSourceID = data case "userName": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userName")) - it.UserName, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.UserName = data case "userPassword": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userPassword")) - it.UserPassword, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.UserPassword = data case "folder": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("folder")) - it.Folder, err = ec.unmarshalOID2ᚖstring(ctx, v) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Folder = data + case "configurationType": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configurationType")) + data, err := ec.unmarshalODriverConfigurationType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType(ctx, v) + if err != nil { + return it, err + } + it.ConfigurationType = data + case "defaultCatalogName": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultCatalogName")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOString2ᚖstring(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.5") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*string); ok { + it.DefaultCatalogName = data + } else if tmp == nil { + it.DefaultCatalogName = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *string`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "defaultSchemaName": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultSchemaName")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOString2ᚖstring(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.0.5") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*string); ok { + it.DefaultSchemaName = data + } else if tmp == nil { + it.DefaultSchemaName = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *string`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputDataTransferOutputSettingsInput(ctx context.Context, obj any) (model.DataTransferOutputSettingsInput, error) { + var it model.DataTransferOutputSettingsInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"insertBom", "encoding", "timestampPattern", "compress", "fileName"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "insertBom": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("insertBom")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.InsertBom = data + case "encoding": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("encoding")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Encoding = data + case "timestampPattern": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("timestampPattern")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TimestampPattern = data + case "compress": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("compress")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.Compress = data + case "fileName": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("fileName")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.FileName = data } } return it, nil } -func (ec *executionContext) unmarshalInputDataTransferParameters(ctx context.Context, obj interface{}) (model.DataTransferParameters, error) { +func (ec *executionContext) unmarshalInputDataTransferParameters(ctx context.Context, obj any) (model.DataTransferParameters, error) { var it model.DataTransferParameters - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } - fieldsInOrder := [...]string{"processorId", "settings", "processorProperties", "filter"} + fieldsInOrder := [...]string{"processorId", "settings", "processorProperties", "outputSettings", "filter"} for _, k := range fieldsInOrder { v, ok := asMap[k] if !ok { @@ -37661,47 +41335,50 @@ func (ec *executionContext) unmarshalInputDataTransferParameters(ctx context.Con } switch k { case "processorId": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("processorId")) - it.ProcessorID, err = ec.unmarshalNID2string(ctx, v) + data, err := ec.unmarshalNID2string(ctx, v) if err != nil { return it, err } + it.ProcessorID = data case "settings": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("settings")) - it.Settings, err = ec.unmarshalOObject2interface(ctx, v) + data, err := ec.unmarshalOObject2interface(ctx, v) if err != nil { return it, err } + it.Settings = data case "processorProperties": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("processorProperties")) - it.ProcessorProperties, err = ec.unmarshalNObject2interface(ctx, v) + data, err := ec.unmarshalNObject2interface(ctx, v) if err != nil { return it, err } + it.ProcessorProperties = data + case "outputSettings": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("outputSettings")) + data, err := ec.unmarshalODataTransferOutputSettingsInput2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferOutputSettingsInput(ctx, v) + if err != nil { + return it, err + } + it.OutputSettings = data case "filter": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filter")) - it.Filter, err = ec.unmarshalOSQLDataFilter2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter(ctx, v) + data, err := ec.unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter(ctx, v) if err != nil { return it, err } + it.Filter = data } } return it, nil } -func (ec *executionContext) unmarshalInputNavigatorSettingsInput(ctx context.Context, obj interface{}) (model.NavigatorSettingsInput, error) { +func (ec *executionContext) unmarshalInputNavigatorSettingsInput(ctx context.Context, obj any) (model.NavigatorSettingsInput, error) { var it model.NavigatorSettingsInput - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } @@ -37713,75 +41390,68 @@ func (ec *executionContext) unmarshalInputNavigatorSettingsInput(ctx context.Con } switch k { case "showSystemObjects": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("showSystemObjects")) - it.ShowSystemObjects, err = ec.unmarshalNBoolean2bool(ctx, v) + data, err := ec.unmarshalNBoolean2bool(ctx, v) if err != nil { return it, err } + it.ShowSystemObjects = data case "showUtilityObjects": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("showUtilityObjects")) - it.ShowUtilityObjects, err = ec.unmarshalNBoolean2bool(ctx, v) + data, err := ec.unmarshalNBoolean2bool(ctx, v) if err != nil { return it, err } + it.ShowUtilityObjects = data case "showOnlyEntities": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("showOnlyEntities")) - it.ShowOnlyEntities, err = ec.unmarshalNBoolean2bool(ctx, v) + data, err := ec.unmarshalNBoolean2bool(ctx, v) if err != nil { return it, err } + it.ShowOnlyEntities = data case "mergeEntities": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("mergeEntities")) - it.MergeEntities, err = ec.unmarshalNBoolean2bool(ctx, v) + data, err := ec.unmarshalNBoolean2bool(ctx, v) if err != nil { return it, err } + it.MergeEntities = data case "hideFolders": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hideFolders")) - it.HideFolders, err = ec.unmarshalNBoolean2bool(ctx, v) + data, err := ec.unmarshalNBoolean2bool(ctx, v) if err != nil { return it, err } + it.HideFolders = data case "hideSchemas": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hideSchemas")) - it.HideSchemas, err = ec.unmarshalNBoolean2bool(ctx, v) + data, err := ec.unmarshalNBoolean2bool(ctx, v) if err != nil { return it, err } + it.HideSchemas = data case "hideVirtualModel": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hideVirtualModel")) - it.HideVirtualModel, err = ec.unmarshalNBoolean2bool(ctx, v) + data, err := ec.unmarshalNBoolean2bool(ctx, v) if err != nil { return it, err } + it.HideVirtualModel = data } } return it, nil } -func (ec *executionContext) unmarshalInputNetworkHandlerConfigInput(ctx context.Context, obj interface{}) (model.NetworkHandlerConfigInput, error) { +func (ec *executionContext) unmarshalInputNetworkHandlerConfigInput(ctx context.Context, obj any) (model.NetworkHandlerConfigInput, error) { var it model.NetworkHandlerConfigInput - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } - fieldsInOrder := [...]string{"id", "enabled", "authType", "userName", "password", "key", "savePassword", "properties"} + fieldsInOrder := [...]string{"id", "enabled", "authType", "userName", "password", "key", "savePassword", "properties", "secureProperties"} for _, k := range fieldsInOrder { v, ok := asMap[k] if !ok { @@ -37789,79 +41459,78 @@ func (ec *executionContext) unmarshalInputNetworkHandlerConfigInput(ctx context. } switch k { case "id": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) - it.ID, err = ec.unmarshalNID2string(ctx, v) + data, err := ec.unmarshalNID2string(ctx, v) if err != nil { return it, err } + it.ID = data case "enabled": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabled")) - it.Enabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.Enabled = data case "authType": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authType")) - it.AuthType, err = ec.unmarshalONetworkHandlerAuthType2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx, v) + data, err := ec.unmarshalONetworkHandlerAuthType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx, v) if err != nil { return it, err } + it.AuthType = data case "userName": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userName")) - it.UserName, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.UserName = data case "password": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("password")) - it.Password, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Password = data case "key": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("key")) - it.Key, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Key = data case "savePassword": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("savePassword")) - it.SavePassword, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.SavePassword = data case "properties": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("properties")) - it.Properties, err = ec.unmarshalOObject2interface(ctx, v) + data, err := ec.unmarshalOObject2interface(ctx, v) if err != nil { return it, err } + it.Properties = data + case "secureProperties": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("secureProperties")) + data, err := ec.unmarshalOObject2interface(ctx, v) + if err != nil { + return it, err + } + it.SecureProperties = data } } return it, nil } -func (ec *executionContext) unmarshalInputObjectPropertyFilter(ctx context.Context, obj interface{}) (model.ObjectPropertyFilter, error) { +func (ec *executionContext) unmarshalInputObjectPropertyFilter(ctx context.Context, obj any) (model.ObjectPropertyFilter, error) { var it model.ObjectPropertyFilter - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } @@ -37873,47 +41542,145 @@ func (ec *executionContext) unmarshalInputObjectPropertyFilter(ctx context.Conte } switch k { case "ids": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("ids")) - it.Ids, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) if err != nil { return it, err } + it.Ids = data case "features": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("features")) - it.Features, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) if err != nil { return it, err } + it.Features = data case "categories": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categories")) - it.Categories, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) if err != nil { return it, err } + it.Categories = data case "dataTypes": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("dataTypes")) - it.DataTypes, err = ec.unmarshalOString2ᚕstringᚄ(ctx, v) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.DataTypes = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputPageInput(ctx context.Context, obj any) (model.PageInput, error) { + var it model.PageInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"limit", "offset"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "limit": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("limit")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.Limit = data + case "offset": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("offset")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) if err != nil { return it, err } + it.Offset = data } } return it, nil } -func (ec *executionContext) unmarshalInputSQLDataFilter(ctx context.Context, obj interface{}) (model.SQLDataFilter, error) { +func (ec *executionContext) unmarshalInputRMProjectPermissions(ctx context.Context, obj any) (model.RMProjectPermissions, error) { + var it model.RMProjectPermissions + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"projectId", "permissions"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "projectId": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("projectId")) + data, err := ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + it.ProjectID = data + case "permissions": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("permissions")) + data, err := ec.unmarshalNString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.Permissions = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputRMSubjectProjectPermissions(ctx context.Context, obj any) (model.RMSubjectProjectPermissions, error) { + var it model.RMSubjectProjectPermissions + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"subjectId", "permissions"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "subjectId": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subjectId")) + data, err := ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + it.SubjectID = data + case "permissions": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("permissions")) + data, err := ec.unmarshalNString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.Permissions = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputSQLDataFilter(ctx context.Context, obj any) (model.SQLDataFilter, error) { var it model.SQLDataFilter - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } @@ -37925,55 +41692,50 @@ func (ec *executionContext) unmarshalInputSQLDataFilter(ctx context.Context, obj } switch k { case "offset": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("offset")) - it.Offset, err = ec.unmarshalOFloat2ᚖfloat64(ctx, v) + data, err := ec.unmarshalOFloat2ᚖfloat64(ctx, v) if err != nil { return it, err } + it.Offset = data case "limit": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("limit")) - it.Limit, err = ec.unmarshalOInt2ᚖint(ctx, v) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) if err != nil { return it, err } + it.Limit = data case "constraints": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("constraints")) - it.Constraints, err = ec.unmarshalOSQLDataFilterConstraint2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx, v) + data, err := ec.unmarshalOSQLDataFilterConstraint2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx, v) if err != nil { return it, err } + it.Constraints = data case "where": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) - it.Where, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Where = data case "orderBy": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) - it.OrderBy, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.OrderBy = data } } return it, nil } -func (ec *executionContext) unmarshalInputSQLDataFilterConstraint(ctx context.Context, obj interface{}) (model.SQLDataFilterConstraint, error) { +func (ec *executionContext) unmarshalInputSQLDataFilterConstraint(ctx context.Context, obj any) (model.SQLDataFilterConstraint, error) { var it model.SQLDataFilterConstraint - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } @@ -37985,67 +41747,61 @@ func (ec *executionContext) unmarshalInputSQLDataFilterConstraint(ctx context.Co } switch k { case "attributePosition": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("attributePosition")) - it.AttributePosition, err = ec.unmarshalNInt2int(ctx, v) + data, err := ec.unmarshalNInt2int(ctx, v) if err != nil { return it, err } + it.AttributePosition = data case "orderPosition": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("orderPosition")) - it.OrderPosition, err = ec.unmarshalOInt2ᚖint(ctx, v) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) if err != nil { return it, err } + it.OrderPosition = data case "orderAsc": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("orderAsc")) - it.OrderAsc, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.OrderAsc = data case "criteria": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("criteria")) - it.Criteria, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Criteria = data case "operator": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("operator")) - it.Operator, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.Operator = data case "value": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("value")) - it.Value, err = ec.unmarshalOObject2interface(ctx, v) + data, err := ec.unmarshalOObject2interface(ctx, v) if err != nil { return it, err } + it.Value = data } } return it, nil } -func (ec *executionContext) unmarshalInputSQLResultRow(ctx context.Context, obj interface{}) (model.SQLResultRow, error) { +func (ec *executionContext) unmarshalInputSQLResultRow(ctx context.Context, obj any) (model.SQLResultRow, error) { var it model.SQLResultRow - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } - fieldsInOrder := [...]string{"data", "updateValues"} + fieldsInOrder := [...]string{"data", "updateValues", "metaData"} for _, k := range fieldsInOrder { v, ok := asMap[k] if !ok { @@ -38053,35 +41809,74 @@ func (ec *executionContext) unmarshalInputSQLResultRow(ctx context.Context, obj } switch k { case "data": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("data")) - it.Data, err = ec.unmarshalNObject2ᚕinterface(ctx, v) + data, err := ec.unmarshalNObject2ᚕinterface(ctx, v) if err != nil { return it, err } + it.Data = data case "updateValues": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("updateValues")) - it.UpdateValues, err = ec.unmarshalOObject2interface(ctx, v) + data, err := ec.unmarshalOObject2interface(ctx, v) if err != nil { return it, err } + it.UpdateValues = data + case "metaData": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("metaData")) + data, err := ec.unmarshalOObject2interface(ctx, v) + if err != nil { + return it, err + } + it.MetaData = data } } return it, nil } -func (ec *executionContext) unmarshalInputServerConfigInput(ctx context.Context, obj interface{}) (model.ServerConfigInput, error) { +func (ec *executionContext) unmarshalInputSQLResultRowMetaDataInput(ctx context.Context, obj any) (model.SQLResultRowMetaDataInput, error) { + var it model.SQLResultRowMetaDataInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"data", "metaData"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "data": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("data")) + data, err := ec.unmarshalOObject2ᚕinterface(ctx, v) + if err != nil { + return it, err + } + it.Data = data + case "metaData": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("metaData")) + data, err := ec.unmarshalNObject2interface(ctx, v) + if err != nil { + return it, err + } + it.MetaData = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputServerConfigInput(ctx context.Context, obj any) (model.ServerConfigInput, error) { var it model.ServerConfigInput - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } - fieldsInOrder := [...]string{"serverName", "serverURL", "adminName", "adminPassword", "anonymousAccessEnabled", "authenticationEnabled", "customConnectionsEnabled", "publicCredentialsSaveEnabled", "adminCredentialsSaveEnabled", "resourceManagerEnabled", "enabledFeatures", "enabledAuthProviders", "disabledDrivers", "sessionExpireTime"} + fieldsInOrder := [...]string{"serverName", "serverURL", "adminName", "adminPassword", "anonymousAccessEnabled", "authenticationEnabled", "customConnectionsEnabled", "publicCredentialsSaveEnabled", "adminCredentialsSaveEnabled", "resourceManagerEnabled", "secretManagerEnabled", "enabledFeatures", "enabledAuthProviders", "disabledDrivers", "sessionExpireTime", "forceHttps", "supportedHosts", "bindSessionToIp"} for _, k := range fieldsInOrder { v, ok := asMap[k] if !ok { @@ -38089,117 +41884,219 @@ func (ec *executionContext) unmarshalInputServerConfigInput(ctx context.Context, } switch k { case "serverName": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("serverName")) - it.ServerName, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.ServerName = data case "serverURL": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("serverURL")) - it.ServerURL, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.ServerURL = data case "adminName": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("adminName")) - it.AdminName, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.AdminName = data case "adminPassword": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("adminPassword")) - it.AdminPassword, err = ec.unmarshalOString2ᚖstring(ctx, v) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) if err != nil { return it, err } + it.AdminPassword = data case "anonymousAccessEnabled": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("anonymousAccessEnabled")) - it.AnonymousAccessEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.AnonymousAccessEnabled = data case "authenticationEnabled": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("authenticationEnabled")) - it.AuthenticationEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.AuthenticationEnabled = data case "customConnectionsEnabled": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("customConnectionsEnabled")) - it.CustomConnectionsEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.CustomConnectionsEnabled = data case "publicCredentialsSaveEnabled": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("publicCredentialsSaveEnabled")) - it.PublicCredentialsSaveEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.PublicCredentialsSaveEnabled = data case "adminCredentialsSaveEnabled": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("adminCredentialsSaveEnabled")) - it.AdminCredentialsSaveEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } + it.AdminCredentialsSaveEnabled = data case "resourceManagerEnabled": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("resourceManagerEnabled")) - it.ResourceManagerEnabled, err = ec.unmarshalOBoolean2ᚖbool(ctx, v) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) if err != nil { return it, err } - case "enabledFeatures": - var err error + it.ResourceManagerEnabled = data + case "secretManagerEnabled": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("secretManagerEnabled")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOBoolean2ᚖbool(ctx, v) } + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "24.3.2") + if err != nil { + var zeroVal *bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*bool); ok { + it.SecretManagerEnabled = data + } else if tmp == nil { + it.SecretManagerEnabled = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *bool`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "enabledFeatures": ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabledFeatures")) - it.EnabledFeatures, err = ec.unmarshalOID2ᚕstringᚄ(ctx, v) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) if err != nil { return it, err } + it.EnabledFeatures = data case "enabledAuthProviders": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("enabledAuthProviders")) - it.EnabledAuthProviders, err = ec.unmarshalOID2ᚕstringᚄ(ctx, v) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) if err != nil { return it, err } + it.EnabledAuthProviders = data case "disabledDrivers": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("disabledDrivers")) - it.DisabledDrivers, err = ec.unmarshalOID2ᚕstringᚄ(ctx, v) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) if err != nil { return it, err } + it.DisabledDrivers = data case "sessionExpireTime": - var err error - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("sessionExpireTime")) - it.SessionExpireTime, err = ec.unmarshalOInt2ᚖint(ctx, v) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) if err != nil { return it, err } + it.SessionExpireTime = data + case "forceHttps": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("forceHttps")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOBoolean2ᚖbool(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.1.3") + if err != nil { + var zeroVal *bool + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *bool + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*bool); ok { + it.ForceHTTPS = data + } else if tmp == nil { + it.ForceHTTPS = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *bool`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "supportedHosts": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("supportedHosts")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOString2ᚕstringᚄ(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.1.3") + if err != nil { + var zeroVal []string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal []string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.([]string); ok { + it.SupportedHosts = data + } else if tmp == nil { + it.SupportedHosts = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be []string`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "bindSessionToIp": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("bindSessionToIp")) + directive0 := func(ctx context.Context) (any, error) { return ec.unmarshalOString2ᚖstring(ctx, v) } + + directive1 := func(ctx context.Context) (any, error) { + version, err := ec.unmarshalNString2string(ctx, "25.1.4") + if err != nil { + var zeroVal *string + return zeroVal, err + } + if ec.directives.Since == nil { + var zeroVal *string + return zeroVal, errors.New("directive since is not implemented") + } + return ec.directives.Since(ctx, obj, directive0, version) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*string); ok { + it.BindSessionToIP = data + } else if tmp == nil { + it.BindSessionToIP = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *string`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } } } @@ -38218,79 +42115,74 @@ var adminAuthProviderConfigurationImplementors = []string{"AdminAuthProviderConf func (ec *executionContext) _AdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, obj *model.AdminAuthProviderConfiguration) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, adminAuthProviderConfigurationImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AdminAuthProviderConfiguration") case "providerId": - out.Values[i] = ec._AdminAuthProviderConfiguration_providerId(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "id": - out.Values[i] = ec._AdminAuthProviderConfiguration_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "displayName": - out.Values[i] = ec._AdminAuthProviderConfiguration_displayName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "disabled": - out.Values[i] = ec._AdminAuthProviderConfiguration_disabled(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "iconURL": - out.Values[i] = ec._AdminAuthProviderConfiguration_iconURL(ctx, field, obj) - case "description": - out.Values[i] = ec._AdminAuthProviderConfiguration_description(ctx, field, obj) - case "parameters": - out.Values[i] = ec._AdminAuthProviderConfiguration_parameters(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "signInLink": - out.Values[i] = ec._AdminAuthProviderConfiguration_signInLink(ctx, field, obj) - case "signOutLink": - out.Values[i] = ec._AdminAuthProviderConfiguration_signOutLink(ctx, field, obj) - case "redirectLink": - out.Values[i] = ec._AdminAuthProviderConfiguration_redirectLink(ctx, field, obj) - case "metadataLink": - out.Values[i] = ec._AdminAuthProviderConfiguration_metadataLink(ctx, field, obj) - + case "acsLink": + out.Values[i] = ec._AdminAuthProviderConfiguration_acsLink(ctx, field, obj) + case "entityIdLink": + out.Values[i] = ec._AdminAuthProviderConfiguration_entityIdLink(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38298,48 +42190,53 @@ var adminConnectionGrantInfoImplementors = []string{"AdminConnectionGrantInfo"} func (ec *executionContext) _AdminConnectionGrantInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminConnectionGrantInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, adminConnectionGrantInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AdminConnectionGrantInfo") case "connectionId": - out.Values[i] = ec._AdminConnectionGrantInfo_connectionId(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "dataSourceId": - out.Values[i] = ec._AdminConnectionGrantInfo_dataSourceId(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "subjectId": - out.Values[i] = ec._AdminConnectionGrantInfo_subjectId(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "subjectType": - out.Values[i] = ec._AdminConnectionGrantInfo_subjectType(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38347,55 +42244,151 @@ var adminConnectionSearchInfoImplementors = []string{"AdminConnectionSearchInfo" func (ec *executionContext) _AdminConnectionSearchInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminConnectionSearchInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, adminConnectionSearchInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AdminConnectionSearchInfo") case "displayName": - out.Values[i] = ec._AdminConnectionSearchInfo_displayName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "host": - out.Values[i] = ec._AdminConnectionSearchInfo_host(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "port": - out.Values[i] = ec._AdminConnectionSearchInfo_port(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "possibleDrivers": - out.Values[i] = ec._AdminConnectionSearchInfo_possibleDrivers(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "defaultDriver": - out.Values[i] = ec._AdminConnectionSearchInfo_defaultDriver(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var adminObjectGrantInfoImplementors = []string{"AdminObjectGrantInfo"} + +func (ec *executionContext) _AdminObjectGrantInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminObjectGrantInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, adminObjectGrantInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("AdminObjectGrantInfo") + case "subjectId": + out.Values[i] = ec._AdminObjectGrantInfo_subjectId(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "subjectType": + out.Values[i] = ec._AdminObjectGrantInfo_subjectType(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "objectPermissions": + out.Values[i] = ec._AdminObjectGrantInfo_objectPermissions(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var adminObjectPermissionsImplementors = []string{"AdminObjectPermissions"} + +func (ec *executionContext) _AdminObjectPermissions(ctx context.Context, sel ast.SelectionSet, obj *model.AdminObjectPermissions) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, adminObjectPermissionsImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("AdminObjectPermissions") + case "objectId": + out.Values[i] = ec._AdminObjectPermissions_objectId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "permissions": + out.Values[i] = ec._AdminObjectPermissions_permissions(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38403,103 +42396,117 @@ var adminPermissionInfoImplementors = []string{"AdminPermissionInfo"} func (ec *executionContext) _AdminPermissionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminPermissionInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, adminPermissionInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AdminPermissionInfo") case "id": - out.Values[i] = ec._AdminPermissionInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "label": - out.Values[i] = ec._AdminPermissionInfo_label(ctx, field, obj) - case "description": - out.Values[i] = ec._AdminPermissionInfo_description(ctx, field, obj) - case "provider": - out.Values[i] = ec._AdminPermissionInfo_provider(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "category": - out.Values[i] = ec._AdminPermissionInfo_category(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } -var adminRoleInfoImplementors = []string{"AdminRoleInfo"} +var adminTeamInfoImplementors = []string{"AdminTeamInfo"} + +func (ec *executionContext) _AdminTeamInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminTeamInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, adminTeamInfoImplementors) -func (ec *executionContext) _AdminRoleInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminRoleInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, adminRoleInfoImplementors) out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": - out.Values[i] = graphql.MarshalString("AdminRoleInfo") - case "roleId": - - out.Values[i] = ec._AdminRoleInfo_roleId(ctx, field, obj) - + out.Values[i] = graphql.MarshalString("AdminTeamInfo") + case "teamId": + out.Values[i] = ec._AdminTeamInfo_teamId(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "roleName": - - out.Values[i] = ec._AdminRoleInfo_roleName(ctx, field, obj) - + case "teamName": + out.Values[i] = ec._AdminTeamInfo_teamName(ctx, field, obj) case "description": - - out.Values[i] = ec._AdminRoleInfo_description(ctx, field, obj) - + out.Values[i] = ec._AdminTeamInfo_description(ctx, field, obj) + case "metaParameters": + out.Values[i] = ec._AdminTeamInfo_metaParameters(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "grantedUsers": - - out.Values[i] = ec._AdminRoleInfo_grantedUsers(ctx, field, obj) - + out.Values[i] = ec._AdminTeamInfo_grantedUsers(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "grantedUsersInfo": + out.Values[i] = ec._AdminTeamInfo_grantedUsersInfo(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "grantedConnections": - - out.Values[i] = ec._AdminRoleInfo_grantedConnections(ctx, field, obj) - + out.Values[i] = ec._AdminTeamInfo_grantedConnections(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "rolePermissions": - - out.Values[i] = ec._AdminRoleInfo_rolePermissions(ctx, field, obj) - + case "teamPermissions": + out.Values[i] = ec._AdminTeamInfo_teamPermissions(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38507,76 +42514,122 @@ var adminUserInfoImplementors = []string{"AdminUserInfo"} func (ec *executionContext) _AdminUserInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminUserInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, adminUserInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AdminUserInfo") case "userId": - out.Values[i] = ec._AdminUserInfo_userId(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "metaParameters": - out.Values[i] = ec._AdminUserInfo_metaParameters(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "configurationParameters": - out.Values[i] = ec._AdminUserInfo_configurationParameters(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "grantedRoles": - - out.Values[i] = ec._AdminUserInfo_grantedRoles(ctx, field, obj) - + case "grantedTeams": + out.Values[i] = ec._AdminUserInfo_grantedTeams(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "grantedConnections": - out.Values[i] = ec._AdminUserInfo_grantedConnections(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "origins": - out.Values[i] = ec._AdminUserInfo_origins(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "linkedAuthProviders": - out.Values[i] = ec._AdminUserInfo_linkedAuthProviders(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "enabled": - out.Values[i] = ec._AdminUserInfo_enabled(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "authRole": + out.Values[i] = ec._AdminUserInfo_authRole(ctx, field, obj) + case "disableDate": + out.Values[i] = ec._AdminUserInfo_disableDate(ctx, field, obj) + case "disabledBy": + out.Values[i] = ec._AdminUserInfo_disabledBy(ctx, field, obj) + case "disableReason": + out.Values[i] = ec._AdminUserInfo_disableReason(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} +var adminUserTeamGrantInfoImplementors = []string{"AdminUserTeamGrantInfo"} + +func (ec *executionContext) _AdminUserTeamGrantInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AdminUserTeamGrantInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, adminUserTeamGrantInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("AdminUserTeamGrantInfo") + case "userId": + out.Values[i] = ec._AdminUserTeamGrantInfo_userId(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "teamRole": + out.Values[i] = ec._AdminUserTeamGrantInfo_teamRole(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38584,54 +42637,51 @@ var asyncTaskInfoImplementors = []string{"AsyncTaskInfo"} func (ec *executionContext) _AsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AsyncTaskInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, asyncTaskInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AsyncTaskInfo") case "id": - out.Values[i] = ec._AsyncTaskInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._AsyncTaskInfo_name(ctx, field, obj) - case "running": - out.Values[i] = ec._AsyncTaskInfo_running(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "status": - out.Values[i] = ec._AsyncTaskInfo_status(ctx, field, obj) - case "error": - out.Values[i] = ec._AsyncTaskInfo_error(ctx, field, obj) - - case "result": - - out.Values[i] = ec._AsyncTaskInfo_result(ctx, field, obj) - case "taskResult": - out.Values[i] = ec._AsyncTaskInfo_taskResult(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38639,67 +42689,64 @@ var authCredentialInfoImplementors = []string{"AuthCredentialInfo"} func (ec *executionContext) _AuthCredentialInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AuthCredentialInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, authCredentialInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AuthCredentialInfo") case "id": - out.Values[i] = ec._AuthCredentialInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "displayName": - out.Values[i] = ec._AuthCredentialInfo_displayName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "description": - out.Values[i] = ec._AuthCredentialInfo_description(ctx, field, obj) - case "admin": - out.Values[i] = ec._AuthCredentialInfo_admin(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "user": - out.Values[i] = ec._AuthCredentialInfo_user(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "identifying": - out.Values[i] = ec._AuthCredentialInfo_identifying(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "possibleValues": - out.Values[i] = ec._AuthCredentialInfo_possibleValues(ctx, field, obj) - case "encryption": - out.Values[i] = ec._AuthCredentialInfo_encryption(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38707,39 +42754,44 @@ var authInfoImplementors = []string{"AuthInfo"} func (ec *executionContext) _AuthInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AuthInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, authInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AuthInfo") case "redirectLink": - out.Values[i] = ec._AuthInfo_redirectLink(ctx, field, obj) - case "authId": - out.Values[i] = ec._AuthInfo_authId(ctx, field, obj) - case "authStatus": - out.Values[i] = ec._AuthInfo_authStatus(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "userTokens": - out.Values[i] = ec._AuthInfo_userTokens(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38747,61 +42799,66 @@ var authProviderConfigurationImplementors = []string{"AuthProviderConfiguration" func (ec *executionContext) _AuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, obj *model.AuthProviderConfiguration) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, authProviderConfigurationImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AuthProviderConfiguration") case "id": - out.Values[i] = ec._AuthProviderConfiguration_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "displayName": - out.Values[i] = ec._AuthProviderConfiguration_displayName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "disabled": - out.Values[i] = ec._AuthProviderConfiguration_disabled(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "authRoleProvided": + out.Values[i] = ec._AuthProviderConfiguration_authRoleProvided(ctx, field, obj) case "iconURL": - out.Values[i] = ec._AuthProviderConfiguration_iconURL(ctx, field, obj) - case "description": - out.Values[i] = ec._AuthProviderConfiguration_description(ctx, field, obj) - case "signInLink": - out.Values[i] = ec._AuthProviderConfiguration_signInLink(ctx, field, obj) - case "signOutLink": - out.Values[i] = ec._AuthProviderConfiguration_signOutLink(ctx, field, obj) - + case "redirectLink": + out.Values[i] = ec._AuthProviderConfiguration_redirectLink(ctx, field, obj) case "metadataLink": - out.Values[i] = ec._AuthProviderConfiguration_metadataLink(ctx, field, obj) - + case "acsLink": + out.Values[i] = ec._AuthProviderConfiguration_acsLink(ctx, field, obj) + case "entityIdLink": + out.Values[i] = ec._AuthProviderConfiguration_entityIdLink(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38809,39 +42866,44 @@ var authProviderCredentialsProfileImplementors = []string{"AuthProviderCredentia func (ec *executionContext) _AuthProviderCredentialsProfile(ctx context.Context, sel ast.SelectionSet, obj *model.AuthProviderCredentialsProfile) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, authProviderCredentialsProfileImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AuthProviderCredentialsProfile") case "id": - out.Values[i] = ec._AuthProviderCredentialsProfile_id(ctx, field, obj) - case "label": - out.Values[i] = ec._AuthProviderCredentialsProfile_label(ctx, field, obj) - case "description": - out.Values[i] = ec._AuthProviderCredentialsProfile_description(ctx, field, obj) - case "credentialParameters": - out.Values[i] = ec._AuthProviderCredentialsProfile_credentialParameters(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38849,74 +42911,148 @@ var authProviderInfoImplementors = []string{"AuthProviderInfo"} func (ec *executionContext) _AuthProviderInfo(ctx context.Context, sel ast.SelectionSet, obj *model.AuthProviderInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, authProviderInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("AuthProviderInfo") case "id": - out.Values[i] = ec._AuthProviderInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "label": - out.Values[i] = ec._AuthProviderInfo_label(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "icon": - out.Values[i] = ec._AuthProviderInfo_icon(ctx, field, obj) - case "description": - out.Values[i] = ec._AuthProviderInfo_description(ctx, field, obj) - case "defaultProvider": - out.Values[i] = ec._AuthProviderInfo_defaultProvider(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "trusted": + out.Values[i] = ec._AuthProviderInfo_trusted(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "private": + out.Values[i] = ec._AuthProviderInfo_private(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "authHidden": + out.Values[i] = ec._AuthProviderInfo_authHidden(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "supportProvisioning": + out.Values[i] = ec._AuthProviderInfo_supportProvisioning(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "configurable": - out.Values[i] = ec._AuthProviderInfo_configurable(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "federated": + out.Values[i] = ec._AuthProviderInfo_federated(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "configurations": - out.Values[i] = ec._AuthProviderInfo_configurations(ctx, field, obj) - + case "templateConfiguration": + out.Values[i] = ec._AuthProviderInfo_templateConfiguration(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "credentialProfiles": - out.Values[i] = ec._AuthProviderInfo_credentialProfiles(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "requiredFeatures": - out.Values[i] = ec._AuthProviderInfo_requiredFeatures(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "required": + out.Values[i] = ec._AuthProviderInfo_required(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var conditionImplementors = []string{"Condition"} + +func (ec *executionContext) _Condition(ctx context.Context, sel ast.SelectionSet, obj *model.Condition) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, conditionImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Condition") + case "expression": + out.Values[i] = ec._Condition_expression(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "conditionType": + out.Values[i] = ec._Condition_conditionType(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38924,31 +43060,45 @@ var connectionFolderInfoImplementors = []string{"ConnectionFolderInfo"} func (ec *executionContext) _ConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ConnectionFolderInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, connectionFolderInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ConnectionFolderInfo") case "id": - out.Values[i] = ec._ConnectionFolderInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "projectId": + out.Values[i] = ec._ConnectionFolderInfo_projectId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "description": - out.Values[i] = ec._ConnectionFolderInfo_description(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -38956,195 +43106,298 @@ var connectionInfoImplementors = []string{"ConnectionInfo"} func (ec *executionContext) _ConnectionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ConnectionInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, connectionInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ConnectionInfo") case "id": - out.Values[i] = ec._ConnectionInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "driverId": - out.Values[i] = ec._ConnectionInfo_driverId(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._ConnectionInfo_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "description": - out.Values[i] = ec._ConnectionInfo_description(ctx, field, obj) - case "host": - out.Values[i] = ec._ConnectionInfo_host(ctx, field, obj) - case "port": - out.Values[i] = ec._ConnectionInfo_port(ctx, field, obj) - case "serverName": - out.Values[i] = ec._ConnectionInfo_serverName(ctx, field, obj) - case "databaseName": - out.Values[i] = ec._ConnectionInfo_databaseName(ctx, field, obj) - case "url": - out.Values[i] = ec._ConnectionInfo_url(ctx, field, obj) - - case "properties": - - out.Values[i] = ec._ConnectionInfo_properties(ctx, field, obj) - - case "template": - - out.Values[i] = ec._ConnectionInfo_template(ctx, field, obj) - + case "mainPropertyValues": + out.Values[i] = ec._ConnectionInfo_mainPropertyValues(ctx, field, obj) + case "expertSettingsValues": + out.Values[i] = ec._ConnectionInfo_expertSettingsValues(ctx, field, obj) + case "keepAliveInterval": + out.Values[i] = ec._ConnectionInfo_keepAliveInterval(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "autocommit": + out.Values[i] = ec._ConnectionInfo_autocommit(ctx, field, obj) + case "properties": + out.Values[i] = ec._ConnectionInfo_properties(ctx, field, obj) case "connected": - out.Values[i] = ec._ConnectionInfo_connected(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "provided": - out.Values[i] = ec._ConnectionInfo_provided(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "readOnly": - out.Values[i] = ec._ConnectionInfo_readOnly(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "useUrl": - out.Values[i] = ec._ConnectionInfo_useUrl(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "saveCredentials": - out.Values[i] = ec._ConnectionInfo_saveCredentials(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "sharedCredentials": + out.Values[i] = ec._ConnectionInfo_sharedCredentials(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "sharedSecrets": + out.Values[i] = ec._ConnectionInfo_sharedSecrets(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "credentialsSaved": + out.Values[i] = ec._ConnectionInfo_credentialsSaved(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "authNeeded": + out.Values[i] = ec._ConnectionInfo_authNeeded(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "folder": - out.Values[i] = ec._ConnectionInfo_folder(ctx, field, obj) - case "nodePath": - out.Values[i] = ec._ConnectionInfo_nodePath(ctx, field, obj) - case "connectTime": - out.Values[i] = ec._ConnectionInfo_connectTime(ctx, field, obj) - case "connectionError": - out.Values[i] = ec._ConnectionInfo_connectionError(ctx, field, obj) - case "serverVersion": - out.Values[i] = ec._ConnectionInfo_serverVersion(ctx, field, obj) - case "clientVersion": - out.Values[i] = ec._ConnectionInfo_clientVersion(ctx, field, obj) - case "origin": - out.Values[i] = ec._ConnectionInfo_origin(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "authNeeded": - - out.Values[i] = ec._ConnectionInfo_authNeeded(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "authModel": - out.Values[i] = ec._ConnectionInfo_authModel(ctx, field, obj) - case "authProperties": - out.Values[i] = ec._ConnectionInfo_authProperties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "providerProperties": - out.Values[i] = ec._ConnectionInfo_providerProperties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "networkHandlersConfig": - out.Values[i] = ec._ConnectionInfo_networkHandlersConfig(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "features": - out.Values[i] = ec._ConnectionInfo_features(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "navigatorSettings": - out.Values[i] = ec._ConnectionInfo_navigatorSettings(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "supportedDataFormats": - out.Values[i] = ec._ConnectionInfo_supportedDataFormats(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "configurationType": + out.Values[i] = ec._ConnectionInfo_configurationType(ctx, field, obj) + case "canViewSettings": + out.Values[i] = ec._ConnectionInfo_canViewSettings(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "canEdit": + out.Values[i] = ec._ConnectionInfo_canEdit(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "canDelete": + out.Values[i] = ec._ConnectionInfo_canDelete(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "projectId": + out.Values[i] = ec._ConnectionInfo_projectId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "requiredAuth": + out.Values[i] = ec._ConnectionInfo_requiredAuth(ctx, field, obj) + case "defaultCatalogName": + out.Values[i] = ec._ConnectionInfo_defaultCatalogName(ctx, field, obj) + case "defaultSchemaName": + out.Values[i] = ec._ConnectionInfo_defaultSchemaName(ctx, field, obj) + case "tools": + out.Values[i] = ec._ConnectionInfo_tools(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var dataTransferDefaultExportSettingsImplementors = []string{"DataTransferDefaultExportSettings"} + +func (ec *executionContext) _DataTransferDefaultExportSettings(ctx context.Context, sel ast.SelectionSet, obj *model.DataTransferDefaultExportSettings) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, dataTransferDefaultExportSettingsImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("DataTransferDefaultExportSettings") + case "outputSettings": + out.Values[i] = ec._DataTransferDefaultExportSettings_outputSettings(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "supportedEncodings": + out.Values[i] = ec._DataTransferDefaultExportSettings_supportedEncodings(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} +var dataTransferOutputSettingsImplementors = []string{"DataTransferOutputSettings"} + +func (ec *executionContext) _DataTransferOutputSettings(ctx context.Context, sel ast.SelectionSet, obj *model.DataTransferOutputSettings) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, dataTransferOutputSettingsImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("DataTransferOutputSettings") + case "insertBom": + out.Values[i] = ec._DataTransferOutputSettings_insertBom(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "encoding": + out.Values[i] = ec._DataTransferOutputSettings_encoding(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "timestampPattern": + out.Values[i] = ec._DataTransferOutputSettings_timestampPattern(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "compress": + out.Values[i] = ec._DataTransferOutputSettings_compress(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39152,70 +43405,61 @@ var dataTransferProcessorInfoImplementors = []string{"DataTransferProcessorInfo" func (ec *executionContext) _DataTransferProcessorInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DataTransferProcessorInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, dataTransferProcessorInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DataTransferProcessorInfo") case "id": - out.Values[i] = ec._DataTransferProcessorInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._DataTransferProcessorInfo_name(ctx, field, obj) - case "description": - out.Values[i] = ec._DataTransferProcessorInfo_description(ctx, field, obj) - case "fileExtension": - out.Values[i] = ec._DataTransferProcessorInfo_fileExtension(ctx, field, obj) - case "appFileExtension": - out.Values[i] = ec._DataTransferProcessorInfo_appFileExtension(ctx, field, obj) - case "appName": - out.Values[i] = ec._DataTransferProcessorInfo_appName(ctx, field, obj) - case "order": - out.Values[i] = ec._DataTransferProcessorInfo_order(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "icon": - out.Values[i] = ec._DataTransferProcessorInfo_icon(ctx, field, obj) - case "properties": - out.Values[i] = ec._DataTransferProcessorInfo_properties(ctx, field, obj) - case "isBinary": - out.Values[i] = ec._DataTransferProcessorInfo_isBinary(ctx, field, obj) - case "isHTML": - out.Values[i] = ec._DataTransferProcessorInfo_isHTML(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39223,38 +43467,45 @@ var dataTypeLogicalOperationImplementors = []string{"DataTypeLogicalOperation"} func (ec *executionContext) _DataTypeLogicalOperation(ctx context.Context, sel ast.SelectionSet, obj *model.DataTypeLogicalOperation) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, dataTypeLogicalOperationImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DataTypeLogicalOperation") case "id": - out.Values[i] = ec._DataTypeLogicalOperation_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "expression": - out.Values[i] = ec._DataTypeLogicalOperation_expression(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "argumentCount": - out.Values[i] = ec._DataTypeLogicalOperation_argumentCount(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39262,53 +43513,56 @@ var databaseAuthModelImplementors = []string{"DatabaseAuthModel"} func (ec *executionContext) _DatabaseAuthModel(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseAuthModel) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, databaseAuthModelImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DatabaseAuthModel") case "id": - out.Values[i] = ec._DatabaseAuthModel_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "displayName": - out.Values[i] = ec._DatabaseAuthModel_displayName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "description": - out.Values[i] = ec._DatabaseAuthModel_description(ctx, field, obj) - case "icon": - out.Values[i] = ec._DatabaseAuthModel_icon(ctx, field, obj) - case "requiresLocalConfiguration": - out.Values[i] = ec._DatabaseAuthModel_requiresLocalConfiguration(ctx, field, obj) - + case "requiredAuth": + out.Values[i] = ec._DatabaseAuthModel_requiredAuth(ctx, field, obj) case "properties": - out.Values[i] = ec._DatabaseAuthModel_properties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39316,34 +43570,43 @@ var databaseCatalogImplementors = []string{"DatabaseCatalog"} func (ec *executionContext) _DatabaseCatalog(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseCatalog) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, databaseCatalogImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DatabaseCatalog") case "catalog": - out.Values[i] = ec._DatabaseCatalog_catalog(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "schemaList": - out.Values[i] = ec._DatabaseCatalog_schemaList(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39351,36 +43614,41 @@ var databaseDocumentImplementors = []string{"DatabaseDocument"} func (ec *executionContext) _DatabaseDocument(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseDocument) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, databaseDocumentImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DatabaseDocument") case "id": - out.Values[i] = ec._DatabaseDocument_id(ctx, field, obj) - case "contentType": - out.Values[i] = ec._DatabaseDocument_contentType(ctx, field, obj) - case "properties": - out.Values[i] = ec._DatabaseDocument_properties(ctx, field, obj) - case "data": - out.Values[i] = ec._DatabaseDocument_data(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39388,64 +43656,55 @@ var databaseObjectInfoImplementors = []string{"DatabaseObjectInfo"} func (ec *executionContext) _DatabaseObjectInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseObjectInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, databaseObjectInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DatabaseObjectInfo") case "name": - out.Values[i] = ec._DatabaseObjectInfo_name(ctx, field, obj) - case "description": - out.Values[i] = ec._DatabaseObjectInfo_description(ctx, field, obj) - case "type": - out.Values[i] = ec._DatabaseObjectInfo_type(ctx, field, obj) - case "properties": - out.Values[i] = ec._DatabaseObjectInfo_properties(ctx, field, obj) - case "ordinalPosition": - out.Values[i] = ec._DatabaseObjectInfo_ordinalPosition(ctx, field, obj) - case "fullyQualifiedName": - out.Values[i] = ec._DatabaseObjectInfo_fullyQualifiedName(ctx, field, obj) - case "overloadedName": - out.Values[i] = ec._DatabaseObjectInfo_overloadedName(ctx, field, obj) - case "uniqueName": - out.Values[i] = ec._DatabaseObjectInfo_uniqueName(ctx, field, obj) - case "state": - out.Values[i] = ec._DatabaseObjectInfo_state(ctx, field, obj) - case "features": - out.Values[i] = ec._DatabaseObjectInfo_features(ctx, field, obj) - case "editors": - out.Values[i] = ec._DatabaseObjectInfo_editors(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39453,48 +43712,101 @@ var databaseStructContainersImplementors = []string{"DatabaseStructContainers"} func (ec *executionContext) _DatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, obj *model.DatabaseStructContainers) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, databaseStructContainersImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DatabaseStructContainers") + case "parentNode": + out.Values[i] = ec._DatabaseStructContainers_parentNode(ctx, field, obj) case "catalogList": - out.Values[i] = ec._DatabaseStructContainers_catalogList(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "schemaList": - out.Values[i] = ec._DatabaseStructContainers_schemaList(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "supportsCatalogChange": + out.Values[i] = ec._DatabaseStructContainers_supportsCatalogChange(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "supportsSchemaChange": + out.Values[i] = ec._DatabaseStructContainers_supportsSchemaChange(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} - out.Values[i] = ec._DatabaseStructContainers_supportsCatalogChange(ctx, field, obj) +var driverFileInfoImplementors = []string{"DriverFileInfo"} + +func (ec *executionContext) _DriverFileInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DriverFileInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, driverFileInfoImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("DriverFileInfo") + case "id": + out.Values[i] = ec._DriverFileInfo_id(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "supportsSchemaChange": - - out.Values[i] = ec._DatabaseStructContainers_supportsSchemaChange(ctx, field, obj) - + case "fileName": + out.Values[i] = ec._DriverFileInfo_fileName(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "icon": + out.Values[i] = ec._DriverFileInfo_icon(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39502,164 +43814,339 @@ var driverInfoImplementors = []string{"DriverInfo"} func (ec *executionContext) _DriverInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DriverInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, driverInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("DriverInfo") case "id": - out.Values[i] = ec._DriverInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._DriverInfo_name(ctx, field, obj) - case "description": - out.Values[i] = ec._DriverInfo_description(ctx, field, obj) - case "icon": - out.Values[i] = ec._DriverInfo_icon(ctx, field, obj) - case "iconBig": - out.Values[i] = ec._DriverInfo_iconBig(ctx, field, obj) - + case "driverId": + out.Values[i] = ec._DriverInfo_driverId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "providerId": - out.Values[i] = ec._DriverInfo_providerId(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "driverClassName": - out.Values[i] = ec._DriverInfo_driverClassName(ctx, field, obj) - case "defaultHost": - out.Values[i] = ec._DriverInfo_defaultHost(ctx, field, obj) - case "defaultPort": - out.Values[i] = ec._DriverInfo_defaultPort(ctx, field, obj) - case "defaultDatabase": - out.Values[i] = ec._DriverInfo_defaultDatabase(ctx, field, obj) - case "defaultServer": - out.Values[i] = ec._DriverInfo_defaultServer(ctx, field, obj) - case "defaultUser": - out.Values[i] = ec._DriverInfo_defaultUser(ctx, field, obj) - case "sampleURL": - out.Values[i] = ec._DriverInfo_sampleURL(ctx, field, obj) - case "driverInfoURL": - out.Values[i] = ec._DriverInfo_driverInfoURL(ctx, field, obj) - case "driverPropertiesURL": - out.Values[i] = ec._DriverInfo_driverPropertiesURL(ctx, field, obj) - case "embedded": - out.Values[i] = ec._DriverInfo_embedded(ctx, field, obj) - case "enabled": - out.Values[i] = ec._DriverInfo_enabled(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "requiresServerName": - out.Values[i] = ec._DriverInfo_requiresServerName(ctx, field, obj) - - case "allowsEmptyPassword": - - out.Values[i] = ec._DriverInfo_allowsEmptyPassword(ctx, field, obj) - + case "requiresDatabaseName": + out.Values[i] = ec._DriverInfo_requiresDatabaseName(ctx, field, obj) + case "useCustomPage": + out.Values[i] = ec._DriverInfo_useCustomPage(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "licenseRequired": - out.Values[i] = ec._DriverInfo_licenseRequired(ctx, field, obj) - case "license": - out.Values[i] = ec._DriverInfo_license(ctx, field, obj) - case "custom": - out.Values[i] = ec._DriverInfo_custom(ctx, field, obj) - case "promotedScore": - out.Values[i] = ec._DriverInfo_promotedScore(ctx, field, obj) - case "driverProperties": - out.Values[i] = ec._DriverInfo_driverProperties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "driverParameters": - out.Values[i] = ec._DriverInfo_driverParameters(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "mainProperties": + out.Values[i] = ec._DriverInfo_mainProperties(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "providerProperties": - out.Values[i] = ec._DriverInfo_providerProperties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "expertSettingsProperties": + out.Values[i] = ec._DriverInfo_expertSettingsProperties(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "anonymousAccess": - out.Values[i] = ec._DriverInfo_anonymousAccess(ctx, field, obj) - case "defaultAuthModel": - out.Values[i] = ec._DriverInfo_defaultAuthModel(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "applicableAuthModels": - out.Values[i] = ec._DriverInfo_applicableAuthModels(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "applicableNetworkHandlers": - out.Values[i] = ec._DriverInfo_applicableNetworkHandlers(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "configurationTypes": + out.Values[i] = ec._DriverInfo_configurationTypes(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "downloadable": + out.Values[i] = ec._DriverInfo_downloadable(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "driverInstalled": + out.Values[i] = ec._DriverInfo_driverInstalled(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "driverLibraries": + out.Values[i] = ec._DriverInfo_driverLibraries(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "safeEmbeddedDriver": + out.Values[i] = ec._DriverInfo_safeEmbeddedDriver(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var driverLibraryInfoImplementors = []string{"DriverLibraryInfo"} + +func (ec *executionContext) _DriverLibraryInfo(ctx context.Context, sel ast.SelectionSet, obj *model.DriverLibraryInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, driverLibraryInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("DriverLibraryInfo") + case "id": + out.Values[i] = ec._DriverLibraryInfo_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "name": + out.Values[i] = ec._DriverLibraryInfo_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "icon": + out.Values[i] = ec._DriverLibraryInfo_icon(ctx, field, obj) + case "libraryFiles": + out.Values[i] = ec._DriverLibraryInfo_libraryFiles(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var dynamicTracePropertyImplementors = []string{"DynamicTraceProperty"} + +func (ec *executionContext) _DynamicTraceProperty(ctx context.Context, sel ast.SelectionSet, obj *model.DynamicTraceProperty) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, dynamicTracePropertyImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("DynamicTraceProperty") + case "name": + out.Values[i] = ec._DynamicTraceProperty_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "value": + out.Values[i] = ec._DynamicTraceProperty_value(ctx, field, obj) + case "description": + out.Values[i] = ec._DynamicTraceProperty_description(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var federatedAuthInfoImplementors = []string{"FederatedAuthInfo"} + +func (ec *executionContext) _FederatedAuthInfo(ctx context.Context, sel ast.SelectionSet, obj *model.FederatedAuthInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, federatedAuthInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("FederatedAuthInfo") + case "redirectLink": + out.Values[i] = ec._FederatedAuthInfo_redirectLink(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "taskInfo": + out.Values[i] = ec._FederatedAuthInfo_taskInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var federatedAuthResultImplementors = []string{"FederatedAuthResult"} + +func (ec *executionContext) _FederatedAuthResult(ctx context.Context, sel ast.SelectionSet, obj *model.FederatedAuthResult) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, federatedAuthResultImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("FederatedAuthResult") + case "userTokens": + out.Values[i] = ec._FederatedAuthResult_userTokens(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39667,39 +44154,83 @@ var logEntryImplementors = []string{"LogEntry"} func (ec *executionContext) _LogEntry(ctx context.Context, sel ast.SelectionSet, obj *model.LogEntry) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, logEntryImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("LogEntry") case "time": - out.Values[i] = ec._LogEntry_time(ctx, field, obj) - case "type": - out.Values[i] = ec._LogEntry_type(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "message": - out.Values[i] = ec._LogEntry_message(ctx, field, obj) - case "stackTrace": - out.Values[i] = ec._LogEntry_stackTrace(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var logoutInfoImplementors = []string{"LogoutInfo"} +func (ec *executionContext) _LogoutInfo(ctx context.Context, sel ast.SelectionSet, obj *model.LogoutInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, logoutInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("LogoutInfo") + case "redirectLinks": + out.Values[i] = ec._LogoutInfo_redirectLinks(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -39712,7 +44243,7 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) }) out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ Object: field.Name, @@ -39722,356 +44253,461 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("Mutation") + case "adminUpdateProductConfiguration": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_adminUpdateProductConfiguration(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "setUserConfigurationParameter": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_setUserConfigurationParameter(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "setUserPreferences": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_setUserPreferences(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "federatedLogin": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_federatedLogin(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "openSession": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_openSession(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "closeSession": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_closeSession(ctx, field) }) - case "touchSession": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_touchSession(ctx, field) }) - + case "updateSession": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_updateSession(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "refreshSessionConnections": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_refreshSessionConnections(ctx, field) }) - case "changeSessionLanguage": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_changeSessionLanguage(ctx, field) }) - case "createConnection": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_createConnection(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "updateConnection": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_updateConnection(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "deleteConnection": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_deleteConnection(ctx, field) }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "createConnectionFromTemplate": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_createConnectionFromTemplate(ctx, field) - }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "createConnectionFolder": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_createConnectionFolder(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "deleteConnectionFolder": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_deleteConnectionFolder(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "copyConnectionFromNode": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_copyConnectionFromNode(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "testConnection": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_testConnection(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "testNetworkHandler": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_testNetworkHandler(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "initConnection": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_initConnection(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "closeConnection": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_closeConnection(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "setConnectionNavigatorSettings": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_setConnectionNavigatorSettings(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "asyncTaskCancel": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_asyncTaskCancel(ctx, field) }) - case "asyncTaskInfo": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_asyncTaskInfo(ctx, field) }) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "openConnection": - - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_openConnection(ctx, field) - }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "asyncTaskStatus": - + case "navReloadNode": out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._Mutation_asyncTaskStatus(ctx, field) + return ec._Mutation_navReloadNode(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "navRenameNode": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_navRenameNode(ctx, field) }) - case "navDeleteNodes": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_navDeleteNodes(ctx, field) }) - case "navMoveNodesToFolder": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_navMoveNodesToFolder(ctx, field) }) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "navSetFolderFilter": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_navSetFolderFilter(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "rmCreateResource": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_rmCreateResource(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "rmMoveResource": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_rmMoveResource(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "rmDeleteResource": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_rmDeleteResource(ctx, field) }) - case "rmWriteResourceStringContent": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_rmWriteResourceStringContent(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "rmCreateProject": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rmCreateProject(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "rmDeleteProject": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rmDeleteProject(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "rmSetProjectPermissions": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rmSetProjectPermissions(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "rmSetSubjectProjectPermissions": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rmSetSubjectProjectPermissions(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "rmAddProjectsPermissions": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rmAddProjectsPermissions(ctx, field) + }) + case "rmDeleteProjectsPermissions": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rmDeleteProjectsPermissions(ctx, field) + }) + case "rmSetResourceProperty": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_rmSetResourceProperty(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "sqlContextCreate": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_sqlContextCreate(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "sqlContextSetDefaults": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_sqlContextSetDefaults(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "sqlContextDestroy": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_sqlContextDestroy(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "asyncSqlExecuteQuery": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_asyncSqlExecuteQuery(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "asyncReadDataFromContainer": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_asyncReadDataFromContainer(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "getTransactionLogInfo": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_getTransactionLogInfo(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "sqlResultClose": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_sqlResultClose(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "asyncUpdateResultsDataBatch": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_asyncUpdateResultsDataBatch(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "updateResultsDataBatch": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_updateResultsDataBatch(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "updateResultsDataBatchScript": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_updateResultsDataBatchScript(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "readLobValue": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_readLobValue(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "sqlReadLobValue": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_sqlReadLobValue(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "sqlReadStringValue": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_sqlReadStringValue(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "asyncSqlExecuteResults": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_asyncSqlExecuteResults(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "asyncSqlExplainExecutionPlan": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_asyncSqlExplainExecutionPlan(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "asyncSqlExplainExecutionPlanResult": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Mutation_asyncSqlExplainExecutionPlanResult(ctx, field) }) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "asyncSqlRowDataCount": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_asyncSqlRowDataCount(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "asyncSqlRowDataCountResult": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_asyncSqlRowDataCountResult(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "sqlGetDynamicTrace": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_sqlGetDynamicTrace(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ } + case "asyncSqlSetAutoCommit": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_asyncSqlSetAutoCommit(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "asyncSqlCommitTransaction": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_asyncSqlCommitTransaction(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "asyncSqlRollbackTransaction": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_asyncSqlRollbackTransaction(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var navigatorNodeFilterImplementors = []string{"NavigatorNodeFilter"} + +func (ec *executionContext) _NavigatorNodeFilter(ctx context.Context, sel ast.SelectionSet, obj *model.NavigatorNodeFilter) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, navigatorNodeFilterImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("NavigatorNodeFilter") + case "include": + out.Values[i] = ec._NavigatorNodeFilter_include(ctx, field, obj) + case "exclude": + out.Values[i] = ec._NavigatorNodeFilter_exclude(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40079,75 +44715,92 @@ var navigatorNodeInfoImplementors = []string{"NavigatorNodeInfo"} func (ec *executionContext) _NavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, obj *model.NavigatorNodeInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, navigatorNodeInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("NavigatorNodeInfo") case "id": - out.Values[i] = ec._NavigatorNodeInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "uri": + out.Values[i] = ec._NavigatorNodeInfo_uri(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "name": - out.Values[i] = ec._NavigatorNodeInfo_name(ctx, field, obj) - case "fullName": - out.Values[i] = ec._NavigatorNodeInfo_fullName(ctx, field, obj) - + case "plainName": + out.Values[i] = ec._NavigatorNodeInfo_plainName(ctx, field, obj) case "icon": - out.Values[i] = ec._NavigatorNodeInfo_icon(ctx, field, obj) - case "description": - out.Values[i] = ec._NavigatorNodeInfo_description(ctx, field, obj) - case "nodeType": - out.Values[i] = ec._NavigatorNodeInfo_nodeType(ctx, field, obj) - case "hasChildren": - out.Values[i] = ec._NavigatorNodeInfo_hasChildren(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "projectId": + out.Values[i] = ec._NavigatorNodeInfo_projectId(ctx, field, obj) case "object": - out.Values[i] = ec._NavigatorNodeInfo_object(ctx, field, obj) - + case "objectId": + out.Values[i] = ec._NavigatorNodeInfo_objectId(ctx, field, obj) case "features": - out.Values[i] = ec._NavigatorNodeInfo_features(ctx, field, obj) - case "nodeDetails": - out.Values[i] = ec._NavigatorNodeInfo_nodeDetails(ctx, field, obj) - case "folder": - out.Values[i] = ec._NavigatorNodeInfo_folder(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "inline": - out.Values[i] = ec._NavigatorNodeInfo_inline(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "navigable": - out.Values[i] = ec._NavigatorNodeInfo_navigable(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "filtered": + out.Values[i] = ec._NavigatorNodeInfo_filtered(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "filter": + out.Values[i] = ec._NavigatorNodeInfo_filter(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40155,69 +44808,68 @@ var navigatorSettingsImplementors = []string{"NavigatorSettings"} func (ec *executionContext) _NavigatorSettings(ctx context.Context, sel ast.SelectionSet, obj *model.NavigatorSettings) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, navigatorSettingsImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("NavigatorSettings") case "showSystemObjects": - out.Values[i] = ec._NavigatorSettings_showSystemObjects(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "showUtilityObjects": - out.Values[i] = ec._NavigatorSettings_showUtilityObjects(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "showOnlyEntities": - out.Values[i] = ec._NavigatorSettings_showOnlyEntities(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "mergeEntities": - out.Values[i] = ec._NavigatorSettings_mergeEntities(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "hideFolders": - out.Values[i] = ec._NavigatorSettings_hideFolders(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "hideSchemas": - out.Values[i] = ec._NavigatorSettings_hideSchemas(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "hideVirtualModel": - out.Values[i] = ec._NavigatorSettings_hideVirtualModel(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40225,32 +44877,39 @@ var networkEndpointInfoImplementors = []string{"NetworkEndpointInfo"} func (ec *executionContext) _NetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, obj *model.NetworkEndpointInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, networkEndpointInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("NetworkEndpointInfo") case "message": - out.Values[i] = ec._NetworkEndpointInfo_message(ctx, field, obj) - case "clientVersion": - out.Values[i] = ec._NetworkEndpointInfo_clientVersion(ctx, field, obj) - case "serverVersion": - out.Values[i] = ec._NetworkEndpointInfo_serverVersion(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40258,67 +44917,69 @@ var networkHandlerConfigImplementors = []string{"NetworkHandlerConfig"} func (ec *executionContext) _NetworkHandlerConfig(ctx context.Context, sel ast.SelectionSet, obj *model.NetworkHandlerConfig) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, networkHandlerConfigImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("NetworkHandlerConfig") case "id": - out.Values[i] = ec._NetworkHandlerConfig_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "enabled": - out.Values[i] = ec._NetworkHandlerConfig_enabled(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "authType": - out.Values[i] = ec._NetworkHandlerConfig_authType(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "userName": - out.Values[i] = ec._NetworkHandlerConfig_userName(ctx, field, obj) - case "password": - out.Values[i] = ec._NetworkHandlerConfig_password(ctx, field, obj) - case "key": - out.Values[i] = ec._NetworkHandlerConfig_key(ctx, field, obj) - case "savePassword": - out.Values[i] = ec._NetworkHandlerConfig_savePassword(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "properties": - out.Values[i] = ec._NetworkHandlerConfig_properties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "secureProperties": + out.Values[i] = ec._NetworkHandlerConfig_secureProperties(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40326,63 +44987,62 @@ var networkHandlerDescriptorImplementors = []string{"NetworkHandlerDescriptor"} func (ec *executionContext) _NetworkHandlerDescriptor(ctx context.Context, sel ast.SelectionSet, obj *model.NetworkHandlerDescriptor) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, networkHandlerDescriptorImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("NetworkHandlerDescriptor") case "id": - out.Values[i] = ec._NetworkHandlerDescriptor_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "codeName": - out.Values[i] = ec._NetworkHandlerDescriptor_codeName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "label": - out.Values[i] = ec._NetworkHandlerDescriptor_label(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "description": - out.Values[i] = ec._NetworkHandlerDescriptor_description(ctx, field, obj) - case "secured": - out.Values[i] = ec._NetworkHandlerDescriptor_secured(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "type": - out.Values[i] = ec._NetworkHandlerDescriptor_type(ctx, field, obj) - case "properties": - out.Values[i] = ec._NetworkHandlerDescriptor_properties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40390,44 +45050,45 @@ var objectDescriptorImplementors = []string{"ObjectDescriptor"} func (ec *executionContext) _ObjectDescriptor(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectDescriptor) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, objectDescriptorImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ObjectDescriptor") case "id": - out.Values[i] = ec._ObjectDescriptor_id(ctx, field, obj) - case "displayName": - out.Values[i] = ec._ObjectDescriptor_displayName(ctx, field, obj) - case "fullName": - out.Values[i] = ec._ObjectDescriptor_fullName(ctx, field, obj) - case "uniqueName": - out.Values[i] = ec._ObjectDescriptor_uniqueName(ctx, field, obj) - case "description": - out.Values[i] = ec._ObjectDescriptor_description(ctx, field, obj) - case "value": - out.Values[i] = ec._ObjectDescriptor_value(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40435,36 +45096,41 @@ var objectDetailsImplementors = []string{"ObjectDetails"} func (ec *executionContext) _ObjectDetails(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectDetails) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, objectDetailsImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ObjectDetails") case "id": - out.Values[i] = ec._ObjectDetails_id(ctx, field, obj) - case "displayName": - out.Values[i] = ec._ObjectDetails_displayName(ctx, field, obj) - case "description": - out.Values[i] = ec._ObjectDetails_description(ctx, field, obj) - case "value": - out.Values[i] = ec._ObjectDetails_value(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40472,50 +45138,51 @@ var objectOriginImplementors = []string{"ObjectOrigin"} func (ec *executionContext) _ObjectOrigin(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectOrigin) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, objectOriginImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ObjectOrigin") case "type": - out.Values[i] = ec._ObjectOrigin_type(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "subType": - out.Values[i] = ec._ObjectOrigin_subType(ctx, field, obj) - case "displayName": - out.Values[i] = ec._ObjectOrigin_displayName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "icon": - out.Values[i] = ec._ObjectOrigin_icon(ctx, field, obj) - case "configuration": - out.Values[i] = ec._ObjectOrigin_configuration(ctx, field, obj) - case "details": - out.Values[i] = ec._ObjectOrigin_details(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40523,73 +45190,131 @@ var objectPropertyInfoImplementors = []string{"ObjectPropertyInfo"} func (ec *executionContext) _ObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ObjectPropertyInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, objectPropertyInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ObjectPropertyInfo") case "id": - out.Values[i] = ec._ObjectPropertyInfo_id(ctx, field, obj) - case "displayName": - out.Values[i] = ec._ObjectPropertyInfo_displayName(ctx, field, obj) - case "description": - out.Values[i] = ec._ObjectPropertyInfo_description(ctx, field, obj) - + case "hint": + out.Values[i] = ec._ObjectPropertyInfo_hint(ctx, field, obj) case "category": - out.Values[i] = ec._ObjectPropertyInfo_category(ctx, field, obj) - case "dataType": - out.Values[i] = ec._ObjectPropertyInfo_dataType(ctx, field, obj) - case "value": - out.Values[i] = ec._ObjectPropertyInfo_value(ctx, field, obj) - case "validValues": - out.Values[i] = ec._ObjectPropertyInfo_validValues(ctx, field, obj) - case "defaultValue": - out.Values[i] = ec._ObjectPropertyInfo_defaultValue(ctx, field, obj) - case "length": - out.Values[i] = ec._ObjectPropertyInfo_length(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "features": - out.Values[i] = ec._ObjectPropertyInfo_features(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "order": - out.Values[i] = ec._ObjectPropertyInfo_order(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "supportedConfigurationTypes": + out.Values[i] = ec._ObjectPropertyInfo_supportedConfigurationTypes(ctx, field, obj) + case "required": + out.Values[i] = ec._ObjectPropertyInfo_required(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "scopes": + out.Values[i] = ec._ObjectPropertyInfo_scopes(ctx, field, obj) + case "conditions": + out.Values[i] = ec._ObjectPropertyInfo_conditions(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} +var passwordPolicyConfigImplementors = []string{"PasswordPolicyConfig"} + +func (ec *executionContext) _PasswordPolicyConfig(ctx context.Context, sel ast.SelectionSet, obj *model.PasswordPolicyConfig) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, passwordPolicyConfigImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("PasswordPolicyConfig") + case "minLength": + out.Values[i] = ec._PasswordPolicyConfig_minLength(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "minNumberCount": + out.Values[i] = ec._PasswordPolicyConfig_minNumberCount(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "minSymbolCount": + out.Values[i] = ec._PasswordPolicyConfig_minSymbolCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "requireMixedCase": + out.Values[i] = ec._PasswordPolicyConfig_requireMixedCase(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40597,67 +45322,235 @@ var productInfoImplementors = []string{"ProductInfo"} func (ec *executionContext) _ProductInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ProductInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, productInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ProductInfo") case "id": - out.Values[i] = ec._ProductInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "version": - out.Values[i] = ec._ProductInfo_version(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._ProductInfo_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "description": - out.Values[i] = ec._ProductInfo_description(ctx, field, obj) - case "buildTime": - out.Values[i] = ec._ProductInfo_buildTime(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "releaseTime": - out.Values[i] = ec._ProductInfo_releaseTime(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "licenseInfo": - out.Values[i] = ec._ProductInfo_licenseInfo(ctx, field, obj) - case "latestVersionInfo": - out.Values[i] = ec._ProductInfo_latestVersionInfo(ctx, field, obj) + case "productPurchaseURL": + out.Values[i] = ec._ProductInfo_productPurchaseURL(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var productSettingsImplementors = []string{"ProductSettings"} + +func (ec *executionContext) _ProductSettings(ctx context.Context, sel ast.SelectionSet, obj *model.ProductSettings) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, productSettingsImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("ProductSettings") + case "groups": + out.Values[i] = ec._ProductSettings_groups(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "settings": + out.Values[i] = ec._ProductSettings_settings(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var productSettingsGroupImplementors = []string{"ProductSettingsGroup"} + +func (ec *executionContext) _ProductSettingsGroup(ctx context.Context, sel ast.SelectionSet, obj *model.ProductSettingsGroup) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, productSettingsGroupImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("ProductSettingsGroup") + case "id": + out.Values[i] = ec._ProductSettingsGroup_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "displayName": + out.Values[i] = ec._ProductSettingsGroup_displayName(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var projectInfoImplementors = []string{"ProjectInfo"} +func (ec *executionContext) _ProjectInfo(ctx context.Context, sel ast.SelectionSet, obj *model.ProjectInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, projectInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("ProjectInfo") + case "id": + out.Values[i] = ec._ProjectInfo_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "global": + out.Values[i] = ec._ProjectInfo_global(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "shared": + out.Values[i] = ec._ProjectInfo_shared(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "name": + out.Values[i] = ec._ProjectInfo_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec._ProjectInfo_description(ctx, field, obj) + case "canEditDataSources": + out.Values[i] = ec._ProjectInfo_canEditDataSources(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "canViewDataSources": + out.Values[i] = ec._ProjectInfo_canViewDataSources(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "canEditResources": + out.Values[i] = ec._ProjectInfo_canEditResources(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "canViewResources": + out.Values[i] = ec._ProjectInfo_canViewResources(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "resourceTypes": + out.Values[i] = ec._ProjectInfo_resourceTypes(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -40670,7 +45563,7 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }) out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ Object: field.Name, @@ -40680,10 +45573,32 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("Query") + case "adminUserInfo": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_adminUserInfo(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "listUsers": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -40691,45 +45606,43 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_listUsers(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listRoles": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listTeams": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_listRoles(ctx, field) + res = ec._Query_listTeams(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "listPermissions": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -40737,22 +45650,87 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_listPermissions(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listAuthRoles": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_listAuthRoles(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listTeamRoles": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_listTeamRoles(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listTeamMetaParameters": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_listTeamMetaParameters(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "createUser": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -40760,22 +45738,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_createUser(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "deleteUser": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -40786,1311 +45763,1501 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "createRole": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "createTeam": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_createRole(ctx, field) + res = ec._Query_createTeam(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "updateRole": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "updateTeam": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_updateRole(ctx, field) + res = ec._Query_updateTeam(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteRole": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "deleteTeam": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_deleteRole(ctx, field) + res = ec._Query_deleteTeam(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "grantUserRole": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "grantUserTeam": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_grantUserRole(ctx, field) + res = ec._Query_grantUserTeam(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "revokeUserRole": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "revokeUserTeam": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_revokeUserRole(ctx, field) + res = ec._Query_revokeUserTeam(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "setSubjectPermissions": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_setSubjectPermissions(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setUserCredentials": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_setUserCredentials(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "deleteUserCredentials": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_deleteUserCredentials(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "enableUser": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_enableUser(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setUserAuthRole": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_setUserAuthRole(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setUserTeamRole": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_setUserTeamRole(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "searchConnections": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_searchConnections(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "getConnectionSubjectAccess": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_getConnectionSubjectAccess(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setConnectionSubjectAccess": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_setConnectionSubjectAccess(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "addConnectionsAccess": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_addConnectionsAccess(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "deleteConnectionsAccess": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_deleteConnectionsAccess(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "getSubjectConnectionAccess": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_getSubjectConnectionAccess(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setSubjectConnectionAccess": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_setSubjectPermissions(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } + res = ec._Query_setSubjectConnectionAccess(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setUserCredentials": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listFeatureSets": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_setUserCredentials(ctx, field) + res = ec._Query_listFeatureSets(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "enableUser": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listAuthProviderConfigurationParameters": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_enableUser(ctx, field) + res = ec._Query_listAuthProviderConfigurationParameters(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "allConnections": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listAuthProviderConfigurations": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_allConnections(ctx, field) + res = ec._Query_listAuthProviderConfigurations(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "searchConnections": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "saveAuthProviderConfiguration": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_searchConnections(ctx, field) + res = ec._Query_saveAuthProviderConfiguration(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "createConnectionConfiguration": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "deleteAuthProviderConfiguration": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_createConnectionConfiguration(ctx, field) + res = ec._Query_deleteAuthProviderConfiguration(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "copyConnectionConfiguration": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "saveUserMetaParameter": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_copyConnectionConfiguration(ctx, field) + res = ec._Query_saveUserMetaParameter(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "updateConnectionConfiguration": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "deleteUserMetaParameter": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_updateConnectionConfiguration(ctx, field) + res = ec._Query_deleteUserMetaParameter(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteConnectionConfiguration": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setUserMetaParameterValues": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_deleteConnectionConfiguration(ctx, field) + res = ec._Query_setUserMetaParameterValues(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "getConnectionSubjectAccess": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setTeamMetaParameterValues": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_getConnectionSubjectAccess(ctx, field) + res = ec._Query_setTeamMetaParameterValues(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setConnectionSubjectAccess": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "configureServer": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_setConnectionSubjectAccess(ctx, field) + res = ec._Query_configureServer(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "getSubjectConnectionAccess": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "setDefaultNavigatorSettings": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_getSubjectConnectionAccess(ctx, field) + res = ec._Query_setDefaultNavigatorSettings(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setSubjectConnectionAccess": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "authLogin": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_setSubjectConnectionAccess(ctx, field) + res = ec._Query_authLogin(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listFeatureSets": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "federatedAuthTaskResult": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_listFeatureSets(ctx, field) + res = ec._Query_federatedAuthTaskResult(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listAuthProviderConfigurationParameters": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "authUpdateStatus": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_listAuthProviderConfigurationParameters(ctx, field) + res = ec._Query_authUpdateStatus(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listAuthProviderConfigurations": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "authLogout": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_listAuthProviderConfigurations(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } + res = ec._Query_authLogout(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "saveAuthProviderConfiguration": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "authLogoutExtended": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_saveAuthProviderConfiguration(ctx, field) + res = ec._Query_authLogoutExtended(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteAuthProviderConfiguration": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "activeUser": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_deleteAuthProviderConfiguration(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } + res = ec._Query_activeUser(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "saveUserMetaParameter": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "authProviders": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_saveUserMetaParameter(ctx, field) + res = ec._Query_authProviders(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "deleteUserMetaParameter": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "authChangeLocalPassword": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_deleteUserMetaParameter(ctx, field) + res = ec._Query_authChangeLocalPassword(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setUserMetaParameterValues": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listUserProfileProperties": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_setUserMetaParameterValues(ctx, field) + res = ec._Query_listUserProfileProperties(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "configureServer": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "serverConfig": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_configureServer(ctx, field) + res = ec._Query_serverConfig(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "setDefaultNavigatorSettings": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "systemInfo": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_setDefaultNavigatorSettings(ctx, field) + res = ec._Query_systemInfo(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authLogin": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "productSettings": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_authLogin(ctx, field) + res = ec._Query_productSettings(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authUpdateStatus": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "sessionState": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_authUpdateStatus(ctx, field) + res = ec._Query_sessionState(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authLogout": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "sessionPermissions": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_authLogout(ctx, field) + res = ec._Query_sessionPermissions(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "activeUser": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "driverList": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_activeUser(ctx, field) + res = ec._Query_driverList(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authProviders": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "authModels": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_authProviders(ctx, field) + res = ec._Query_authModels(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authChangeLocalPassword": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "networkHandlers": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_authChangeLocalPassword(ctx, field) + res = ec._Query_networkHandlers(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "listUserProfileProperties": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "userConnections": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_listUserProfileProperties(ctx, field) + res = ec._Query_userConnections(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "serverConfig": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "connectionFolders": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_serverConfig(ctx, field) + res = ec._Query_connectionFolders(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sessionState": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "connectionInfo": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_sessionState(ctx, field) + res = ec._Query_connectionInfo(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "sessionPermissions": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "listProjects": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_sessionPermissions(ctx, field) + res = ec._Query_listProjects(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "driverList": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "readSessionLog": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_driverList(ctx, field) + res = ec._Query_readSessionLog(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "authModels": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "dataTransferAvailableStreamProcessors": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_authModels(ctx, field) + res = ec._Query_dataTransferAvailableStreamProcessors(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "networkHandlers": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "dataTransferAvailableImportStreamProcessors": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_networkHandlers(ctx, field) + res = ec._Query_dataTransferAvailableImportStreamProcessors(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "userConnections": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "dataTransferDefaultExportSettings": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_userConnections(ctx, field) + res = ec._Query_dataTransferDefaultExportSettings(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "templateConnections": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "dataTransferExportDataFromContainer": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_templateConnections(ctx, field) + res = ec._Query_dataTransferExportDataFromContainer(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "connectionFolders": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "dataTransferExportDataFromResults": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_connectionFolders(ctx, field) + res = ec._Query_dataTransferExportDataFromResults(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "connectionState": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "dataTransferRemoveDataFile": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_connectionState(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } + res = ec._Query_dataTransferRemoveDataFile(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "connectionInfo": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "metadataGetNodeDDL": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_connectionInfo(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } + res = ec._Query_metadataGetNodeDDL(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "readSessionLog": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "metadataGetNodeExtendedDDL": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_readSessionLog(ctx, field) - if res == graphql.Null { - atomic.AddUint32(&invalids, 1) - } + res = ec._Query_metadataGetNodeExtendedDDL(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferAvailableStreamProcessors": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "navNodeChildren": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_dataTransferAvailableStreamProcessors(ctx, field) + res = ec._Query_navNodeChildren(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferExportDataFromContainer": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "navNodeParents": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_dataTransferExportDataFromContainer(ctx, field) + res = ec._Query_navNodeParents(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferExportDataFromResults": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "navNodeInfo": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_dataTransferExportDataFromResults(ctx, field) + res = ec._Query_navNodeInfo(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "dataTransferRemoveDataFile": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "navRefreshNode": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_dataTransferRemoveDataFile(ctx, field) + res = ec._Query_navRefreshNode(ctx, field) return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "metadataGetNodeDDL": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "navGetStructContainers": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_metadataGetNodeDDL(ctx, field) + res = ec._Query_navGetStructContainers(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navNodeChildren": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "rmListProjects": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_navNodeChildren(ctx, field) + res = ec._Query_rmListProjects(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navNodeParents": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "rmListSharedProjects": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_navNodeParents(ctx, field) + res = ec._Query_rmListSharedProjects(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navNodeInfo": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "rmProject": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_navNodeInfo(ctx, field) + res = ec._Query_rmProject(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navRefreshNode": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "rmListProjectPermissions": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_navRefreshNode(ctx, field) + res = ec._Query_rmListProjectPermissions(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "navGetStructContainers": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "rmListProjectGrantedPermissions": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_navGetStructContainers(ctx, field) + res = ec._Query_rmListProjectGrantedPermissions(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "rmListProjects": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "rmListSubjectProjectsPermissionGrants": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) } }() - res = ec._Query_rmListProjects(ctx, field) + res = ec._Query_rmListSubjectProjectsPermissionGrants(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "rmListResources": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42098,22 +47265,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_rmListResources(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "rmReadResourceAsString": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42121,22 +47287,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_rmReadResourceAsString(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlDialectInfo": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42147,16 +47312,15 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlListContexts": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42164,22 +47328,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_sqlListContexts(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlCompletionProposals": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42190,16 +47353,15 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlFormatQuery": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42207,22 +47369,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_sqlFormatQuery(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlSupportedOperations": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42230,22 +47391,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_sqlSupportedOperations(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlEntityQueryGenerators": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42253,22 +47413,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_sqlEntityQueryGenerators(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlGenerateEntityQuery": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42276,22 +47435,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_sqlGenerateEntityQuery(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlParseScript": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42299,22 +47457,21 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_sqlParseScript(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "sqlParseQuery": field := field - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) @@ -42322,38 +47479,67 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr }() res = ec._Query_sqlParseQuery(ctx, field) if res == graphql.Null { - atomic.AddUint32(&invalids, 1) + atomic.AddUint32(&fs.Invalids, 1) } return res } rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } - out.Concurrently(i, func() graphql.Marshaler { - return rrm(innerCtx) - }) - case "__type": + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "sqlGenerateGroupingQuery": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_sqlGenerateGroupingQuery(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "__type": out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Query___type(ctx, field) }) - case "__schema": - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { return ec._Query___schema(ctx, field) }) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42361,59 +47547,75 @@ var rMProjectImplementors = []string{"RMProject"} func (ec *executionContext) _RMProject(ctx context.Context, sel ast.SelectionSet, obj *model.RMProject) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, rMProjectImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("RMProject") case "id": - out.Values[i] = ec._RMProject_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._RMProject_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "description": - out.Values[i] = ec._RMProject_description(ctx, field, obj) - case "shared": - out.Values[i] = ec._RMProject_shared(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "global": + out.Values[i] = ec._RMProject_global(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "createTime": - out.Values[i] = ec._RMProject_createTime(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "creator": - out.Values[i] = ec._RMProject_creator(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "projectPermissions": + out.Values[i] = ec._RMProject_projectPermissions(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "resourceTypes": + out.Values[i] = ec._RMProject_resourceTypes(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42421,41 +47623,103 @@ var rMResourceImplementors = []string{"RMResource"} func (ec *executionContext) _RMResource(ctx context.Context, sel ast.SelectionSet, obj *model.RMResource) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, rMResourceImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("RMResource") case "name": - out.Values[i] = ec._RMResource_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "folder": - out.Values[i] = ec._RMResource_folder(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "length": - out.Values[i] = ec._RMResource_length(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "properties": + out.Values[i] = ec._RMResource_properties(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var rMResourceTypeImplementors = []string{"RMResourceType"} + +func (ec *executionContext) _RMResourceType(ctx context.Context, sel ast.SelectionSet, obj *model.RMResourceType) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, rMResourceTypeImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("RMResourceType") + case "id": + out.Values[i] = ec._RMResourceType_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "displayName": + out.Values[i] = ec._RMResourceType_displayName(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "icon": + out.Values[i] = ec._RMResourceType_icon(ctx, field, obj) + case "fileExtensions": + out.Values[i] = ec._RMResourceType_fileExtensions(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "rootFolder": + out.Values[i] = ec._RMResourceType_rootFolder(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42463,71 +47727,66 @@ var sQLCompletionProposalImplementors = []string{"SQLCompletionProposal"} func (ec *executionContext) _SQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, obj *model.SQLCompletionProposal) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLCompletionProposalImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLCompletionProposal") case "displayString": - out.Values[i] = ec._SQLCompletionProposal_displayString(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "type": - out.Values[i] = ec._SQLCompletionProposal_type(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "score": - out.Values[i] = ec._SQLCompletionProposal_score(ctx, field, obj) - case "replacementString": - out.Values[i] = ec._SQLCompletionProposal_replacementString(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "replacementOffset": - out.Values[i] = ec._SQLCompletionProposal_replacementOffset(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "replacementLength": - out.Values[i] = ec._SQLCompletionProposal_replacementLength(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "cursorPosition": - out.Values[i] = ec._SQLCompletionProposal_cursorPosition(ctx, field, obj) - case "icon": - out.Values[i] = ec._SQLCompletionProposal_icon(ctx, field, obj) - case "nodePath": - out.Values[i] = ec._SQLCompletionProposal_nodePath(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42535,42 +47794,54 @@ var sQLContextInfoImplementors = []string{"SQLContextInfo"} func (ec *executionContext) _SQLContextInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLContextInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLContextInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLContextInfo") case "id": - out.Values[i] = ec._SQLContextInfo_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "projectId": + out.Values[i] = ec._SQLContextInfo_projectId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "connectionId": - out.Values[i] = ec._SQLContextInfo_connectionId(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "autoCommit": + out.Values[i] = ec._SQLContextInfo_autoCommit(ctx, field, obj) case "defaultCatalog": - out.Values[i] = ec._SQLContextInfo_defaultCatalog(ctx, field, obj) - case "defaultSchema": - out.Values[i] = ec._SQLContextInfo_defaultSchema(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42578,88 +47849,79 @@ var sQLDialectInfoImplementors = []string{"SQLDialectInfo"} func (ec *executionContext) _SQLDialectInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLDialectInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLDialectInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLDialectInfo") case "name": - out.Values[i] = ec._SQLDialectInfo_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "dataTypes": - out.Values[i] = ec._SQLDialectInfo_dataTypes(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "functions": - out.Values[i] = ec._SQLDialectInfo_functions(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "reservedWords": - out.Values[i] = ec._SQLDialectInfo_reservedWords(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "quoteStrings": - out.Values[i] = ec._SQLDialectInfo_quoteStrings(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "singleLineComments": - out.Values[i] = ec._SQLDialectInfo_singleLineComments(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "multiLineComments": - out.Values[i] = ec._SQLDialectInfo_multiLineComments(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "catalogSeparator": - out.Values[i] = ec._SQLDialectInfo_catalogSeparator(ctx, field, obj) - case "structSeparator": - out.Values[i] = ec._SQLDialectInfo_structSeparator(ctx, field, obj) - case "scriptDelimiter": - out.Values[i] = ec._SQLDialectInfo_scriptDelimiter(ctx, field, obj) - case "supportsExplainExecutionPlan": - out.Values[i] = ec._SQLDialectInfo_supportsExplainExecutionPlan(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42667,42 +47929,49 @@ var sQLExecuteInfoImplementors = []string{"SQLExecuteInfo"} func (ec *executionContext) _SQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLExecuteInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLExecuteInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLExecuteInfo") case "statusMessage": - out.Values[i] = ec._SQLExecuteInfo_statusMessage(ctx, field, obj) - case "duration": - out.Values[i] = ec._SQLExecuteInfo_duration(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "filterText": - out.Values[i] = ec._SQLExecuteInfo_filterText(ctx, field, obj) - + case "fullQuery": + out.Values[i] = ec._SQLExecuteInfo_fullQuery(ctx, field, obj) case "results": - out.Values[i] = ec._SQLExecuteInfo_results(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42710,34 +47979,43 @@ var sQLExecutionPlanImplementors = []string{"SQLExecutionPlan"} func (ec *executionContext) _SQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, obj *model.SQLExecutionPlan) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLExecutionPlanImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLExecutionPlan") case "query": - out.Values[i] = ec._SQLExecutionPlan_query(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "nodes": - out.Values[i] = ec._SQLExecutionPlan_nodes(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42745,64 +48023,61 @@ var sQLExecutionPlanNodeImplementors = []string{"SQLExecutionPlanNode"} func (ec *executionContext) _SQLExecutionPlanNode(ctx context.Context, sel ast.SelectionSet, obj *model.SQLExecutionPlanNode) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLExecutionPlanNodeImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLExecutionPlanNode") case "id": - out.Values[i] = ec._SQLExecutionPlanNode_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "parentId": - out.Values[i] = ec._SQLExecutionPlanNode_parentId(ctx, field, obj) - case "kind": - out.Values[i] = ec._SQLExecutionPlanNode_kind(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._SQLExecutionPlanNode_name(ctx, field, obj) - case "type": - out.Values[i] = ec._SQLExecutionPlanNode_type(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "condition": - out.Values[i] = ec._SQLExecutionPlanNode_condition(ctx, field, obj) - case "description": - out.Values[i] = ec._SQLExecutionPlanNode_description(ctx, field, obj) - case "properties": - out.Values[i] = ec._SQLExecutionPlanNode_properties(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42810,52 +48085,55 @@ var sQLQueryGeneratorImplementors = []string{"SQLQueryGenerator"} func (ec *executionContext) _SQLQueryGenerator(ctx context.Context, sel ast.SelectionSet, obj *model.SQLQueryGenerator) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLQueryGeneratorImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLQueryGenerator") case "id": - out.Values[i] = ec._SQLQueryGenerator_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "label": - out.Values[i] = ec._SQLQueryGenerator_label(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "description": - out.Values[i] = ec._SQLQueryGenerator_description(ctx, field, obj) - case "order": - out.Values[i] = ec._SQLQueryGenerator_order(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "multiObject": - out.Values[i] = ec._SQLQueryGenerator_multiObject(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42863,40 +48141,43 @@ var sQLQueryResultsImplementors = []string{"SQLQueryResults"} func (ec *executionContext) _SQLQueryResults(ctx context.Context, sel ast.SelectionSet, obj *model.SQLQueryResults) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLQueryResultsImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLQueryResults") case "title": - out.Values[i] = ec._SQLQueryResults_title(ctx, field, obj) - case "updateRowCount": - out.Values[i] = ec._SQLQueryResults_updateRowCount(ctx, field, obj) - case "sourceQuery": - out.Values[i] = ec._SQLQueryResults_sourceQuery(ctx, field, obj) - case "dataFormat": - out.Values[i] = ec._SQLQueryResults_dataFormat(ctx, field, obj) - case "resultSet": - out.Values[i] = ec._SQLQueryResults_resultSet(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42904,92 +48185,123 @@ var sQLResultColumnImplementors = []string{"SQLResultColumn"} func (ec *executionContext) _SQLResultColumn(ctx context.Context, sel ast.SelectionSet, obj *model.SQLResultColumn) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLResultColumnImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLResultColumn") case "position": - out.Values[i] = ec._SQLResultColumn_position(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "name": - out.Values[i] = ec._SQLResultColumn_name(ctx, field, obj) - case "label": - out.Values[i] = ec._SQLResultColumn_label(ctx, field, obj) - case "icon": - out.Values[i] = ec._SQLResultColumn_icon(ctx, field, obj) - case "entityName": - out.Values[i] = ec._SQLResultColumn_entityName(ctx, field, obj) - case "dataKind": - out.Values[i] = ec._SQLResultColumn_dataKind(ctx, field, obj) - case "typeName": - out.Values[i] = ec._SQLResultColumn_typeName(ctx, field, obj) - case "fullTypeName": - out.Values[i] = ec._SQLResultColumn_fullTypeName(ctx, field, obj) - case "maxLength": - out.Values[i] = ec._SQLResultColumn_maxLength(ctx, field, obj) - case "scale": - out.Values[i] = ec._SQLResultColumn_scale(ctx, field, obj) - case "precision": - out.Values[i] = ec._SQLResultColumn_precision(ctx, field, obj) - case "required": - out.Values[i] = ec._SQLResultColumn_required(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "autoGenerated": + out.Values[i] = ec._SQLResultColumn_autoGenerated(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } case "readOnly": - out.Values[i] = ec._SQLResultColumn_readOnly(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "readOnlyStatus": - out.Values[i] = ec._SQLResultColumn_readOnlyStatus(ctx, field, obj) - case "supportedOperations": - out.Values[i] = ec._SQLResultColumn_supportedOperations(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec._SQLResultColumn_description(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var sQLResultRowMetaDataImplementors = []string{"SQLResultRowMetaData"} + +func (ec *executionContext) _SQLResultRowMetaData(ctx context.Context, sel ast.SelectionSet, obj *model.SQLResultRowMetaData) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, sQLResultRowMetaDataImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("SQLResultRowMetaData") + case "data": + out.Values[i] = ec._SQLResultRowMetaData_data(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "metaData": + out.Values[i] = ec._SQLResultRowMetaData_metaData(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -42997,56 +48309,81 @@ var sQLResultSetImplementors = []string{"SQLResultSet"} func (ec *executionContext) _SQLResultSet(ctx context.Context, sel ast.SelectionSet, obj *model.SQLResultSet) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLResultSetImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLResultSet") case "id": - out.Values[i] = ec._SQLResultSet_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "columns": - out.Values[i] = ec._SQLResultSet_columns(ctx, field, obj) - case "rows": - out.Values[i] = ec._SQLResultSet_rows(ctx, field, obj) - + case "rowsWithMetaData": + out.Values[i] = ec._SQLResultSet_rowsWithMetaData(ctx, field, obj) case "singleEntity": - out.Values[i] = ec._SQLResultSet_singleEntity(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "hasMoreData": - out.Values[i] = ec._SQLResultSet_hasMoreData(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "hasRowIdentifier": - out.Values[i] = ec._SQLResultSet_hasRowIdentifier(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "hasChildrenCollection": + out.Values[i] = ec._SQLResultSet_hasChildrenCollection(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "hasDynamicTrace": + out.Values[i] = ec._SQLResultSet_hasDynamicTrace(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "isSupportsDataFilter": + out.Values[i] = ec._SQLResultSet_isSupportsDataFilter(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "readOnly": + out.Values[i] = ec._SQLResultSet_readOnly(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } + case "readOnlyStatus": + out.Values[i] = ec._SQLResultSet_readOnlyStatus(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -43054,27 +48391,38 @@ var sQLScriptInfoImplementors = []string{"SQLScriptInfo"} func (ec *executionContext) _SQLScriptInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SQLScriptInfo) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLScriptInfoImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLScriptInfo") case "queries": - out.Values[i] = ec._SQLScriptInfo_queries(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -43082,34 +48430,87 @@ var sQLScriptQueryImplementors = []string{"SQLScriptQuery"} func (ec *executionContext) _SQLScriptQuery(ctx context.Context, sel ast.SelectionSet, obj *model.SQLScriptQuery) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, sQLScriptQueryImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("SQLScriptQuery") case "start": - out.Values[i] = ec._SQLScriptQuery_start(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "end": - out.Values[i] = ec._SQLScriptQuery_end(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var secretInfoImplementors = []string{"SecretInfo"} +func (ec *executionContext) _SecretInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SecretInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, secretInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("SecretInfo") + case "displayName": + out.Values[i] = ec._SecretInfo_displayName(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ + } + case "secretId": + out.Values[i] = ec._SecretInfo_secretId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -43117,188 +48518,144 @@ var serverConfigImplementors = []string{"ServerConfig"} func (ec *executionContext) _ServerConfig(ctx context.Context, sel ast.SelectionSet, obj *model.ServerConfig) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, serverConfigImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ServerConfig") case "name": - out.Values[i] = ec._ServerConfig_name(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "version": - out.Values[i] = ec._ServerConfig_version(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "workspaceId": - out.Values[i] = ec._ServerConfig_workspaceId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "serverURL": - - out.Values[i] = ec._ServerConfig_serverURL(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "rootURI": - - out.Values[i] = ec._ServerConfig_rootURI(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "hostName": - - out.Values[i] = ec._ServerConfig_hostName(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "anonymousAccessEnabled": - out.Values[i] = ec._ServerConfig_anonymousAccessEnabled(ctx, field, obj) - - case "authenticationEnabled": - - out.Values[i] = ec._ServerConfig_authenticationEnabled(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "supportsCustomConnections": - out.Values[i] = ec._ServerConfig_supportsCustomConnections(ctx, field, obj) - - case "supportsConnectionBrowser": - - out.Values[i] = ec._ServerConfig_supportsConnectionBrowser(ctx, field, obj) - - case "supportsWorkspaces": - - out.Values[i] = ec._ServerConfig_supportsWorkspaces(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "resourceManagerEnabled": - out.Values[i] = ec._ServerConfig_resourceManagerEnabled(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "secretManagerEnabled": + out.Values[i] = ec._ServerConfig_secretManagerEnabled(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "publicCredentialsSaveEnabled": - out.Values[i] = ec._ServerConfig_publicCredentialsSaveEnabled(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "adminCredentialsSaveEnabled": - out.Values[i] = ec._ServerConfig_adminCredentialsSaveEnabled(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "licenseRequired": - out.Values[i] = ec._ServerConfig_licenseRequired(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "licenseValid": - out.Values[i] = ec._ServerConfig_licenseValid(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "sessionExpireTime": - - out.Values[i] = ec._ServerConfig_sessionExpireTime(ctx, field, obj) - - case "localHostAddress": - - out.Values[i] = ec._ServerConfig_localHostAddress(ctx, field, obj) - + case "licenseStatus": + out.Values[i] = ec._ServerConfig_licenseStatus(ctx, field, obj) case "configurationMode": - out.Values[i] = ec._ServerConfig_configurationMode(ctx, field, obj) - + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "developmentMode": - out.Values[i] = ec._ServerConfig_developmentMode(ctx, field, obj) - - case "redirectOnFederatedAuth": - - out.Values[i] = ec._ServerConfig_redirectOnFederatedAuth(ctx, field, obj) - - case "enabledFeatures": - - out.Values[i] = ec._ServerConfig_enabledFeatures(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "enabledAuthProviders": - - out.Values[i] = ec._ServerConfig_enabledAuthProviders(ctx, field, obj) - + case "distributed": + out.Values[i] = ec._ServerConfig_distributed(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "enabledFeatures": + out.Values[i] = ec._ServerConfig_enabledFeatures(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "disabledBetaFeatures": + out.Values[i] = ec._ServerConfig_disabledBetaFeatures(ctx, field, obj) + case "serverFeatures": + out.Values[i] = ec._ServerConfig_serverFeatures(ctx, field, obj) case "supportedLanguages": - out.Values[i] = ec._ServerConfig_supportedLanguages(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "services": - - out.Values[i] = ec._ServerConfig_services(ctx, field, obj) - case "productConfiguration": - out.Values[i] = ec._ServerConfig_productConfiguration(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "productInfo": - out.Values[i] = ec._ServerConfig_productInfo(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "defaultNavigatorSettings": - out.Values[i] = ec._ServerConfig_defaultNavigatorSettings(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "disabledDrivers": - out.Values[i] = ec._ServerConfig_disabledDrivers(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "resourceQuotas": - out.Values[i] = ec._ServerConfig_resourceQuotas(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -43306,40 +48663,43 @@ var serverErrorImplementors = []string{"ServerError"} func (ec *executionContext) _ServerError(ctx context.Context, sel ast.SelectionSet, obj *model.ServerError) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, serverErrorImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ServerError") case "message": - out.Values[i] = ec._ServerError_message(ctx, field, obj) - case "errorCode": - out.Values[i] = ec._ServerError_errorCode(ctx, field, obj) - case "errorType": - out.Values[i] = ec._ServerError_errorType(ctx, field, obj) - case "stackTrace": - out.Values[i] = ec._ServerError_stackTrace(ctx, field, obj) - case "causedBy": - out.Values[i] = ec._ServerError_causedBy(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -43347,35 +48707,42 @@ var serverLanguageImplementors = []string{"ServerLanguage"} func (ec *executionContext) _ServerLanguage(ctx context.Context, sel ast.SelectionSet, obj *model.ServerLanguage) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, serverLanguageImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ServerLanguage") case "isoCode": - out.Values[i] = ec._ServerLanguage_isoCode(ctx, field, obj) - if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } case "displayName": - out.Values[i] = ec._ServerLanguage_displayName(ctx, field, obj) - case "nativeName": - out.Values[i] = ec._ServerLanguage_nativeName(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } @@ -43383,641 +48750,1410 @@ var serverMessageImplementors = []string{"ServerMessage"} func (ec *executionContext) _ServerMessage(ctx context.Context, sel ast.SelectionSet, obj *model.ServerMessage) graphql.Marshaler { fields := graphql.CollectFields(ec.OperationContext, sel, serverMessageImplementors) + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": out.Values[i] = graphql.MarshalString("ServerMessage") case "time": - out.Values[i] = ec._ServerMessage_time(ctx, field, obj) + case "message": + out.Values[i] = ec._ServerMessage_message(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} +var sessionInfoImplementors = []string{"SessionInfo"} + +func (ec *executionContext) _SessionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SessionInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, sessionInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("SessionInfo") + case "createTime": + out.Values[i] = ec._SessionInfo_createTime(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "lastAccessTime": + out.Values[i] = ec._SessionInfo_lastAccessTime(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "locale": + out.Values[i] = ec._SessionInfo_locale(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "cacheExpired": + out.Values[i] = ec._SessionInfo_cacheExpired(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "connections": + out.Values[i] = ec._SessionInfo_connections(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "actionParameters": + out.Values[i] = ec._SessionInfo_actionParameters(ctx, field, obj) + case "valid": + out.Values[i] = ec._SessionInfo_valid(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "remainingTime": + out.Values[i] = ec._SessionInfo_remainingTime(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var transactionLogInfoItemImplementors = []string{"TransactionLogInfoItem"} + +func (ec *executionContext) _TransactionLogInfoItem(ctx context.Context, sel ast.SelectionSet, obj *model.TransactionLogInfoItem) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, transactionLogInfoItemImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("TransactionLogInfoItem") + case "id": + out.Values[i] = ec._TransactionLogInfoItem_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "time": + out.Values[i] = ec._TransactionLogInfoItem_time(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "type": + out.Values[i] = ec._TransactionLogInfoItem_type(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "queryString": + out.Values[i] = ec._TransactionLogInfoItem_queryString(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "durationMs": + out.Values[i] = ec._TransactionLogInfoItem_durationMs(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "rows": + out.Values[i] = ec._TransactionLogInfoItem_rows(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "result": + out.Values[i] = ec._TransactionLogInfoItem_result(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var transactionLogInfosImplementors = []string{"TransactionLogInfos"} + +func (ec *executionContext) _TransactionLogInfos(ctx context.Context, sel ast.SelectionSet, obj *model.TransactionLogInfos) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, transactionLogInfosImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("TransactionLogInfos") + case "count": + out.Values[i] = ec._TransactionLogInfos_count(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "transactionLogInfos": + out.Values[i] = ec._TransactionLogInfos_transactionLogInfos(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var userAuthTokenImplementors = []string{"UserAuthToken"} + +func (ec *executionContext) _UserAuthToken(ctx context.Context, sel ast.SelectionSet, obj *model.UserAuthToken) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, userAuthTokenImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("UserAuthToken") + case "authProvider": + out.Values[i] = ec._UserAuthToken_authProvider(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "authConfiguration": + out.Values[i] = ec._UserAuthToken_authConfiguration(ctx, field, obj) + case "loginTime": + out.Values[i] = ec._UserAuthToken_loginTime(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "userId": + out.Values[i] = ec._UserAuthToken_userId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "displayName": + out.Values[i] = ec._UserAuthToken_displayName(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } case "message": + out.Values[i] = ec._UserAuthToken_message(ctx, field, obj) + case "origin": + out.Values[i] = ec._UserAuthToken_origin(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } - out.Values[i] = ec._ServerMessage_message(ctx, field, obj) + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var userInfoImplementors = []string{"UserInfo"} + +func (ec *executionContext) _UserInfo(ctx context.Context, sel ast.SelectionSet, obj *model.UserInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, userInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("UserInfo") + case "userId": + out.Values[i] = ec._UserInfo_userId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "displayName": + out.Values[i] = ec._UserInfo_displayName(ctx, field, obj) + case "authRole": + out.Values[i] = ec._UserInfo_authRole(ctx, field, obj) + case "authTokens": + out.Values[i] = ec._UserInfo_authTokens(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "linkedAuthProviders": + out.Values[i] = ec._UserInfo_linkedAuthProviders(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "metaParameters": + out.Values[i] = ec._UserInfo_metaParameters(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "configurationParameters": + out.Values[i] = ec._UserInfo_configurationParameters(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "teams": + out.Values[i] = ec._UserInfo_teams(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "isAnonymous": + out.Values[i] = ec._UserInfo_isAnonymous(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var userTeamInfoImplementors = []string{"UserTeamInfo"} + +func (ec *executionContext) _UserTeamInfo(ctx context.Context, sel ast.SelectionSet, obj *model.UserTeamInfo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, userTeamInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("UserTeamInfo") + case "teamId": + out.Values[i] = ec._UserTeamInfo_teamId(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "teamName": + out.Values[i] = ec._UserTeamInfo_teamName(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "teamRole": + out.Values[i] = ec._UserTeamInfo_teamRole(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var webFeatureSetImplementors = []string{"WebFeatureSet"} + +func (ec *executionContext) _WebFeatureSet(ctx context.Context, sel ast.SelectionSet, obj *model.WebFeatureSet) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, webFeatureSetImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("WebFeatureSet") + case "id": + out.Values[i] = ec._WebFeatureSet_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "label": + out.Values[i] = ec._WebFeatureSet_label(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec._WebFeatureSet_description(ctx, field, obj) + case "icon": + out.Values[i] = ec._WebFeatureSet_icon(ctx, field, obj) + case "enabled": + out.Values[i] = ec._WebFeatureSet_enabled(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } -var sessionInfoImplementors = []string{"SessionInfo"} +var __DirectiveImplementors = []string{"__Directive"} + +func (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __DirectiveImplementors) -func (ec *executionContext) _SessionInfo(ctx context.Context, sel ast.SelectionSet, obj *model.SessionInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, sessionInfoImplementors) out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": - out.Values[i] = graphql.MarshalString("SessionInfo") - case "createTime": - - out.Values[i] = ec._SessionInfo_createTime(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "lastAccessTime": - - out.Values[i] = ec._SessionInfo_lastAccessTime(ctx, field, obj) - + out.Values[i] = graphql.MarshalString("__Directive") + case "name": + out.Values[i] = ec.___Directive_name(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "locale": - - out.Values[i] = ec._SessionInfo_locale(ctx, field, obj) - + case "description": + out.Values[i] = ec.___Directive_description(ctx, field, obj) + case "isRepeatable": + out.Values[i] = ec.___Directive_isRepeatable(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "cacheExpired": - - out.Values[i] = ec._SessionInfo_cacheExpired(ctx, field, obj) - + case "locations": + out.Values[i] = ec.___Directive_locations(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "serverMessages": - - out.Values[i] = ec._SessionInfo_serverMessages(ctx, field, obj) - - case "connections": - - out.Values[i] = ec._SessionInfo_connections(ctx, field, obj) - + case "args": + out.Values[i] = ec.___Directive_args(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "actionParameters": - - out.Values[i] = ec._SessionInfo_actionParameters(ctx, field, obj) - default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } -var userAuthTokenImplementors = []string{"UserAuthToken"} +var __EnumValueImplementors = []string{"__EnumValue"} + +func (ec *executionContext) ___EnumValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.EnumValue) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __EnumValueImplementors) -func (ec *executionContext) _UserAuthToken(ctx context.Context, sel ast.SelectionSet, obj *model.UserAuthToken) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, userAuthTokenImplementors) out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": - out.Values[i] = graphql.MarshalString("UserAuthToken") - case "authProvider": - - out.Values[i] = ec._UserAuthToken_authProvider(ctx, field, obj) - + out.Values[i] = graphql.MarshalString("__EnumValue") + case "name": + out.Values[i] = ec.___EnumValue_name(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "authConfiguration": + case "description": + out.Values[i] = ec.___EnumValue_description(ctx, field, obj) + case "isDeprecated": + out.Values[i] = ec.___EnumValue_isDeprecated(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "deprecationReason": + out.Values[i] = ec.___EnumValue_deprecationReason(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } - out.Values[i] = ec._UserAuthToken_authConfiguration(ctx, field, obj) + atomic.AddInt32(&ec.deferred, int32(len(deferred))) - case "loginTime": + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } - out.Values[i] = ec._UserAuthToken_loginTime(ctx, field, obj) + return out +} - if out.Values[i] == graphql.Null { - invalids++ - } - case "userId": +var __FieldImplementors = []string{"__Field"} - out.Values[i] = ec._UserAuthToken_userId(ctx, field, obj) +func (ec *executionContext) ___Field(ctx context.Context, sel ast.SelectionSet, obj *introspection.Field) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __FieldImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Field") + case "name": + out.Values[i] = ec.___Field_name(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "displayName": - - out.Values[i] = ec._UserAuthToken_displayName(ctx, field, obj) - + case "description": + out.Values[i] = ec.___Field_description(ctx, field, obj) + case "args": + out.Values[i] = ec.___Field_args(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "message": - - out.Values[i] = ec._UserAuthToken_message(ctx, field, obj) - - case "origin": - - out.Values[i] = ec._UserAuthToken_origin(ctx, field, obj) - + case "type": + out.Values[i] = ec.___Field_type(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "isDeprecated": + out.Values[i] = ec.___Field_isDeprecated(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "deprecationReason": + out.Values[i] = ec.___Field_deprecationReason(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } -var userInfoImplementors = []string{"UserInfo"} +var __InputValueImplementors = []string{"__InputValue"} + +func (ec *executionContext) ___InputValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.InputValue) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __InputValueImplementors) -func (ec *executionContext) _UserInfo(ctx context.Context, sel ast.SelectionSet, obj *model.UserInfo) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, userInfoImplementors) out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": - out.Values[i] = graphql.MarshalString("UserInfo") - case "userId": - - out.Values[i] = ec._UserInfo_userId(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "displayName": - - out.Values[i] = ec._UserInfo_displayName(ctx, field, obj) - - case "authTokens": - - out.Values[i] = ec._UserInfo_authTokens(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "linkedAuthProviders": - - out.Values[i] = ec._UserInfo_linkedAuthProviders(ctx, field, obj) - + out.Values[i] = graphql.MarshalString("__InputValue") + case "name": + out.Values[i] = ec.___InputValue_name(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "metaParameters": - - out.Values[i] = ec._UserInfo_metaParameters(ctx, field, obj) - + case "description": + out.Values[i] = ec.___InputValue_description(ctx, field, obj) + case "type": + out.Values[i] = ec.___InputValue_type(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "configurationParameters": - - out.Values[i] = ec._UserInfo_configurationParameters(ctx, field, obj) - + case "defaultValue": + out.Values[i] = ec.___InputValue_defaultValue(ctx, field, obj) + case "isDeprecated": + out.Values[i] = ec.___InputValue_isDeprecated(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "deprecationReason": + out.Values[i] = ec.___InputValue_deprecationReason(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } -var webFeatureSetImplementors = []string{"WebFeatureSet"} +var __SchemaImplementors = []string{"__Schema"} + +func (ec *executionContext) ___Schema(ctx context.Context, sel ast.SelectionSet, obj *introspection.Schema) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __SchemaImplementors) -func (ec *executionContext) _WebFeatureSet(ctx context.Context, sel ast.SelectionSet, obj *model.WebFeatureSet) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, webFeatureSetImplementors) out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { switch field.Name { case "__typename": - out.Values[i] = graphql.MarshalString("WebFeatureSet") - case "id": - - out.Values[i] = ec._WebFeatureSet_id(ctx, field, obj) - + out.Values[i] = graphql.MarshalString("__Schema") + case "description": + out.Values[i] = ec.___Schema_description(ctx, field, obj) + case "types": + out.Values[i] = ec.___Schema_types(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "label": - - out.Values[i] = ec._WebFeatureSet_label(ctx, field, obj) - + case "queryType": + out.Values[i] = ec.___Schema_queryType(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } - case "description": + case "mutationType": + out.Values[i] = ec.___Schema_mutationType(ctx, field, obj) + case "subscriptionType": + out.Values[i] = ec.___Schema_subscriptionType(ctx, field, obj) + case "directives": + out.Values[i] = ec.___Schema_directives(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } - out.Values[i] = ec._WebFeatureSet_description(ctx, field, obj) + atomic.AddInt32(&ec.deferred, int32(len(deferred))) - case "icon": + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } - out.Values[i] = ec._WebFeatureSet_icon(ctx, field, obj) + return out +} - case "enabled": +var __TypeImplementors = []string{"__Type"} - out.Values[i] = ec._WebFeatureSet_enabled(ctx, field, obj) +func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, obj *introspection.Type) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __TypeImplementors) + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Type") + case "kind": + out.Values[i] = ec.___Type_kind(ctx, field, obj) if out.Values[i] == graphql.Null { - invalids++ + out.Invalids++ } + case "name": + out.Values[i] = ec.___Type_name(ctx, field, obj) + case "description": + out.Values[i] = ec.___Type_description(ctx, field, obj) + case "specifiedByURL": + out.Values[i] = ec.___Type_specifiedByURL(ctx, field, obj) + case "fields": + out.Values[i] = ec.___Type_fields(ctx, field, obj) + case "interfaces": + out.Values[i] = ec.___Type_interfaces(ctx, field, obj) + case "possibleTypes": + out.Values[i] = ec.___Type_possibleTypes(ctx, field, obj) + case "enumValues": + out.Values[i] = ec.___Type_enumValues(ctx, field, obj) + case "inputFields": + out.Values[i] = ec.___Type_inputFields(ctx, field, obj) + case "ofType": + out.Values[i] = ec.___Type_ofType(ctx, field, obj) + case "isOneOf": + out.Values[i] = ec.___Type_isOneOf(ctx, field, obj) default: panic("unknown field " + strconv.Quote(field.Name)) } } - out.Dispatch() - if invalids > 0 { + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } -var webServiceConfigImplementors = []string{"WebServiceConfig"} +// endregion **************************** object.gotpl **************************** -func (ec *executionContext) _WebServiceConfig(ctx context.Context, sel ast.SelectionSet, obj *model.WebServiceConfig) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, webServiceConfigImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("WebServiceConfig") - case "id": +// region ***************************** type.gotpl ***************************** - out.Values[i] = ec._WebServiceConfig_id(ctx, field, obj) +func (ec *executionContext) marshalNAdminAuthProviderConfiguration2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v model.AdminAuthProviderConfiguration) graphql.Marshaler { + return ec._AdminAuthProviderConfiguration(ctx, sel, &v) +} - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfigurationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminAuthProviderConfiguration) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "name": + ret[i] = ec.marshalNAdminAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec._WebServiceConfig_name(ctx, field, obj) + } + wg.Wait() - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec._WebServiceConfig_description(ctx, field, obj) + return ret +} - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v *model.AdminAuthProviderConfiguration) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AdminAuthProviderConfiguration(ctx, sel, v) +} + +func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminConnectionGrantInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "bundleVersion": + ret[i] = ec.marshalNAdminConnectionGrantInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec._WebServiceConfig_bundleVersion(ctx, field, obj) + } + wg.Wait() - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) + for _, e := range ret { + if e == graphql.Null { + return graphql.Null } } - out.Dispatch() - if invalids > 0 { + + return ret +} + +func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminConnectionGrantInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } return graphql.Null } - return out + return ec._AdminConnectionGrantInfo(ctx, sel, v) } -var __DirectiveImplementors = []string{"__Directive"} +func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminConnectionSearchInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNAdminConnectionSearchInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } -func (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __DirectiveImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Directive") - case "name": + } + wg.Wait() - out.Values[i] = ec.___Directive_name(ctx, field, obj) + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - if out.Values[i] == graphql.Null { - invalids++ + return ret +} + +func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminConnectionSearchInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AdminConnectionSearchInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNAdminObjectGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminObjectGrantInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminObjectGrantInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "description": + ret[i] = ec.marshalNAdminObjectGrantInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminObjectGrantInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec.___Directive_description(ctx, field, obj) + } + wg.Wait() - case "locations": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec.___Directive_locations(ctx, field, obj) + return ret +} - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAdminObjectGrantInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminObjectGrantInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminObjectGrantInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AdminObjectGrantInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNAdminObjectPermissions2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminObjectPermissions(ctx context.Context, sel ast.SelectionSet, v *model.AdminObjectPermissions) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AdminObjectPermissions(ctx, sel, v) +} + +func (ec *executionContext) marshalNAdminPermissionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminPermissionInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "args": + ret[i] = ec.marshalNAdminPermissionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec.___Directive_args(ctx, field, obj) + } + wg.Wait() - if out.Values[i] == graphql.Null { - invalids++ - } - case "isRepeatable": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec.___Directive_isRepeatable(ctx, field, obj) + return ret +} - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) +func (ec *executionContext) marshalNAdminPermissionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminPermissionInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - } - out.Dispatch() - if invalids > 0 { return graphql.Null } - return out + return ec._AdminPermissionInfo(ctx, sel, v) } -var __EnumValueImplementors = []string{"__EnumValue"} +func (ec *executionContext) unmarshalNAdminSubjectType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminSubjectType(ctx context.Context, v any) (model.AdminSubjectType, error) { + var res model.AdminSubjectType + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} -func (ec *executionContext) ___EnumValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.EnumValue) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __EnumValueImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__EnumValue") - case "name": +func (ec *executionContext) marshalNAdminSubjectType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminSubjectType(ctx context.Context, sel ast.SelectionSet, v model.AdminSubjectType) graphql.Marshaler { + return v +} - out.Values[i] = ec.___EnumValue_name(ctx, field, obj) +func (ec *executionContext) marshalNAdminTeamInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminTeamInfo(ctx context.Context, sel ast.SelectionSet, v model.AdminTeamInfo) graphql.Marshaler { + return ec._AdminTeamInfo(ctx, sel, &v) +} - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAdminTeamInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminTeamInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminTeamInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "description": - - out.Values[i] = ec.___EnumValue_description(ctx, field, obj) - - case "isDeprecated": + ret[i] = ec.marshalNAdminTeamInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminTeamInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec.___EnumValue_isDeprecated(ctx, field, obj) + } + wg.Wait() - if out.Values[i] == graphql.Null { - invalids++ - } - case "deprecationReason": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec.___EnumValue_deprecationReason(ctx, field, obj) + return ret +} - default: - panic("unknown field " + strconv.Quote(field.Name)) +func (ec *executionContext) marshalNAdminTeamInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminTeamInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminTeamInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - } - out.Dispatch() - if invalids > 0 { return graphql.Null } - return out + return ec._AdminTeamInfo(ctx, sel, v) } -var __FieldImplementors = []string{"__Field"} - -func (ec *executionContext) ___Field(ctx context.Context, sel ast.SelectionSet, obj *introspection.Field) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __FieldImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Field") - case "name": - - out.Values[i] = ec.___Field_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "description": - - out.Values[i] = ec.___Field_description(ctx, field, obj) - - case "args": - - out.Values[i] = ec.___Field_args(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "type": +func (ec *executionContext) unmarshalNAdminUserFilterInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserFilterInput(ctx context.Context, v any) (model.AdminUserFilterInput, error) { + res, err := ec.unmarshalInputAdminUserFilterInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} - out.Values[i] = ec.___Field_type(ctx, field, obj) +func (ec *executionContext) marshalNAdminUserInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo(ctx context.Context, sel ast.SelectionSet, v model.AdminUserInfo) graphql.Marshaler { + return ec._AdminUserInfo(ctx, sel, &v) +} - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAdminUserInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminUserInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "isDeprecated": + ret[i] = ec.marshalNAdminUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec.___Field_isDeprecated(ctx, field, obj) + } + wg.Wait() - if out.Values[i] == graphql.Null { - invalids++ - } - case "deprecationReason": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec.___Field_deprecationReason(ctx, field, obj) + return ret +} - default: - panic("unknown field " + strconv.Quote(field.Name)) +func (ec *executionContext) marshalNAdminUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminUserInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - } - out.Dispatch() - if invalids > 0 { return graphql.Null } - return out + return ec._AdminUserInfo(ctx, sel, v) } -var __InputValueImplementors = []string{"__InputValue"} - -func (ec *executionContext) ___InputValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.InputValue) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __InputValueImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__InputValue") - case "name": - - out.Values[i] = ec.___InputValue_name(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAdminUserTeamGrantInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserTeamGrantInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminUserTeamGrantInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "description": - - out.Values[i] = ec.___InputValue_description(ctx, field, obj) - - case "type": + ret[i] = ec.marshalNAdminUserTeamGrantInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserTeamGrantInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec.___InputValue_type(ctx, field, obj) + } + wg.Wait() - if out.Values[i] == graphql.Null { - invalids++ - } - case "defaultValue": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec.___InputValue_defaultValue(ctx, field, obj) + return ret +} - default: - panic("unknown field " + strconv.Quote(field.Name)) +func (ec *executionContext) marshalNAdminUserTeamGrantInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserTeamGrantInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminUserTeamGrantInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - } - out.Dispatch() - if invalids > 0 { return graphql.Null } - return out + return ec._AdminUserTeamGrantInfo(ctx, sel, v) } -var __SchemaImplementors = []string{"__Schema"} - -func (ec *executionContext) ___Schema(ctx context.Context, sel ast.SelectionSet, obj *introspection.Schema) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __SchemaImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Schema") - case "description": - - out.Values[i] = ec.___Schema_description(ctx, field, obj) - - case "types": - - out.Values[i] = ec.___Schema_types(ctx, field, obj) - - if out.Values[i] == graphql.Null { - invalids++ - } - case "queryType": +func (ec *executionContext) marshalNAsyncTaskInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, v model.AsyncTaskInfo) graphql.Marshaler { + return ec._AsyncTaskInfo(ctx, sel, &v) +} - out.Values[i] = ec.___Schema_queryType(ctx, field, obj) +func (ec *executionContext) marshalNAsyncTaskInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, v *model.AsyncTaskInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AsyncTaskInfo(ctx, sel, v) +} - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAuthCredentialInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthCredentialInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "mutationType": - - out.Values[i] = ec.___Schema_mutationType(ctx, field, obj) - - case "subscriptionType": + ret[i] = ec.marshalNAuthCredentialInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec.___Schema_subscriptionType(ctx, field, obj) + } + wg.Wait() - case "directives": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec.___Schema_directives(ctx, field, obj) + return ret +} - if out.Values[i] == graphql.Null { - invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) +func (ec *executionContext) marshalNAuthCredentialInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthCredentialInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - } - out.Dispatch() - if invalids > 0 { return graphql.Null } - return out + return ec._AuthCredentialInfo(ctx, sel, v) } -var __TypeImplementors = []string{"__Type"} +func (ec *executionContext) marshalNAuthInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo(ctx context.Context, sel ast.SelectionSet, v model.AuthInfo) graphql.Marshaler { + return ec._AuthInfo(ctx, sel, &v) +} -func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, obj *introspection.Type) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, __TypeImplementors) - out := graphql.NewFieldSet(fields) - var invalids uint32 - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("__Type") - case "kind": +func (ec *executionContext) marshalNAuthInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AuthInfo(ctx, sel, v) +} - out.Values[i] = ec.___Type_kind(ctx, field, obj) +func (ec *executionContext) marshalNAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderConfiguration) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AuthProviderConfiguration(ctx, sel, v) +} - if out.Values[i] == graphql.Null { - invalids++ +func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfileᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderCredentialsProfile) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() } - case "name": - - out.Values[i] = ec.___Type_name(ctx, field, obj) - - case "description": - - out.Values[i] = ec.___Type_description(ctx, field, obj) - - case "fields": - - out.Values[i] = ec.___Type_fields(ctx, field, obj) - - case "interfaces": - - out.Values[i] = ec.___Type_interfaces(ctx, field, obj) - - case "possibleTypes": - - out.Values[i] = ec.___Type_possibleTypes(ctx, field, obj) - - case "enumValues": - - out.Values[i] = ec.___Type_enumValues(ctx, field, obj) - - case "inputFields": - - out.Values[i] = ec.___Type_inputFields(ctx, field, obj) - - case "ofType": + ret[i] = ec.marshalNAuthProviderCredentialsProfile2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfile(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } - out.Values[i] = ec.___Type_ofType(ctx, field, obj) + } + wg.Wait() - case "specifiedByURL": + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } - out.Values[i] = ec.___Type_specifiedByURL(ctx, field, obj) + return ret +} - default: - panic("unknown field " + strconv.Quote(field.Name)) +func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfile(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderCredentialsProfile) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - } - out.Dispatch() - if invalids > 0 { return graphql.Null } - return out -} - -// endregion **************************** object.gotpl **************************** - -// region ***************************** type.gotpl ***************************** - -func (ec *executionContext) marshalNAdminAuthProviderConfiguration2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v model.AdminAuthProviderConfiguration) graphql.Marshaler { - return ec._AdminAuthProviderConfiguration(ctx, sel, &v) + return ec._AuthProviderCredentialsProfile(ctx, sel, v) } -func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfigurationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminAuthProviderConfiguration) graphql.Marshaler { +func (ec *executionContext) marshalNAuthProviderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44041,7 +50177,7 @@ func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚕᚖdmsᚋi if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAdminAuthProviderConfiguration2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration(ctx, sel, v[i]) + ret[i] = ec.marshalNAuthProviderInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44061,17 +50197,72 @@ func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚕᚖdmsᚋi return ret } -func (ec *executionContext) marshalNAdminAuthProviderConfiguration2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v *model.AdminAuthProviderConfiguration) graphql.Marshaler { +func (ec *executionContext) marshalNAuthProviderInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AdminAuthProviderConfiguration(ctx, sel, v) + return ec._AuthProviderInfo(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNAuthStatus2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthStatus(ctx context.Context, v any) (model.AuthStatus, error) { + var res model.AuthStatus + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNAuthStatus2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthStatus(ctx context.Context, sel ast.SelectionSet, v model.AuthStatus) graphql.Marshaler { + return v +} + +func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v any) (bool, error) { + res, err := graphql.UnmarshalBoolean(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { + _ = sel + res := graphql.MarshalBoolean(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) marshalNCondition2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐCondition(ctx context.Context, sel ast.SelectionSet, v *model.Condition) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Condition(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNConditionType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConditionType(ctx context.Context, v any) (model.ConditionType, error) { + var res model.ConditionType + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNConditionType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConditionType(ctx context.Context, sel ast.SelectionSet, v model.ConditionType) graphql.Marshaler { + return v +} + +func (ec *executionContext) unmarshalNConnectionConfig2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx context.Context, v any) (model.ConnectionConfig, error) { + res, err := ec.unmarshalInputConnectionConfig(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminConnectionGrantInfo) graphql.Marshaler { +func (ec *executionContext) marshalNConnectionFolderInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, v model.ConnectionFolderInfo) graphql.Marshaler { + return ec._ConnectionFolderInfo(ctx, sel, &v) +} + +func (ec *executionContext) marshalNConnectionFolderInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ConnectionFolderInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44095,7 +50286,7 @@ func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚕᚖdmsᚋinterna if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAdminConnectionGrantInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNConnectionFolderInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44115,17 +50306,21 @@ func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚕᚖdmsᚋinterna return ret } -func (ec *executionContext) marshalNAdminConnectionGrantInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionGrantInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminConnectionGrantInfo) graphql.Marshaler { +func (ec *executionContext) marshalNConnectionFolderInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, v *model.ConnectionFolderInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AdminConnectionGrantInfo(ctx, sel, v) + return ec._ConnectionFolderInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNConnectionInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx context.Context, sel ast.SelectionSet, v model.ConnectionInfo) graphql.Marshaler { + return ec._ConnectionInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminConnectionSearchInfo) graphql.Marshaler { +func (ec *executionContext) marshalNConnectionInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ConnectionInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44149,7 +50344,7 @@ func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚕᚖdmsᚋintern if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAdminConnectionSearchInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44169,17 +50364,46 @@ func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚕᚖdmsᚋintern return ret } -func (ec *executionContext) marshalNAdminConnectionSearchInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminConnectionSearchInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminConnectionSearchInfo) graphql.Marshaler { +func (ec *executionContext) marshalNConnectionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx context.Context, sel ast.SelectionSet, v *model.ConnectionInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AdminConnectionSearchInfo(ctx, sel, v) + return ec._ConnectionInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNDataTransferDefaultExportSettings2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferDefaultExportSettings(ctx context.Context, sel ast.SelectionSet, v model.DataTransferDefaultExportSettings) graphql.Marshaler { + return ec._DataTransferDefaultExportSettings(ctx, sel, &v) +} + +func (ec *executionContext) marshalNDataTransferDefaultExportSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferDefaultExportSettings(ctx context.Context, sel ast.SelectionSet, v *model.DataTransferDefaultExportSettings) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._DataTransferDefaultExportSettings(ctx, sel, v) } -func (ec *executionContext) marshalNAdminPermissionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminPermissionInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDataTransferOutputSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferOutputSettings(ctx context.Context, sel ast.SelectionSet, v *model.DataTransferOutputSettings) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._DataTransferOutputSettings(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNDataTransferParameters2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferParameters(ctx context.Context, v any) (model.DataTransferParameters, error) { + res, err := ec.unmarshalInputDataTransferParameters(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNDataTransferProcessorInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DataTransferProcessorInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44203,7 +50427,7 @@ func (ec *executionContext) marshalNAdminPermissionInfo2ᚕᚖdmsᚋinternalᚋp if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAdminPermissionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNDataTransferProcessorInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44223,21 +50447,17 @@ func (ec *executionContext) marshalNAdminPermissionInfo2ᚕᚖdmsᚋinternalᚋp return ret } -func (ec *executionContext) marshalNAdminPermissionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminPermissionInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminPermissionInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDataTransferProcessorInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfo(ctx context.Context, sel ast.SelectionSet, v *model.DataTransferProcessorInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AdminPermissionInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAdminRoleInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminRoleInfo(ctx context.Context, sel ast.SelectionSet, v model.AdminRoleInfo) graphql.Marshaler { - return ec._AdminRoleInfo(ctx, sel, &v) + return ec._DataTransferProcessorInfo(ctx, sel, v) } -func (ec *executionContext) marshalNAdminRoleInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminRoleInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminRoleInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DataTypeLogicalOperation) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44261,7 +50481,7 @@ func (ec *executionContext) marshalNAdminRoleInfo2ᚕᚖdmsᚋinternalᚋpkgᚋc if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAdminRoleInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminRoleInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNDataTypeLogicalOperation2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperation(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44281,31 +50501,17 @@ func (ec *executionContext) marshalNAdminRoleInfo2ᚕᚖdmsᚋinternalᚋpkgᚋc return ret } -func (ec *executionContext) marshalNAdminRoleInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminRoleInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminRoleInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperation(ctx context.Context, sel ast.SelectionSet, v *model.DataTypeLogicalOperation) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AdminRoleInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNAdminSubjectType2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminSubjectType(ctx context.Context, v interface{}) (model.AdminSubjectType, error) { - var res model.AdminSubjectType - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNAdminSubjectType2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminSubjectType(ctx context.Context, sel ast.SelectionSet, v model.AdminSubjectType) graphql.Marshaler { - return v -} - -func (ec *executionContext) marshalNAdminUserInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo(ctx context.Context, sel ast.SelectionSet, v model.AdminUserInfo) graphql.Marshaler { - return ec._AdminUserInfo(ctx, sel, &v) + return ec._DataTypeLogicalOperation(ctx, sel, v) } -func (ec *executionContext) marshalNAdminUserInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AdminUserInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDatabaseAuthModel2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModelᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DatabaseAuthModel) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44329,7 +50535,7 @@ func (ec *executionContext) marshalNAdminUserInfo2ᚕᚖdmsᚋinternalᚋpkgᚋc if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAdminUserInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNDatabaseAuthModel2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModel(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44349,31 +50555,17 @@ func (ec *executionContext) marshalNAdminUserInfo2ᚕᚖdmsᚋinternalᚋpkgᚋc return ret } -func (ec *executionContext) marshalNAdminUserInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAdminUserInfo(ctx context.Context, sel ast.SelectionSet, v *model.AdminUserInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._AdminUserInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNAsyncTaskInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, v model.AsyncTaskInfo) graphql.Marshaler { - return ec._AsyncTaskInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNAsyncTaskInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAsyncTaskInfo(ctx context.Context, sel ast.SelectionSet, v *model.AsyncTaskInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDatabaseAuthModel2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModel(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseAuthModel) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AsyncTaskInfo(ctx, sel, v) + return ec._DatabaseAuthModel(ctx, sel, v) } -func (ec *executionContext) marshalNAuthCredentialInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthCredentialInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDatabaseCatalog2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalogᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DatabaseCatalog) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44397,7 +50589,7 @@ func (ec *executionContext) marshalNAuthCredentialInfo2ᚕᚖdmsᚋinternalᚋpk if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAuthCredentialInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNDatabaseCatalog2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalog(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44417,41 +50609,62 @@ func (ec *executionContext) marshalNAuthCredentialInfo2ᚕᚖdmsᚋinternalᚋpk return ret } -func (ec *executionContext) marshalNAuthCredentialInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthCredentialInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDatabaseCatalog2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalog(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseCatalog) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AuthCredentialInfo(ctx, sel, v) + return ec._DatabaseCatalog(ctx, sel, v) } -func (ec *executionContext) marshalNAuthInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo(ctx context.Context, sel ast.SelectionSet, v model.AuthInfo) graphql.Marshaler { - return ec._AuthInfo(ctx, sel, &v) +func (ec *executionContext) marshalNDatabaseStructContainers2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, v model.DatabaseStructContainers) graphql.Marshaler { + return ec._DatabaseStructContainers(ctx, sel, &v) } -func (ec *executionContext) marshalNAuthInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDatabaseStructContainers2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseStructContainers) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AuthInfo(ctx, sel, v) + return ec._DatabaseStructContainers(ctx, sel, v) } -func (ec *executionContext) marshalNAuthProviderConfiguration2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfiguration(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderConfiguration) graphql.Marshaler { - if v == nil { +func (ec *executionContext) unmarshalNDateTime2timeᚐTime(ctx context.Context, v any) (time.Time, error) { + res, err := graphql.UnmarshalTime(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNDateTime2timeᚐTime(ctx context.Context, sel ast.SelectionSet, v time.Time) graphql.Marshaler { + _ = sel + res := graphql.MarshalTime(v) + if res == graphql.Null { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - return graphql.Null } - return ec._AuthProviderConfiguration(ctx, sel, v) + return res +} + +func (ec *executionContext) unmarshalNDriverConfigurationType2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType(ctx context.Context, v any) ([]*model.DriverConfigurationType, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) + var err error + res := make([]*model.DriverConfigurationType, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalODriverConfigurationType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil } -func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfileᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderCredentialsProfile) graphql.Marshaler { +func (ec *executionContext) marshalNDriverConfigurationType2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType(ctx context.Context, sel ast.SelectionSet, v []*model.DriverConfigurationType) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44475,7 +50688,7 @@ func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚕᚖdmsᚋi if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAuthProviderCredentialsProfile2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfile(ctx, sel, v[i]) + ret[i] = ec.marshalODriverConfigurationType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44486,26 +50699,20 @@ func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚕᚖdmsᚋi } wg.Wait() - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - return ret } -func (ec *executionContext) marshalNAuthProviderCredentialsProfile2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderCredentialsProfile(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderCredentialsProfile) graphql.Marshaler { +func (ec *executionContext) marshalNDriverFileInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverFileInfo(ctx context.Context, sel ast.SelectionSet, v *model.DriverFileInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AuthProviderCredentialsProfile(ctx, sel, v) + return ec._DriverFileInfo(ctx, sel, v) } -func (ec *executionContext) marshalNAuthProviderInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDriverInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DriverInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44529,7 +50736,7 @@ func (ec *executionContext) marshalNAuthProviderInfo2ᚕᚖdmsᚋinternalᚋpkg if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAuthProviderInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNDriverInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44549,51 +50756,17 @@ func (ec *executionContext) marshalNAuthProviderInfo2ᚕᚖdmsᚋinternalᚋpkg return ret } -func (ec *executionContext) marshalNAuthProviderInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderInfo(ctx context.Context, sel ast.SelectionSet, v *model.AuthProviderInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDriverInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfo(ctx context.Context, sel ast.SelectionSet, v *model.DriverInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._AuthProviderInfo(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNAuthStatus2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthStatus(ctx context.Context, v interface{}) (model.AuthStatus, error) { - var res model.AuthStatus - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNAuthStatus2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthStatus(ctx context.Context, sel ast.SelectionSet, v model.AuthStatus) graphql.Marshaler { - return v -} - -func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v interface{}) (bool, error) { - res, err := graphql.UnmarshalBoolean(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { - res := graphql.MarshalBoolean(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) unmarshalNConnectionConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx context.Context, v interface{}) (model.ConnectionConfig, error) { - res, err := ec.unmarshalInputConnectionConfig(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNConnectionFolderInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, v model.ConnectionFolderInfo) graphql.Marshaler { - return ec._ConnectionFolderInfo(ctx, sel, &v) + return ec._DriverInfo(ctx, sel, v) } -func (ec *executionContext) marshalNConnectionFolderInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ConnectionFolderInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDriverLibraryInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverLibraryInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DriverLibraryInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44617,7 +50790,7 @@ func (ec *executionContext) marshalNConnectionFolderInfo2ᚕᚖdmsᚋinternalᚋ if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNConnectionFolderInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNDriverLibraryInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverLibraryInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44637,21 +50810,17 @@ func (ec *executionContext) marshalNConnectionFolderInfo2ᚕᚖdmsᚋinternalᚋ return ret } -func (ec *executionContext) marshalNConnectionFolderInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionFolderInfo(ctx context.Context, sel ast.SelectionSet, v *model.ConnectionFolderInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDriverLibraryInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverLibraryInfo(ctx context.Context, sel ast.SelectionSet, v *model.DriverLibraryInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._ConnectionFolderInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNConnectionInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx context.Context, sel ast.SelectionSet, v model.ConnectionInfo) graphql.Marshaler { - return ec._ConnectionInfo(ctx, sel, &v) + return ec._DriverLibraryInfo(ctx, sel, v) } -func (ec *executionContext) marshalNConnectionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ConnectionInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDynamicTraceProperty2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDynamicTracePropertyᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DynamicTraceProperty) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44675,7 +50844,7 @@ func (ec *executionContext) marshalNConnectionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋ if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNDynamicTraceProperty2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDynamicTraceProperty(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44695,55 +50864,80 @@ func (ec *executionContext) marshalNConnectionInfo2ᚕᚖdmsᚋinternalᚋpkgᚋ return ret } -func (ec *executionContext) marshalNConnectionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionInfo(ctx context.Context, sel ast.SelectionSet, v *model.ConnectionInfo) graphql.Marshaler { +func (ec *executionContext) marshalNDynamicTraceProperty2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDynamicTraceProperty(ctx context.Context, sel ast.SelectionSet, v *model.DynamicTraceProperty) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._ConnectionInfo(ctx, sel, v) + return ec._DynamicTraceProperty(ctx, sel, v) } -func (ec *executionContext) unmarshalNDataTransferParameters2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferParameters(ctx context.Context, v interface{}) (model.DataTransferParameters, error) { - res, err := ec.unmarshalInputDataTransferParameters(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) +func (ec *executionContext) marshalNFederatedAuthInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐFederatedAuthInfo(ctx context.Context, sel ast.SelectionSet, v model.FederatedAuthInfo) graphql.Marshaler { + return ec._FederatedAuthInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNDataTransferProcessorInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DataTransferProcessorInfo) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) +func (ec *executionContext) marshalNFederatedAuthInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐFederatedAuthInfo(ctx context.Context, sel ast.SelectionSet, v *model.FederatedAuthInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], + return ec._FederatedAuthInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNFederatedAuthResult2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐFederatedAuthResult(ctx context.Context, sel ast.SelectionSet, v model.FederatedAuthResult) graphql.Marshaler { + return ec._FederatedAuthResult(ctx, sel, &v) +} + +func (ec *executionContext) marshalNFederatedAuthResult2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐFederatedAuthResult(ctx context.Context, sel ast.SelectionSet, v *model.FederatedAuthResult) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNDataTransferProcessorInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfo(ctx, sel, v[i]) + return graphql.Null + } + return ec._FederatedAuthResult(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNID2string(ctx context.Context, v any) (string, error) { + res, err := graphql.UnmarshalID(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNID2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + _ = sel + res := graphql.MarshalID(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - if isLen1 { - f(i) - } else { - go f(i) + } + return res +} + +func (ec *executionContext) unmarshalNID2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNID2string(ctx, vSlice[i]) + if err != nil { + return nil, err } + } + return res, nil +} +func (ec *executionContext) marshalNID2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNID2string(ctx, sel, v[i]) } - wg.Wait() for _, e := range ret { if e == graphql.Null { @@ -44754,17 +50948,47 @@ func (ec *executionContext) marshalNDataTransferProcessorInfo2ᚕᚖdmsᚋintern return ret } -func (ec *executionContext) marshalNDataTransferProcessorInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferProcessorInfo(ctx context.Context, sel ast.SelectionSet, v *model.DataTransferProcessorInfo) graphql.Marshaler { - if v == nil { +func (ec *executionContext) unmarshalNID2ᚕᚖstring(ctx context.Context, v any) ([]*string, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) + var err error + res := make([]*string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalOID2ᚖstring(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalNID2ᚕᚖstring(ctx context.Context, sel ast.SelectionSet, v []*string) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalOID2ᚖstring(ctx, sel, v[i]) + } + + return ret +} + +func (ec *executionContext) unmarshalNInt2int(ctx context.Context, v any) (int, error) { + res, err := graphql.UnmarshalInt(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { + _ = sel + res := graphql.MarshalInt(v) + if res == graphql.Null { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } - return graphql.Null } - return ec._DataTransferProcessorInfo(ctx, sel, v) + return res } -func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DataTypeLogicalOperation) graphql.Marshaler { +func (ec *executionContext) marshalNLogEntry2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntryᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.LogEntry) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44788,7 +51012,7 @@ func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚕᚖdmsᚋinterna if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNDataTypeLogicalOperation2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperation(ctx, sel, v[i]) + ret[i] = ec.marshalNLogEntry2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntry(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44808,17 +51032,35 @@ func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚕᚖdmsᚋinterna return ret } -func (ec *executionContext) marshalNDataTypeLogicalOperation2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTypeLogicalOperation(ctx context.Context, sel ast.SelectionSet, v *model.DataTypeLogicalOperation) graphql.Marshaler { +func (ec *executionContext) marshalNLogEntry2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntry(ctx context.Context, sel ast.SelectionSet, v *model.LogEntry) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._DataTypeLogicalOperation(ctx, sel, v) + return ec._LogEntry(ctx, sel, v) +} + +func (ec *executionContext) marshalNLogoutInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogoutInfo(ctx context.Context, sel ast.SelectionSet, v model.LogoutInfo) graphql.Marshaler { + return ec._LogoutInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNDatabaseAuthModel2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModelᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DatabaseAuthModel) graphql.Marshaler { +func (ec *executionContext) marshalNLogoutInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogoutInfo(ctx context.Context, sel ast.SelectionSet, v *model.LogoutInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._LogoutInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNNavigatorNodeInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, v model.NavigatorNodeInfo) graphql.Marshaler { + return ec._NavigatorNodeInfo(ctx, sel, &v) +} + +func (ec *executionContext) marshalNNavigatorNodeInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NavigatorNodeInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44842,7 +51084,7 @@ func (ec *executionContext) marshalNDatabaseAuthModel2ᚕᚖdmsᚋinternalᚋpkg if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNDatabaseAuthModel2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModel(ctx, sel, v[i]) + ret[i] = ec.marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44862,17 +51104,56 @@ func (ec *executionContext) marshalNDatabaseAuthModel2ᚕᚖdmsᚋinternalᚋpkg return ret } -func (ec *executionContext) marshalNDatabaseAuthModel2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseAuthModel(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseAuthModel) graphql.Marshaler { +func (ec *executionContext) marshalNNavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorNodeInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._DatabaseAuthModel(ctx, sel, v) + return ec._NavigatorNodeInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNNavigatorSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettings(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorSettings) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._NavigatorSettings(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNNavigatorSettingsInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettingsInput(ctx context.Context, v any) (model.NavigatorSettingsInput, error) { + res, err := ec.unmarshalInputNavigatorSettingsInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNNetworkEndpointInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, v model.NetworkEndpointInfo) graphql.Marshaler { + return ec._NetworkEndpointInfo(ctx, sel, &v) +} + +func (ec *executionContext) marshalNNetworkEndpointInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, v *model.NetworkEndpointInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._NetworkEndpointInfo(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNNetworkHandlerAuthType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, v any) (model.NetworkHandlerAuthType, error) { + var res model.NetworkHandlerAuthType + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNNetworkHandlerAuthType2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, sel ast.SelectionSet, v model.NetworkHandlerAuthType) graphql.Marshaler { + return v } -func (ec *executionContext) marshalNDatabaseCatalog2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalogᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DatabaseCatalog) graphql.Marshaler { +func (ec *executionContext) marshalNNetworkHandlerConfig2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NetworkHandlerConfig) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44896,7 +51177,7 @@ func (ec *executionContext) marshalNDatabaseCatalog2ᚕᚖdmsᚋinternalᚋpkg if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNDatabaseCatalog2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalog(ctx, sel, v[i]) + ret[i] = ec.marshalNNetworkHandlerConfig2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfig(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44916,46 +51197,27 @@ func (ec *executionContext) marshalNDatabaseCatalog2ᚕᚖdmsᚋinternalᚋpkg return ret } -func (ec *executionContext) marshalNDatabaseCatalog2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseCatalog(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseCatalog) graphql.Marshaler { +func (ec *executionContext) marshalNNetworkHandlerConfig2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfig(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerConfig) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._DatabaseCatalog(ctx, sel, v) -} - -func (ec *executionContext) marshalNDatabaseStructContainers2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, v model.DatabaseStructContainers) graphql.Marshaler { - return ec._DatabaseStructContainers(ctx, sel, &v) -} - -func (ec *executionContext) marshalNDatabaseStructContainers2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseStructContainers(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseStructContainers) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._DatabaseStructContainers(ctx, sel, v) + return ec._NetworkHandlerConfig(ctx, sel, v) } -func (ec *executionContext) unmarshalNDateTime2timeᚐTime(ctx context.Context, v interface{}) (time.Time, error) { - res, err := graphql.UnmarshalTime(v) +func (ec *executionContext) unmarshalNNetworkHandlerConfigInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput(ctx context.Context, v any) (model.NetworkHandlerConfigInput, error) { + res, err := ec.unmarshalInputNetworkHandlerConfigInput(ctx, v) return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNDateTime2timeᚐTime(ctx context.Context, sel ast.SelectionSet, v time.Time) graphql.Marshaler { - res := graphql.MarshalTime(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res +func (ec *executionContext) unmarshalNNetworkHandlerConfigInput2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput(ctx context.Context, v any) (*model.NetworkHandlerConfigInput, error) { + res, err := ec.unmarshalInputNetworkHandlerConfigInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNDriverInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DriverInfo) graphql.Marshaler { +func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptorᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NetworkHandlerDescriptor) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -44979,7 +51241,7 @@ func (ec *executionContext) marshalNDriverInfo2ᚕᚖdmsᚋinternalᚋpkgᚋclou if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNDriverInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNNetworkHandlerDescriptor2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptor(ctx, sel, v[i]) } if isLen1 { f(i) @@ -44999,23 +51261,30 @@ func (ec *executionContext) marshalNDriverInfo2ᚕᚖdmsᚋinternalᚋpkgᚋclou return ret } -func (ec *executionContext) marshalNDriverInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverInfo(ctx context.Context, sel ast.SelectionSet, v *model.DriverInfo) graphql.Marshaler { +func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptor(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerDescriptor) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._DriverInfo(ctx, sel, v) + return ec._NetworkHandlerDescriptor(ctx, sel, v) } -func (ec *executionContext) unmarshalNID2string(ctx context.Context, v interface{}) (string, error) { - res, err := graphql.UnmarshalID(v) +func (ec *executionContext) unmarshalNObject2interface(ctx context.Context, v any) (any, error) { + res, err := graphql.UnmarshalAny(v) return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNID2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { - res := graphql.MarshalID(v) +func (ec *executionContext) marshalNObject2interface(ctx context.Context, sel ast.SelectionSet, v any) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + _ = sel + res := graphql.MarshalAny(v) if res == graphql.Null { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") @@ -45024,48 +51293,14 @@ func (ec *executionContext) marshalNID2string(ctx context.Context, sel ast.Selec return res } -func (ec *executionContext) unmarshalNID2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } +func (ec *executionContext) unmarshalNObject2ᚕinterface(ctx context.Context, v any) ([]any, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) var err error - res := make([]string, len(vSlice)) + res := make([]any, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNID2string(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalNID2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalNID2string(ctx, sel, v[i]) - } - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - -func (ec *executionContext) unmarshalNID2ᚕᚖstring(ctx context.Context, v interface{}) ([]*string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*string, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOID2ᚖstring(ctx, vSlice[i]) + res[i], err = ec.unmarshalOObject2interface(ctx, vSlice[i]) if err != nil { return nil, err } @@ -45073,31 +51308,16 @@ func (ec *executionContext) unmarshalNID2ᚕᚖstring(ctx context.Context, v int return res, nil } -func (ec *executionContext) marshalNID2ᚕᚖstring(ctx context.Context, sel ast.SelectionSet, v []*string) graphql.Marshaler { +func (ec *executionContext) marshalNObject2ᚕinterface(ctx context.Context, sel ast.SelectionSet, v []any) graphql.Marshaler { ret := make(graphql.Array, len(v)) for i := range v { - ret[i] = ec.marshalOID2ᚖstring(ctx, sel, v[i]) + ret[i] = ec.marshalOObject2interface(ctx, sel, v[i]) } return ret } -func (ec *executionContext) unmarshalNInt2int(ctx context.Context, v interface{}) (int, error) { - res, err := graphql.UnmarshalInt(v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { - res := graphql.MarshalInt(v) - if res == graphql.Null { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - } - return res -} - -func (ec *executionContext) marshalNLogEntry2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntryᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.LogEntry) graphql.Marshaler { +func (ec *executionContext) marshalNObjectOrigin2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOriginᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectOrigin) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45121,7 +51341,7 @@ func (ec *executionContext) marshalNLogEntry2ᚕᚖdmsᚋinternalᚋpkgᚋcloudb if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNLogEntry2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntry(ctx, sel, v[i]) + ret[i] = ec.marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45141,21 +51361,21 @@ func (ec *executionContext) marshalNLogEntry2ᚕᚖdmsᚋinternalᚋpkgᚋcloudb return ret } -func (ec *executionContext) marshalNLogEntry2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐLogEntry(ctx context.Context, sel ast.SelectionSet, v *model.LogEntry) graphql.Marshaler { +func (ec *executionContext) marshalNObjectOrigin2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin(ctx context.Context, sel ast.SelectionSet, v *model.ObjectOrigin) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._LogEntry(ctx, sel, v) + return ec._ObjectOrigin(ctx, sel, v) } -func (ec *executionContext) marshalNNavigatorNodeInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, v model.NavigatorNodeInfo) graphql.Marshaler { - return ec._NavigatorNodeInfo(ctx, sel, &v) +func (ec *executionContext) marshalNObjectPropertyInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v model.ObjectPropertyInfo) graphql.Marshaler { + return ec._ObjectPropertyInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNNavigatorNodeInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NavigatorNodeInfo) graphql.Marshaler { +func (ec *executionContext) marshalNObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45179,7 +51399,7 @@ func (ec *executionContext) marshalNNavigatorNodeInfo2ᚕᚖdmsᚋinternalᚋpkg if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNNavigatorNodeInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45199,56 +51419,56 @@ func (ec *executionContext) marshalNNavigatorNodeInfo2ᚕᚖdmsᚋinternalᚋpkg return ret } -func (ec *executionContext) marshalNNavigatorNodeInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorNodeInfo) graphql.Marshaler { +func (ec *executionContext) marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v *model.ObjectPropertyInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._NavigatorNodeInfo(ctx, sel, v) + return ec._ObjectPropertyInfo(ctx, sel, v) } -func (ec *executionContext) marshalNNavigatorSettings2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettings(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorSettings) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._NavigatorSettings(ctx, sel, v) +func (ec *executionContext) unmarshalNObjectPropertyLength2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyLength(ctx context.Context, v any) (model.ObjectPropertyLength, error) { + var res model.ObjectPropertyLength + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) unmarshalNNavigatorSettingsInput2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorSettingsInput(ctx context.Context, v interface{}) (model.NavigatorSettingsInput, error) { - res, err := ec.unmarshalInputNavigatorSettingsInput(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) +func (ec *executionContext) marshalNObjectPropertyLength2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyLength(ctx context.Context, sel ast.SelectionSet, v model.ObjectPropertyLength) graphql.Marshaler { + return v } -func (ec *executionContext) marshalNNetworkEndpointInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, v model.NetworkEndpointInfo) graphql.Marshaler { - return ec._NetworkEndpointInfo(ctx, sel, &v) +func (ec *executionContext) unmarshalNPageInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐPageInput(ctx context.Context, v any) (model.PageInput, error) { + res, err := ec.unmarshalInputPageInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNNetworkEndpointInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkEndpointInfo(ctx context.Context, sel ast.SelectionSet, v *model.NetworkEndpointInfo) graphql.Marshaler { +func (ec *executionContext) marshalNProductInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductInfo(ctx context.Context, sel ast.SelectionSet, v *model.ProductInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._NetworkEndpointInfo(ctx, sel, v) + return ec._ProductInfo(ctx, sel, v) } -func (ec *executionContext) unmarshalNNetworkHandlerAuthType2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, v interface{}) (model.NetworkHandlerAuthType, error) { - var res model.NetworkHandlerAuthType - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) +func (ec *executionContext) marshalNProductSettings2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductSettings(ctx context.Context, sel ast.SelectionSet, v model.ProductSettings) graphql.Marshaler { + return ec._ProductSettings(ctx, sel, &v) } -func (ec *executionContext) marshalNNetworkHandlerAuthType2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, sel ast.SelectionSet, v model.NetworkHandlerAuthType) graphql.Marshaler { - return v +func (ec *executionContext) marshalNProductSettings2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductSettings(ctx context.Context, sel ast.SelectionSet, v *model.ProductSettings) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._ProductSettings(ctx, sel, v) } -func (ec *executionContext) marshalNNetworkHandlerConfig2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NetworkHandlerConfig) graphql.Marshaler { +func (ec *executionContext) marshalNProductSettingsGroup2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductSettingsGroupᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ProductSettingsGroup) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45272,7 +51492,7 @@ func (ec *executionContext) marshalNNetworkHandlerConfig2ᚕᚖdmsᚋinternalᚋ if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNNetworkHandlerConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfig(ctx, sel, v[i]) + ret[i] = ec.marshalNProductSettingsGroup2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductSettingsGroup(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45292,27 +51512,17 @@ func (ec *executionContext) marshalNNetworkHandlerConfig2ᚕᚖdmsᚋinternalᚋ return ret } -func (ec *executionContext) marshalNNetworkHandlerConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfig(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerConfig) graphql.Marshaler { +func (ec *executionContext) marshalNProductSettingsGroup2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductSettingsGroup(ctx context.Context, sel ast.SelectionSet, v *model.ProductSettingsGroup) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._NetworkHandlerConfig(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNNetworkHandlerConfigInput2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput(ctx context.Context, v interface{}) (model.NetworkHandlerConfigInput, error) { - res, err := ec.unmarshalInputNetworkHandlerConfigInput(ctx, v) - return res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) unmarshalNNetworkHandlerConfigInput2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput(ctx context.Context, v interface{}) (*model.NetworkHandlerConfigInput, error) { - res, err := ec.unmarshalInputNetworkHandlerConfigInput(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) + return ec._ProductSettingsGroup(ctx, sel, v) } -func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptorᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.NetworkHandlerDescriptor) graphql.Marshaler { +func (ec *executionContext) marshalNProjectInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProjectInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ProjectInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45336,7 +51546,7 @@ func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚕᚖdmsᚋinterna if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNNetworkHandlerDescriptor2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptor(ctx, sel, v[i]) + ret[i] = ec.marshalNProjectInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProjectInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45356,47 +51566,82 @@ func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚕᚖdmsᚋinterna return ret } -func (ec *executionContext) marshalNNetworkHandlerDescriptor2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerDescriptor(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerDescriptor) graphql.Marshaler { +func (ec *executionContext) marshalNProjectInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProjectInfo(ctx context.Context, sel ast.SelectionSet, v *model.ProjectInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._NetworkHandlerDescriptor(ctx, sel, v) + return ec._ProjectInfo(ctx, sel, v) } -func (ec *executionContext) unmarshalNObject2interface(ctx context.Context, v interface{}) (interface{}, error) { - res, err := graphql.UnmarshalAny(v) - return res, graphql.ErrorOnPath(ctx, err) +func (ec *executionContext) marshalNRMProject2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProject(ctx context.Context, sel ast.SelectionSet, v model.RMProject) graphql.Marshaler { + return ec._RMProject(ctx, sel, &v) } -func (ec *executionContext) marshalNObject2interface(ctx context.Context, sel ast.SelectionSet, v interface{}) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") +func (ec *executionContext) marshalNRMProject2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.RMProject) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], } - return graphql.Null + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNRMProject2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProject(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + } - res := graphql.MarshalAny(v) - if res == graphql.Null { + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNRMProject2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProject(ctx context.Context, sel ast.SelectionSet, v *model.RMProject) graphql.Marshaler { + if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } + return graphql.Null } - return res + return ec._RMProject(ctx, sel, v) } -func (ec *executionContext) unmarshalNObject2ᚕinterface(ctx context.Context, v interface{}) ([]interface{}, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } +func (ec *executionContext) unmarshalNRMProjectPermissions2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectPermissionsᚄ(ctx context.Context, v any) ([]*model.RMProjectPermissions, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) var err error - res := make([]interface{}, len(vSlice)) + res := make([]*model.RMProjectPermissions, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOObject2interface(ctx, vSlice[i]) + res[i], err = ec.unmarshalNRMProjectPermissions2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectPermissions(ctx, vSlice[i]) if err != nil { return nil, err } @@ -45404,16 +51649,12 @@ func (ec *executionContext) unmarshalNObject2ᚕinterface(ctx context.Context, v return res, nil } -func (ec *executionContext) marshalNObject2ᚕinterface(ctx context.Context, sel ast.SelectionSet, v []interface{}) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalOObject2interface(ctx, sel, v[i]) - } - - return ret +func (ec *executionContext) unmarshalNRMProjectPermissions2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectPermissions(ctx context.Context, v any) (*model.RMProjectPermissions, error) { + res, err := ec.unmarshalInputRMProjectPermissions(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNObjectOrigin2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOriginᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectOrigin) graphql.Marshaler { +func (ec *executionContext) marshalNRMResource2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.RMResource) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45437,7 +51678,7 @@ func (ec *executionContext) marshalNObjectOrigin2ᚕᚖdmsᚋinternalᚋpkgᚋcl if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNObjectOrigin2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin(ctx, sel, v[i]) + ret[i] = ec.marshalNRMResource2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResource(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45457,21 +51698,17 @@ func (ec *executionContext) marshalNObjectOrigin2ᚕᚖdmsᚋinternalᚋpkgᚋcl return ret } -func (ec *executionContext) marshalNObjectOrigin2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectOrigin(ctx context.Context, sel ast.SelectionSet, v *model.ObjectOrigin) graphql.Marshaler { +func (ec *executionContext) marshalNRMResource2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResource(ctx context.Context, sel ast.SelectionSet, v *model.RMResource) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._ObjectOrigin(ctx, sel, v) -} - -func (ec *executionContext) marshalNObjectPropertyInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v model.ObjectPropertyInfo) graphql.Marshaler { - return ec._ObjectPropertyInfo(ctx, sel, &v) + return ec._RMResource(ctx, sel, v) } -func (ec *executionContext) marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { +func (ec *executionContext) marshalNRMResourceType2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.RMResourceType) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45495,7 +51732,7 @@ func (ec *executionContext) marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpk if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNObjectPropertyInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNRMResourceType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceType(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45515,37 +51752,110 @@ func (ec *executionContext) marshalNObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpk return ret } -func (ec *executionContext) marshalNObjectPropertyInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v *model.ObjectPropertyInfo) graphql.Marshaler { +func (ec *executionContext) marshalNRMResourceType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceType(ctx context.Context, sel ast.SelectionSet, v *model.RMResourceType) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._ObjectPropertyInfo(ctx, sel, v) + return ec._RMResourceType(ctx, sel, v) } -func (ec *executionContext) unmarshalNObjectPropertyLength2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyLength(ctx context.Context, v interface{}) (model.ObjectPropertyLength, error) { - var res model.ObjectPropertyLength +func (ec *executionContext) unmarshalNRMSubjectProjectPermissions2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMSubjectProjectPermissionsᚄ(ctx context.Context, v any) ([]*model.RMSubjectProjectPermissions, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) + var err error + res := make([]*model.RMSubjectProjectPermissions, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNRMSubjectProjectPermissions2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMSubjectProjectPermissions(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalNRMSubjectProjectPermissions2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMSubjectProjectPermissions(ctx context.Context, v any) (*model.RMSubjectProjectPermissions, error) { + res, err := ec.unmarshalInputRMSubjectProjectPermissions(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNResultDataFormat2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, v any) (model.ResultDataFormat, error) { + var res model.ResultDataFormat err := res.UnmarshalGQL(v) return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNObjectPropertyLength2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyLength(ctx context.Context, sel ast.SelectionSet, v model.ObjectPropertyLength) graphql.Marshaler { +func (ec *executionContext) marshalNResultDataFormat2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, sel ast.SelectionSet, v model.ResultDataFormat) graphql.Marshaler { return v } -func (ec *executionContext) marshalNProductInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐProductInfo(ctx context.Context, sel ast.SelectionSet, v *model.ProductInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") +func (ec *executionContext) unmarshalNResultDataFormat2ᚕgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormatᚄ(ctx context.Context, v any) ([]model.ResultDataFormat, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) + var err error + res := make([]model.ResultDataFormat, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNResultDataFormat2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx, vSlice[i]) + if err != nil { + return nil, err } - return graphql.Null } - return ec._ProductInfo(ctx, sel, v) + return res, nil +} + +func (ec *executionContext) marshalNResultDataFormat2ᚕgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormatᚄ(ctx context.Context, sel ast.SelectionSet, v []model.ResultDataFormat) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNResultDataFormat2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNSQLContextInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLContextInfo) graphql.Marshaler { + return ec._SQLContextInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNRMProject2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProjectᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.RMProject) graphql.Marshaler { +func (ec *executionContext) marshalNSQLContextInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v []*model.SQLContextInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45569,7 +51879,7 @@ func (ec *executionContext) marshalNRMProject2ᚕᚖdmsᚋinternalᚋpkgᚋcloud if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNRMProject2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProject(ctx, sel, v[i]) + ret[i] = ec.marshalOSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45580,107 +51890,48 @@ func (ec *executionContext) marshalNRMProject2ᚕᚖdmsᚋinternalᚋpkgᚋcloud } wg.Wait() - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - return ret } -func (ec *executionContext) marshalNRMProject2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMProject(ctx context.Context, sel ast.SelectionSet, v *model.RMProject) graphql.Marshaler { +func (ec *executionContext) marshalNSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLContextInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._RMProject(ctx, sel, v) + return ec._SQLContextInfo(ctx, sel, v) } -func (ec *executionContext) marshalNRMResource2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResourceᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.RMResource) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNRMResource2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResource(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret +func (ec *executionContext) marshalNSQLExecuteInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLExecuteInfo) graphql.Marshaler { + return ec._SQLExecuteInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNRMResource2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐRMResource(ctx context.Context, sel ast.SelectionSet, v *model.RMResource) graphql.Marshaler { +func (ec *executionContext) marshalNSQLExecuteInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecuteInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._RMResource(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNResultDataFormat2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, v interface{}) (model.ResultDataFormat, error) { - var res model.ResultDataFormat - err := res.UnmarshalGQL(v) - return res, graphql.ErrorOnPath(ctx, err) + return ec._SQLExecuteInfo(ctx, sel, v) } -func (ec *executionContext) marshalNResultDataFormat2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, sel ast.SelectionSet, v model.ResultDataFormat) graphql.Marshaler { - return v +func (ec *executionContext) marshalNSQLExecutionPlan2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, v model.SQLExecutionPlan) graphql.Marshaler { + return ec._SQLExecutionPlan(ctx, sel, &v) } -func (ec *executionContext) unmarshalNResultDataFormat2ᚕdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormatᚄ(ctx context.Context, v interface{}) ([]model.ResultDataFormat, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]model.ResultDataFormat, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNResultDataFormat2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx, vSlice[i]) - if err != nil { - return nil, err +func (ec *executionContext) marshalNSQLExecutionPlan2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecutionPlan) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") } + return graphql.Null } - return res, nil + return ec._SQLExecutionPlan(ctx, sel, v) } -func (ec *executionContext) marshalNResultDataFormat2ᚕdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormatᚄ(ctx context.Context, sel ast.SelectionSet, v []model.ResultDataFormat) graphql.Marshaler { +func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNodeᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLExecutionPlanNode) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45704,7 +51955,7 @@ func (ec *executionContext) marshalNResultDataFormat2ᚕdmsᚋinternalᚋpkgᚋc if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNResultDataFormat2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx, sel, v[i]) + ret[i] = ec.marshalNSQLExecutionPlanNode2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNode(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45724,11 +51975,17 @@ func (ec *executionContext) marshalNResultDataFormat2ᚕdmsᚋinternalᚋpkgᚋc return ret } -func (ec *executionContext) marshalNSQLContextInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLContextInfo) graphql.Marshaler { - return ec._SQLContextInfo(ctx, sel, &v) +func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNode(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecutionPlanNode) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._SQLExecutionPlanNode(ctx, sel, v) } -func (ec *executionContext) marshalNSQLContextInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v []*model.SQLContextInfo) graphql.Marshaler { +func (ec *executionContext) marshalNSQLQueryGenerator2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGeneratorᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLQueryGenerator) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45752,7 +52009,7 @@ func (ec *executionContext) marshalNSQLContextInfo2ᚕᚖdmsᚋinternalᚋpkgᚋ if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalOSQLContextInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNSQLQueryGenerator2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGenerator(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45763,48 +52020,26 @@ func (ec *executionContext) marshalNSQLContextInfo2ᚕᚖdmsᚋinternalᚋpkgᚋ } wg.Wait() - return ret -} - -func (ec *executionContext) marshalNSQLContextInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLContextInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLContextInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLExecuteInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLExecuteInfo) graphql.Marshaler { - return ec._SQLExecuteInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSQLExecuteInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecuteInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") + for _, e := range ret { + if e == graphql.Null { + return graphql.Null } - return graphql.Null } - return ec._SQLExecuteInfo(ctx, sel, v) -} -func (ec *executionContext) marshalNSQLExecutionPlan2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, v model.SQLExecutionPlan) graphql.Marshaler { - return ec._SQLExecutionPlan(ctx, sel, &v) + return ret } -func (ec *executionContext) marshalNSQLExecutionPlan2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlan(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecutionPlan) graphql.Marshaler { +func (ec *executionContext) marshalNSQLQueryGenerator2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGenerator(ctx context.Context, sel ast.SelectionSet, v *model.SQLQueryGenerator) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._SQLExecutionPlan(ctx, sel, v) + return ec._SQLQueryGenerator(ctx, sel, v) } -func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNodeᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLExecutionPlanNode) graphql.Marshaler { +func (ec *executionContext) marshalNSQLQueryResults2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResultsᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLQueryResults) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45828,7 +52063,7 @@ func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚕᚖdmsᚋinternalᚋ if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNSQLExecutionPlanNode2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNode(ctx, sel, v[i]) + ret[i] = ec.marshalNSQLQueryResults2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResults(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45848,71 +52083,60 @@ func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚕᚖdmsᚋinternalᚋ return ret } -func (ec *executionContext) marshalNSQLExecutionPlanNode2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecutionPlanNode(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecutionPlanNode) graphql.Marshaler { +func (ec *executionContext) marshalNSQLQueryResults2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResults(ctx context.Context, sel ast.SelectionSet, v *model.SQLQueryResults) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._SQLExecutionPlanNode(ctx, sel, v) + return ec._SQLQueryResults(ctx, sel, v) } -func (ec *executionContext) marshalNSQLQueryGenerator2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGeneratorᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLQueryGenerator) graphql.Marshaler { - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalNSQLQueryGenerator2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGenerator(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() +func (ec *executionContext) unmarshalNSQLResultRow2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow(ctx context.Context, v any) (model.SQLResultRow, error) { + res, err := ec.unmarshalInputSQLResultRow(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} - for _, e := range ret { - if e == graphql.Null { - return graphql.Null +func (ec *executionContext) unmarshalNSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx context.Context, v any) ([]*model.SQLResultRow, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) + var err error + res := make([]*model.SQLResultRow, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNSQLResultRow2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow(ctx, vSlice[i]) + if err != nil { + return nil, err } } + return res, nil +} - return ret +func (ec *executionContext) unmarshalNSQLResultRow2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow(ctx context.Context, v any) (*model.SQLResultRow, error) { + res, err := ec.unmarshalInputSQLResultRow(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNSQLScriptInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLScriptInfo) graphql.Marshaler { + return ec._SQLScriptInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNSQLQueryGenerator2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryGenerator(ctx context.Context, sel ast.SelectionSet, v *model.SQLQueryGenerator) graphql.Marshaler { +func (ec *executionContext) marshalNSQLScriptInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLScriptInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._SQLQueryGenerator(ctx, sel, v) + return ec._SQLScriptInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNSQLScriptQuery2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery(ctx context.Context, sel ast.SelectionSet, v model.SQLScriptQuery) graphql.Marshaler { + return ec._SQLScriptQuery(ctx, sel, &v) } -func (ec *executionContext) marshalNSQLQueryResults2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResultsᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLQueryResults) graphql.Marshaler { +func (ec *executionContext) marshalNSQLScriptQuery2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQueryᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLScriptQuery) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -45936,7 +52160,7 @@ func (ec *executionContext) marshalNSQLQueryResults2ᚕᚖdmsᚋinternalᚋpkg if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNSQLQueryResults2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResults(ctx, sel, v[i]) + ret[i] = ec.marshalNSQLScriptQuery2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery(ctx, sel, v[i]) } if isLen1 { f(i) @@ -45956,57 +52180,17 @@ func (ec *executionContext) marshalNSQLQueryResults2ᚕᚖdmsᚋinternalᚋpkg return ret } -func (ec *executionContext) marshalNSQLQueryResults2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLQueryResults(ctx context.Context, sel ast.SelectionSet, v *model.SQLQueryResults) graphql.Marshaler { +func (ec *executionContext) marshalNSQLScriptQuery2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery(ctx context.Context, sel ast.SelectionSet, v *model.SQLScriptQuery) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._SQLQueryResults(ctx, sel, v) -} - -func (ec *executionContext) unmarshalNSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx context.Context, v interface{}) ([]*model.SQLResultRow, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]*model.SQLResultRow, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNSQLResultRow2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) unmarshalNSQLResultRow2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow(ctx context.Context, v interface{}) (*model.SQLResultRow, error) { - res, err := ec.unmarshalInputSQLResultRow(ctx, v) - return &res, graphql.ErrorOnPath(ctx, err) -} - -func (ec *executionContext) marshalNSQLScriptInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptInfo(ctx context.Context, sel ast.SelectionSet, v model.SQLScriptInfo) graphql.Marshaler { - return ec._SQLScriptInfo(ctx, sel, &v) -} - -func (ec *executionContext) marshalNSQLScriptInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLScriptInfo) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - ec.Errorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._SQLScriptInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalNSQLScriptQuery2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery(ctx context.Context, sel ast.SelectionSet, v model.SQLScriptQuery) graphql.Marshaler { - return ec._SQLScriptQuery(ctx, sel, &v) + return ec._SQLScriptQuery(ctx, sel, v) } -func (ec *executionContext) marshalNSQLScriptQuery2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQueryᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SQLScriptQuery) graphql.Marshaler { +func (ec *executionContext) marshalNSecretInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSecretInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.SecretInfo) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -46030,7 +52214,7 @@ func (ec *executionContext) marshalNSQLScriptQuery2ᚕᚖdmsᚋinternalᚋpkgᚋ if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNSQLScriptQuery2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery(ctx, sel, v[i]) + ret[i] = ec.marshalNSecretInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSecretInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -46050,21 +52234,21 @@ func (ec *executionContext) marshalNSQLScriptQuery2ᚕᚖdmsᚋinternalᚋpkgᚋ return ret } -func (ec *executionContext) marshalNSQLScriptQuery2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLScriptQuery(ctx context.Context, sel ast.SelectionSet, v *model.SQLScriptQuery) graphql.Marshaler { +func (ec *executionContext) marshalNSecretInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSecretInfo(ctx context.Context, sel ast.SelectionSet, v *model.SecretInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") } return graphql.Null } - return ec._SQLScriptQuery(ctx, sel, v) + return ec._SecretInfo(ctx, sel, v) } -func (ec *executionContext) marshalNServerConfig2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfig(ctx context.Context, sel ast.SelectionSet, v model.ServerConfig) graphql.Marshaler { +func (ec *executionContext) marshalNServerConfig2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfig(ctx context.Context, sel ast.SelectionSet, v model.ServerConfig) graphql.Marshaler { return ec._ServerConfig(ctx, sel, &v) } -func (ec *executionContext) marshalNServerConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfig(ctx context.Context, sel ast.SelectionSet, v *model.ServerConfig) graphql.Marshaler { +func (ec *executionContext) marshalNServerConfig2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfig(ctx context.Context, sel ast.SelectionSet, v *model.ServerConfig) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") @@ -46074,12 +52258,12 @@ func (ec *executionContext) marshalNServerConfig2ᚖdmsᚋinternalᚋpkgᚋcloud return ec._ServerConfig(ctx, sel, v) } -func (ec *executionContext) unmarshalNServerConfigInput2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfigInput(ctx context.Context, v interface{}) (model.ServerConfigInput, error) { +func (ec *executionContext) unmarshalNServerConfigInput2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerConfigInput(ctx context.Context, v any) (model.ServerConfigInput, error) { res, err := ec.unmarshalInputServerConfigInput(ctx, v) return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNServerLanguage2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguageᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ServerLanguage) graphql.Marshaler { +func (ec *executionContext) marshalNServerLanguage2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguageᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ServerLanguage) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -46103,7 +52287,7 @@ func (ec *executionContext) marshalNServerLanguage2ᚕᚖdmsᚋinternalᚋpkgᚋ if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNServerLanguage2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguage(ctx, sel, v[i]) + ret[i] = ec.marshalNServerLanguage2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguage(ctx, sel, v[i]) } if isLen1 { f(i) @@ -46123,7 +52307,7 @@ func (ec *executionContext) marshalNServerLanguage2ᚕᚖdmsᚋinternalᚋpkgᚋ return ret } -func (ec *executionContext) marshalNServerLanguage2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguage(ctx context.Context, sel ast.SelectionSet, v *model.ServerLanguage) graphql.Marshaler { +func (ec *executionContext) marshalNServerLanguage2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerLanguage(ctx context.Context, sel ast.SelectionSet, v *model.ServerLanguage) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") @@ -46133,11 +52317,11 @@ func (ec *executionContext) marshalNServerLanguage2ᚖdmsᚋinternalᚋpkgᚋclo return ec._ServerLanguage(ctx, sel, v) } -func (ec *executionContext) marshalNSessionInfo2dmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo(ctx context.Context, sel ast.SelectionSet, v model.SessionInfo) graphql.Marshaler { +func (ec *executionContext) marshalNSessionInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo(ctx context.Context, sel ast.SelectionSet, v model.SessionInfo) graphql.Marshaler { return ec._SessionInfo(ctx, sel, &v) } -func (ec *executionContext) marshalNSessionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo(ctx context.Context, sel ast.SelectionSet, v *model.SessionInfo) graphql.Marshaler { +func (ec *executionContext) marshalNSessionInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSessionInfo(ctx context.Context, sel ast.SelectionSet, v *model.SessionInfo) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") @@ -46147,12 +52331,13 @@ func (ec *executionContext) marshalNSessionInfo2ᚖdmsᚋinternalᚋpkgᚋcloudb return ec._SessionInfo(ctx, sel, v) } -func (ec *executionContext) unmarshalNString2string(ctx context.Context, v interface{}) (string, error) { +func (ec *executionContext) unmarshalNString2string(ctx context.Context, v any) (string, error) { res, err := graphql.UnmarshalString(v) return res, graphql.ErrorOnPath(ctx, err) } func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + _ = sel res := graphql.MarshalString(v) if res == graphql.Null { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { @@ -46162,11 +52347,9 @@ func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.S return res } -func (ec *executionContext) unmarshalNString2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } +func (ec *executionContext) unmarshalNString2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]string, len(vSlice)) for i := range vSlice { @@ -46194,11 +52377,9 @@ func (ec *executionContext) marshalNString2ᚕstringᚄ(ctx context.Context, sel return ret } -func (ec *executionContext) unmarshalNString2ᚕᚕᚖstring(ctx context.Context, v interface{}) ([][]*string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } +func (ec *executionContext) unmarshalNString2ᚕᚕᚖstring(ctx context.Context, v any) ([][]*string, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([][]*string, len(vSlice)) for i := range vSlice { @@ -46220,11 +52401,9 @@ func (ec *executionContext) marshalNString2ᚕᚕᚖstring(ctx context.Context, return ret } -func (ec *executionContext) unmarshalNString2ᚕᚖstring(ctx context.Context, v interface{}) ([]*string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } +func (ec *executionContext) unmarshalNString2ᚕᚖstring(ctx context.Context, v any) ([]*string, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]*string, len(vSlice)) for i := range vSlice { @@ -46246,7 +52425,75 @@ func (ec *executionContext) marshalNString2ᚕᚖstring(ctx context.Context, sel return ret } -func (ec *executionContext) marshalNUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.UserAuthToken) graphql.Marshaler { +func (ec *executionContext) marshalNTransactionLogInfoItem2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐTransactionLogInfoItemᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.TransactionLogInfoItem) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNTransactionLogInfoItem2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐTransactionLogInfoItem(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNTransactionLogInfoItem2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐTransactionLogInfoItem(ctx context.Context, sel ast.SelectionSet, v *model.TransactionLogInfoItem) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._TransactionLogInfoItem(ctx, sel, v) +} + +func (ec *executionContext) marshalNTransactionLogInfos2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐTransactionLogInfos(ctx context.Context, sel ast.SelectionSet, v model.TransactionLogInfos) graphql.Marshaler { + return ec._TransactionLogInfos(ctx, sel, &v) +} + +func (ec *executionContext) marshalNTransactionLogInfos2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐTransactionLogInfos(ctx context.Context, sel ast.SelectionSet, v *model.TransactionLogInfos) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._TransactionLogInfos(ctx, sel, v) +} + +func (ec *executionContext) marshalNUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.UserAuthToken) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -46270,7 +52517,7 @@ func (ec *executionContext) marshalNUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋc if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNUserAuthToken2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthToken(ctx, sel, v[i]) + ret[i] = ec.marshalNUserAuthToken2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthToken(ctx, sel, v[i]) } if isLen1 { f(i) @@ -46290,7 +52537,7 @@ func (ec *executionContext) marshalNUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋc return ret } -func (ec *executionContext) marshalNUserAuthToken2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthToken(ctx context.Context, sel ast.SelectionSet, v *model.UserAuthToken) graphql.Marshaler { +func (ec *executionContext) marshalNUserAuthToken2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthToken(ctx context.Context, sel ast.SelectionSet, v *model.UserAuthToken) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") @@ -46300,7 +52547,75 @@ func (ec *executionContext) marshalNUserAuthToken2ᚖdmsᚋinternalᚋpkgᚋclou return ec._UserAuthToken(ctx, sel, v) } -func (ec *executionContext) marshalNWebFeatureSet2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSetᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.WebFeatureSet) graphql.Marshaler { +func (ec *executionContext) marshalNUserInfo2githubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserInfo(ctx context.Context, sel ast.SelectionSet, v model.UserInfo) graphql.Marshaler { + return ec._UserInfo(ctx, sel, &v) +} + +func (ec *executionContext) marshalNUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserInfo(ctx context.Context, sel ast.SelectionSet, v *model.UserInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._UserInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNUserTeamInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserTeamInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.UserTeamInfo) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNUserTeamInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserTeamInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNUserTeamInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserTeamInfo(ctx context.Context, sel ast.SelectionSet, v *model.UserTeamInfo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._UserTeamInfo(ctx, sel, v) +} + +func (ec *executionContext) marshalNWebFeatureSet2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSetᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.WebFeatureSet) graphql.Marshaler { ret := make(graphql.Array, len(v)) var wg sync.WaitGroup isLen1 := len(v) == 1 @@ -46324,7 +52639,7 @@ func (ec *executionContext) marshalNWebFeatureSet2ᚕᚖdmsᚋinternalᚋpkgᚋc if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNWebFeatureSet2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSet(ctx, sel, v[i]) + ret[i] = ec.marshalNWebFeatureSet2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSet(ctx, sel, v[i]) } if isLen1 { f(i) @@ -46344,7 +52659,7 @@ func (ec *executionContext) marshalNWebFeatureSet2ᚕᚖdmsᚋinternalᚋpkgᚋc return ret } -func (ec *executionContext) marshalNWebFeatureSet2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSet(ctx context.Context, sel ast.SelectionSet, v *model.WebFeatureSet) graphql.Marshaler { +func (ec *executionContext) marshalNWebFeatureSet2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebFeatureSet(ctx context.Context, sel ast.SelectionSet, v *model.WebFeatureSet) graphql.Marshaler { if v == nil { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { ec.Errorf(ctx, "the requested element is null which the schema does not allow") @@ -46402,12 +52717,13 @@ func (ec *executionContext) marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgq return ret } -func (ec *executionContext) unmarshalN__DirectiveLocation2string(ctx context.Context, v interface{}) (string, error) { +func (ec *executionContext) unmarshalN__DirectiveLocation2string(ctx context.Context, v any) (string, error) { res, err := graphql.UnmarshalString(v) return res, graphql.ErrorOnPath(ctx, err) } func (ec *executionContext) marshalN__DirectiveLocation2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + _ = sel res := graphql.MarshalString(v) if res == graphql.Null { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { @@ -46417,11 +52733,9 @@ func (ec *executionContext) marshalN__DirectiveLocation2string(ctx context.Conte return res } -func (ec *executionContext) unmarshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } +func (ec *executionContext) unmarshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]string, len(vSlice)) for i := range vSlice { @@ -46592,12 +52906,13 @@ func (ec *executionContext) marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgen return ec.___Type(ctx, sel, v) } -func (ec *executionContext) unmarshalN__TypeKind2string(ctx context.Context, v interface{}) (string, error) { +func (ec *executionContext) unmarshalN__TypeKind2string(ctx context.Context, v any) (string, error) { res, err := graphql.UnmarshalString(v) return res, graphql.ErrorOnPath(ctx, err) } func (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + _ = sel res := graphql.MarshalString(v) if res == graphql.Null { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { @@ -46607,7 +52922,7 @@ func (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel a return res } -func (ec *executionContext) unmarshalOAuthCredentialEncryption2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialEncryption(ctx context.Context, v interface{}) (*model.AuthCredentialEncryption, error) { +func (ec *executionContext) unmarshalOAuthCredentialEncryption2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialEncryption(ctx context.Context, v any) (*model.AuthCredentialEncryption, error) { if v == nil { return nil, nil } @@ -46616,14 +52931,14 @@ func (ec *executionContext) unmarshalOAuthCredentialEncryption2ᚖdmsᚋinternal return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalOAuthCredentialEncryption2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialEncryption(ctx context.Context, sel ast.SelectionSet, v *model.AuthCredentialEncryption) graphql.Marshaler { +func (ec *executionContext) marshalOAuthCredentialEncryption2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthCredentialEncryption(ctx context.Context, sel ast.SelectionSet, v *model.AuthCredentialEncryption) graphql.Marshaler { if v == nil { return graphql.Null } return v } -func (ec *executionContext) marshalOAuthProviderConfiguration2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfigurationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderConfiguration) graphql.Marshaler { +func (ec *executionContext) marshalOAuthProviderConfiguration2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfigurationᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AuthProviderConfiguration) graphql.Marshaler { if v == nil { return graphql.Null } @@ -46650,7 +52965,7 @@ func (ec *executionContext) marshalOAuthProviderConfiguration2ᚕᚖdmsᚋintern if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNAuthProviderConfiguration2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfiguration(ctx, sel, v[i]) + ret[i] = ec.marshalNAuthProviderConfiguration2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐAuthProviderConfiguration(ctx, sel, v[i]) } if isLen1 { f(i) @@ -46670,17 +52985,19 @@ func (ec *executionContext) marshalOAuthProviderConfiguration2ᚕᚖdmsᚋintern return ret } -func (ec *executionContext) unmarshalOBoolean2bool(ctx context.Context, v interface{}) (bool, error) { +func (ec *executionContext) unmarshalOBoolean2bool(ctx context.Context, v any) (bool, error) { res, err := graphql.UnmarshalBoolean(v) return res, graphql.ErrorOnPath(ctx, err) } func (ec *executionContext) marshalOBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { + _ = sel + _ = ctx res := graphql.MarshalBoolean(v) return res } -func (ec *executionContext) unmarshalOBoolean2ᚖbool(ctx context.Context, v interface{}) (*bool, error) { +func (ec *executionContext) unmarshalOBoolean2ᚖbool(ctx context.Context, v any) (*bool, error) { if v == nil { return nil, nil } @@ -46692,11 +53009,60 @@ func (ec *executionContext) marshalOBoolean2ᚖbool(ctx context.Context, sel ast if v == nil { return graphql.Null } + _ = sel + _ = ctx res := graphql.MarshalBoolean(*v) return res } -func (ec *executionContext) unmarshalOConnectionConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx context.Context, v interface{}) (*model.ConnectionConfig, error) { +func (ec *executionContext) marshalOCondition2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConditionᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.Condition) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNCondition2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐCondition(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOConnectionConfig2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐConnectionConfig(ctx context.Context, v any) (*model.ConnectionConfig, error) { if v == nil { return nil, nil } @@ -46704,14 +53070,22 @@ func (ec *executionContext) unmarshalOConnectionConfig2ᚖdmsᚋinternalᚋpkg return &res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalODatabaseObjectInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseObjectInfo(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseObjectInfo) graphql.Marshaler { +func (ec *executionContext) unmarshalODataTransferOutputSettingsInput2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDataTransferOutputSettingsInput(ctx context.Context, v any) (*model.DataTransferOutputSettingsInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputDataTransferOutputSettingsInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalODatabaseObjectInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDatabaseObjectInfo(ctx context.Context, sel ast.SelectionSet, v *model.DatabaseObjectInfo) graphql.Marshaler { if v == nil { return graphql.Null } return ec._DatabaseObjectInfo(ctx, sel, v) } -func (ec *executionContext) unmarshalODateTime2ᚖtimeᚐTime(ctx context.Context, v interface{}) (*time.Time, error) { +func (ec *executionContext) unmarshalODateTime2ᚖtimeᚐTime(ctx context.Context, v any) (*time.Time, error) { if v == nil { return nil, nil } @@ -46723,11 +53097,76 @@ func (ec *executionContext) marshalODateTime2ᚖtimeᚐTime(ctx context.Context, if v == nil { return graphql.Null } + _ = sel + _ = ctx res := graphql.MarshalTime(*v) return res } -func (ec *executionContext) unmarshalOFloat2ᚖfloat64(ctx context.Context, v interface{}) (*float64, error) { +func (ec *executionContext) unmarshalODriverConfigurationType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType(ctx context.Context, v any) (*model.DriverConfigurationType, error) { + if v == nil { + return nil, nil + } + var res = new(model.DriverConfigurationType) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalODriverConfigurationType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverConfigurationType(ctx context.Context, sel ast.SelectionSet, v *model.DriverConfigurationType) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return v +} + +func (ec *executionContext) marshalODriverFileInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverFileInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.DriverFileInfo) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNDriverFileInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐDriverFileInfo(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOFloat2ᚖfloat64(ctx context.Context, v any) (*float64, error) { if v == nil { return nil, nil } @@ -46739,18 +53178,17 @@ func (ec *executionContext) marshalOFloat2ᚖfloat64(ctx context.Context, sel as if v == nil { return graphql.Null } + _ = sel res := graphql.MarshalFloatContext(*v) return graphql.WrapContextMarshaler(ctx, res) } -func (ec *executionContext) unmarshalOID2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { +func (ec *executionContext) unmarshalOID2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { if v == nil { return nil, nil } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]string, len(vSlice)) for i := range vSlice { @@ -46781,7 +53219,7 @@ func (ec *executionContext) marshalOID2ᚕstringᚄ(ctx context.Context, sel ast return ret } -func (ec *executionContext) unmarshalOID2ᚖstring(ctx context.Context, v interface{}) (*string, error) { +func (ec *executionContext) unmarshalOID2ᚖstring(ctx context.Context, v any) (*string, error) { if v == nil { return nil, nil } @@ -46793,11 +53231,13 @@ func (ec *executionContext) marshalOID2ᚖstring(ctx context.Context, sel ast.Se if v == nil { return graphql.Null } + _ = sel + _ = ctx res := graphql.MarshalID(*v) return res } -func (ec *executionContext) unmarshalOInt2ᚖint(ctx context.Context, v interface{}) (*int, error) { +func (ec *executionContext) unmarshalOInt2ᚖint(ctx context.Context, v any) (*int, error) { if v == nil { return nil, nil } @@ -46809,11 +53249,27 @@ func (ec *executionContext) marshalOInt2ᚖint(ctx context.Context, sel ast.Sele if v == nil { return graphql.Null } + _ = sel + _ = ctx res := graphql.MarshalInt(*v) return res } -func (ec *executionContext) unmarshalONetworkHandlerAuthType2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, v interface{}) (*model.NetworkHandlerAuthType, error) { +func (ec *executionContext) marshalONavigatorNodeFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeFilter(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorNodeFilter) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._NavigatorNodeFilter(ctx, sel, v) +} + +func (ec *executionContext) marshalONavigatorNodeInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNavigatorNodeInfo(ctx context.Context, sel ast.SelectionSet, v *model.NavigatorNodeInfo) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._NavigatorNodeInfo(ctx, sel, v) +} + +func (ec *executionContext) unmarshalONetworkHandlerAuthType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, v any) (*model.NetworkHandlerAuthType, error) { if v == nil { return nil, nil } @@ -46822,26 +53278,24 @@ func (ec *executionContext) unmarshalONetworkHandlerAuthType2ᚖdmsᚋinternal return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalONetworkHandlerAuthType2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerAuthType) graphql.Marshaler { +func (ec *executionContext) marshalONetworkHandlerAuthType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerAuthType(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerAuthType) graphql.Marshaler { if v == nil { return graphql.Null } return v } -func (ec *executionContext) unmarshalONetworkHandlerConfigInput2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx context.Context, v interface{}) ([]*model.NetworkHandlerConfigInput, error) { +func (ec *executionContext) unmarshalONetworkHandlerConfigInput2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInputᚄ(ctx context.Context, v any) ([]*model.NetworkHandlerConfigInput, error) { if v == nil { return nil, nil } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]*model.NetworkHandlerConfigInput, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNNetworkHandlerConfigInput2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput(ctx, vSlice[i]) + res[i], err = ec.unmarshalNNetworkHandlerConfigInput2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerConfigInput(ctx, vSlice[i]) if err != nil { return nil, err } @@ -46849,7 +53303,7 @@ func (ec *executionContext) unmarshalONetworkHandlerConfigInput2ᚕᚖdmsᚋinte return res, nil } -func (ec *executionContext) unmarshalONetworkHandlerType2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerType(ctx context.Context, v interface{}) (*model.NetworkHandlerType, error) { +func (ec *executionContext) unmarshalONetworkHandlerType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerType(ctx context.Context, v any) (*model.NetworkHandlerType, error) { if v == nil { return nil, nil } @@ -46858,14 +53312,14 @@ func (ec *executionContext) unmarshalONetworkHandlerType2ᚖdmsᚋinternalᚋpkg return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalONetworkHandlerType2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerType(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerType) graphql.Marshaler { +func (ec *executionContext) marshalONetworkHandlerType2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐNetworkHandlerType(ctx context.Context, sel ast.SelectionSet, v *model.NetworkHandlerType) graphql.Marshaler { if v == nil { return graphql.Null } return v } -func (ec *executionContext) unmarshalOObject2interface(ctx context.Context, v interface{}) (interface{}, error) { +func (ec *executionContext) unmarshalOObject2interface(ctx context.Context, v any) (any, error) { if v == nil { return nil, nil } @@ -46873,24 +53327,24 @@ func (ec *executionContext) unmarshalOObject2interface(ctx context.Context, v in return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalOObject2interface(ctx context.Context, sel ast.SelectionSet, v interface{}) graphql.Marshaler { +func (ec *executionContext) marshalOObject2interface(ctx context.Context, sel ast.SelectionSet, v any) graphql.Marshaler { if v == nil { return graphql.Null } + _ = sel + _ = ctx res := graphql.MarshalAny(v) return res } -func (ec *executionContext) unmarshalOObject2ᚕinterface(ctx context.Context, v interface{}) ([]interface{}, error) { +func (ec *executionContext) unmarshalOObject2ᚕinterface(ctx context.Context, v any) ([]any, error) { if v == nil { return nil, nil } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error - res := make([]interface{}, len(vSlice)) + res := make([]any, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) res[i], err = ec.unmarshalOObject2interface(ctx, vSlice[i]) @@ -46901,7 +53355,7 @@ func (ec *executionContext) unmarshalOObject2ᚕinterface(ctx context.Context, v return res, nil } -func (ec *executionContext) marshalOObject2ᚕinterface(ctx context.Context, sel ast.SelectionSet, v []interface{}) graphql.Marshaler { +func (ec *executionContext) marshalOObject2ᚕinterface(ctx context.Context, sel ast.SelectionSet, v []any) graphql.Marshaler { if v == nil { return graphql.Null } @@ -46913,16 +53367,14 @@ func (ec *executionContext) marshalOObject2ᚕinterface(ctx context.Context, sel return ret } -func (ec *executionContext) unmarshalOObject2ᚕᚕinterface(ctx context.Context, v interface{}) ([][]interface{}, error) { +func (ec *executionContext) unmarshalOObject2ᚕᚕinterface(ctx context.Context, v any) ([][]any, error) { if v == nil { return nil, nil } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error - res := make([][]interface{}, len(vSlice)) + res := make([][]any, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) res[i], err = ec.unmarshalOObject2ᚕinterface(ctx, vSlice[i]) @@ -46933,7 +53385,7 @@ func (ec *executionContext) unmarshalOObject2ᚕᚕinterface(ctx context.Context return res, nil } -func (ec *executionContext) marshalOObject2ᚕᚕinterface(ctx context.Context, sel ast.SelectionSet, v [][]interface{}) graphql.Marshaler { +func (ec *executionContext) marshalOObject2ᚕᚕinterface(ctx context.Context, sel ast.SelectionSet, v [][]any) graphql.Marshaler { if v == nil { return graphql.Null } @@ -46945,7 +53397,7 @@ func (ec *executionContext) marshalOObject2ᚕᚕinterface(ctx context.Context, return ret } -func (ec *executionContext) unmarshalOObjectPropertyFilter2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyFilter(ctx context.Context, v interface{}) (*model.ObjectPropertyFilter, error) { +func (ec *executionContext) unmarshalOObjectPropertyFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyFilter(ctx context.Context, v any) (*model.ObjectPropertyFilter, error) { if v == nil { return nil, nil } @@ -46953,7 +53405,7 @@ func (ec *executionContext) unmarshalOObjectPropertyFilter2ᚖdmsᚋinternalᚋp return &res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { +func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { if v == nil { return graphql.Null } @@ -46980,7 +53432,7 @@ func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpk if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalOObjectPropertyInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) + ret[i] = ec.marshalOObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -46994,7 +53446,7 @@ func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpk return ret } -func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { +func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfoᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.ObjectPropertyInfo) graphql.Marshaler { if v == nil { return graphql.Null } @@ -47021,7 +53473,7 @@ func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpk if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNObjectPropertyInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) + ret[i] = ec.marshalNObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx, sel, v[i]) } if isLen1 { f(i) @@ -47041,14 +53493,14 @@ func (ec *executionContext) marshalOObjectPropertyInfo2ᚕᚖdmsᚋinternalᚋpk return ret } -func (ec *executionContext) marshalOObjectPropertyInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v *model.ObjectPropertyInfo) graphql.Marshaler { +func (ec *executionContext) marshalOObjectPropertyInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐObjectPropertyInfo(ctx context.Context, sel ast.SelectionSet, v *model.ObjectPropertyInfo) graphql.Marshaler { if v == nil { return graphql.Null } return ec._ObjectPropertyInfo(ctx, sel, v) } -func (ec *executionContext) unmarshalOResultDataFormat2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, v interface{}) (*model.ResultDataFormat, error) { +func (ec *executionContext) unmarshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, v any) (*model.ResultDataFormat, error) { if v == nil { return nil, nil } @@ -47057,14 +53509,14 @@ func (ec *executionContext) unmarshalOResultDataFormat2ᚖdmsᚋinternalᚋpkg return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalOResultDataFormat2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, sel ast.SelectionSet, v *model.ResultDataFormat) graphql.Marshaler { +func (ec *executionContext) marshalOResultDataFormat2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐResultDataFormat(ctx context.Context, sel ast.SelectionSet, v *model.ResultDataFormat) graphql.Marshaler { if v == nil { return graphql.Null } return v } -func (ec *executionContext) marshalOSQLCompletionProposal2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, v []*model.SQLCompletionProposal) graphql.Marshaler { +func (ec *executionContext) marshalOSQLCompletionProposal2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, v []*model.SQLCompletionProposal) graphql.Marshaler { if v == nil { return graphql.Null } @@ -47091,7 +53543,7 @@ func (ec *executionContext) marshalOSQLCompletionProposal2ᚕᚖdmsᚋinternal if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalOSQLCompletionProposal2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal(ctx, sel, v[i]) + ret[i] = ec.marshalOSQLCompletionProposal2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal(ctx, sel, v[i]) } if isLen1 { f(i) @@ -47105,21 +53557,21 @@ func (ec *executionContext) marshalOSQLCompletionProposal2ᚕᚖdmsᚋinternal return ret } -func (ec *executionContext) marshalOSQLCompletionProposal2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, v *model.SQLCompletionProposal) graphql.Marshaler { +func (ec *executionContext) marshalOSQLCompletionProposal2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLCompletionProposal(ctx context.Context, sel ast.SelectionSet, v *model.SQLCompletionProposal) graphql.Marshaler { if v == nil { return graphql.Null } return ec._SQLCompletionProposal(ctx, sel, v) } -func (ec *executionContext) marshalOSQLContextInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLContextInfo) graphql.Marshaler { +func (ec *executionContext) marshalOSQLContextInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLContextInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLContextInfo) graphql.Marshaler { if v == nil { return graphql.Null } return ec._SQLContextInfo(ctx, sel, v) } -func (ec *executionContext) unmarshalOSQLDataFilter2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter(ctx context.Context, v interface{}) (*model.SQLDataFilter, error) { +func (ec *executionContext) unmarshalOSQLDataFilter2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilter(ctx context.Context, v any) (*model.SQLDataFilter, error) { if v == nil { return nil, nil } @@ -47127,19 +53579,17 @@ func (ec *executionContext) unmarshalOSQLDataFilter2ᚖdmsᚋinternalᚋpkgᚋcl return &res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx context.Context, v interface{}) ([]*model.SQLDataFilterConstraint, error) { +func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx context.Context, v any) ([]*model.SQLDataFilterConstraint, error) { if v == nil { return nil, nil } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]*model.SQLDataFilterConstraint, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalOSQLDataFilterConstraint2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx, vSlice[i]) + res[i], err = ec.unmarshalOSQLDataFilterConstraint2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx, vSlice[i]) if err != nil { return nil, err } @@ -47147,7 +53597,7 @@ func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚕᚖdmsᚋintern return res, nil } -func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx context.Context, v interface{}) (*model.SQLDataFilterConstraint, error) { +func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDataFilterConstraint(ctx context.Context, v any) (*model.SQLDataFilterConstraint, error) { if v == nil { return nil, nil } @@ -47155,21 +53605,14 @@ func (ec *executionContext) unmarshalOSQLDataFilterConstraint2ᚖdmsᚋinternal return &res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalOSQLDialectInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDialectInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLDialectInfo) graphql.Marshaler { +func (ec *executionContext) marshalOSQLDialectInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLDialectInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLDialectInfo) graphql.Marshaler { if v == nil { return graphql.Null } return ec._SQLDialectInfo(ctx, sel, v) } -func (ec *executionContext) marshalOSQLExecuteInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLExecuteInfo(ctx context.Context, sel ast.SelectionSet, v *model.SQLExecuteInfo) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLExecuteInfo(ctx, sel, v) -} - -func (ec *executionContext) marshalOSQLResultColumn2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn(ctx context.Context, sel ast.SelectionSet, v []*model.SQLResultColumn) graphql.Marshaler { +func (ec *executionContext) marshalOSQLResultColumn2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn(ctx context.Context, sel ast.SelectionSet, v []*model.SQLResultColumn) graphql.Marshaler { if v == nil { return graphql.Null } @@ -47196,7 +53639,7 @@ func (ec *executionContext) marshalOSQLResultColumn2ᚕᚖdmsᚋinternalᚋpkg if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalOSQLResultColumn2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn(ctx, sel, v[i]) + ret[i] = ec.marshalOSQLResultColumn2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn(ctx, sel, v[i]) } if isLen1 { f(i) @@ -47210,26 +53653,24 @@ func (ec *executionContext) marshalOSQLResultColumn2ᚕᚖdmsᚋinternalᚋpkg return ret } -func (ec *executionContext) marshalOSQLResultColumn2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn(ctx context.Context, sel ast.SelectionSet, v *model.SQLResultColumn) graphql.Marshaler { +func (ec *executionContext) marshalOSQLResultColumn2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultColumn(ctx context.Context, sel ast.SelectionSet, v *model.SQLResultColumn) graphql.Marshaler { if v == nil { return graphql.Null } return ec._SQLResultColumn(ctx, sel, v) } -func (ec *executionContext) unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx context.Context, v interface{}) ([]*model.SQLResultRow, error) { +func (ec *executionContext) unmarshalOSQLResultRow2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowᚄ(ctx context.Context, v any) ([]*model.SQLResultRow, error) { if v == nil { return nil, nil } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]*model.SQLResultRow, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNSQLResultRow2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow(ctx, vSlice[i]) + res[i], err = ec.unmarshalNSQLResultRow2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRow(ctx, vSlice[i]) if err != nil { return nil, err } @@ -47237,21 +53678,7 @@ func (ec *executionContext) unmarshalOSQLResultRow2ᚕᚖdmsᚋinternalᚋpkgᚋ return res, nil } -func (ec *executionContext) marshalOSQLResultSet2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultSet(ctx context.Context, sel ast.SelectionSet, v *model.SQLResultSet) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._SQLResultSet(ctx, sel, v) -} - -func (ec *executionContext) marshalOServerError2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError(ctx context.Context, sel ast.SelectionSet, v *model.ServerError) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._ServerError(ctx, sel, v) -} - -func (ec *executionContext) marshalOServerMessage2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerMessage(ctx context.Context, sel ast.SelectionSet, v []*model.ServerMessage) graphql.Marshaler { +func (ec *executionContext) marshalOSQLResultRowMetaData2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowMetaData(ctx context.Context, sel ast.SelectionSet, v []*model.SQLResultRowMetaData) graphql.Marshaler { if v == nil { return graphql.Null } @@ -47278,7 +53705,7 @@ func (ec *executionContext) marshalOServerMessage2ᚕᚖdmsᚋinternalᚋpkgᚋc if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalOServerMessage2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerMessage(ctx, sel, v[i]) + ret[i] = ec.marshalOSQLResultRowMetaData2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowMetaData(ctx, sel, v[i]) } if isLen1 { f(i) @@ -47292,21 +53719,33 @@ func (ec *executionContext) marshalOServerMessage2ᚕᚖdmsᚋinternalᚋpkgᚋc return ret } -func (ec *executionContext) marshalOServerMessage2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerMessage(ctx context.Context, sel ast.SelectionSet, v *model.ServerMessage) graphql.Marshaler { +func (ec *executionContext) marshalOSQLResultRowMetaData2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultRowMetaData(ctx context.Context, sel ast.SelectionSet, v *model.SQLResultRowMetaData) graphql.Marshaler { if v == nil { return graphql.Null } - return ec._ServerMessage(ctx, sel, v) + return ec._SQLResultRowMetaData(ctx, sel, v) } -func (ec *executionContext) unmarshalOString2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { +func (ec *executionContext) marshalOSQLResultSet2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐSQLResultSet(ctx context.Context, sel ast.SelectionSet, v *model.SQLResultSet) graphql.Marshaler { if v == nil { - return nil, nil + return graphql.Null } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) + return ec._SQLResultSet(ctx, sel, v) +} + +func (ec *executionContext) marshalOServerError2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐServerError(ctx context.Context, sel ast.SelectionSet, v *model.ServerError) graphql.Marshaler { + if v == nil { + return graphql.Null } + return ec._ServerError(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOString2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { + if v == nil { + return nil, nil + } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]string, len(vSlice)) for i := range vSlice { @@ -47337,14 +53776,12 @@ func (ec *executionContext) marshalOString2ᚕstringᚄ(ctx context.Context, sel return ret } -func (ec *executionContext) unmarshalOString2ᚕᚖstring(ctx context.Context, v interface{}) ([]*string, error) { +func (ec *executionContext) unmarshalOString2ᚕᚖstring(ctx context.Context, v any) ([]*string, error) { if v == nil { return nil, nil } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]*string, len(vSlice)) for i := range vSlice { @@ -47369,7 +53806,7 @@ func (ec *executionContext) marshalOString2ᚕᚖstring(ctx context.Context, sel return ret } -func (ec *executionContext) unmarshalOString2ᚖstring(ctx context.Context, v interface{}) (*string, error) { +func (ec *executionContext) unmarshalOString2ᚖstring(ctx context.Context, v any) (*string, error) { if v == nil { return nil, nil } @@ -47381,11 +53818,13 @@ func (ec *executionContext) marshalOString2ᚖstring(ctx context.Context, sel as if v == nil { return graphql.Null } + _ = sel + _ = ctx res := graphql.MarshalString(*v) return res } -func (ec *executionContext) marshalOUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.UserAuthToken) graphql.Marshaler { +func (ec *executionContext) marshalOUserAuthToken2ᚕᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthTokenᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.UserAuthToken) graphql.Marshaler { if v == nil { return graphql.Null } @@ -47412,7 +53851,7 @@ func (ec *executionContext) marshalOUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋc if !isLen1 { defer wg.Done() } - ret[i] = ec.marshalNUserAuthToken2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthToken(ctx, sel, v[i]) + ret[i] = ec.marshalNUserAuthToken2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserAuthToken(ctx, sel, v[i]) } if isLen1 { f(i) @@ -47432,61 +53871,13 @@ func (ec *executionContext) marshalOUserAuthToken2ᚕᚖdmsᚋinternalᚋpkgᚋc return ret } -func (ec *executionContext) marshalOUserInfo2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserInfo(ctx context.Context, sel ast.SelectionSet, v *model.UserInfo) graphql.Marshaler { +func (ec *executionContext) marshalOUserInfo2ᚖgithubᚗcomᚋactiontechᚋdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐUserInfo(ctx context.Context, sel ast.SelectionSet, v *model.UserInfo) graphql.Marshaler { if v == nil { return graphql.Null } return ec._UserInfo(ctx, sel, v) } -func (ec *executionContext) marshalOWebServiceConfig2ᚕᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebServiceConfig(ctx context.Context, sel ast.SelectionSet, v []*model.WebServiceConfig) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - var wg sync.WaitGroup - isLen1 := len(v) == 1 - if !isLen1 { - wg.Add(len(v)) - } - for i := range v { - i := i - fc := &graphql.FieldContext{ - Index: &i, - Result: &v[i], - } - ctx := graphql.WithFieldContext(ctx, fc) - f := func(i int) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = nil - } - }() - if !isLen1 { - defer wg.Done() - } - ret[i] = ec.marshalOWebServiceConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebServiceConfig(ctx, sel, v[i]) - } - if isLen1 { - f(i) - } else { - go f(i) - } - - } - wg.Wait() - - return ret -} - -func (ec *executionContext) marshalOWebServiceConfig2ᚖdmsᚋinternalᚋpkgᚋcloudbeaverᚋmodelᚐWebServiceConfig(ctx context.Context, sel ast.SelectionSet, v *model.WebServiceConfig) graphql.Marshaler { - if v == nil { - return graphql.Null - } - return ec._WebServiceConfig(ctx, sel, v) -} - func (ec *executionContext) marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.EnumValue) graphql.Marshaler { if v == nil { return graphql.Null diff --git a/internal/pkg/cloudbeaver/resolver/schema_gen.go b/internal/pkg/cloudbeaver/resolver/schema_gen.go index c9ef8df5a..d9e235bac 100644 --- a/internal/pkg/cloudbeaver/resolver/schema_gen.go +++ b/internal/pkg/cloudbeaver/resolver/schema_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 // Mutation returns MutationResolver implementation. func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} } diff --git a/internal/pkg/cloudbeaver/resolver/service.admin_gen.go b/internal/pkg/cloudbeaver/resolver/service.admin_gen.go index 4eb5e004e..72ba8f283 100644 --- a/internal/pkg/cloudbeaver/resolver/service.admin_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.admin_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -10,14 +11,24 @@ import ( "github.com/actiontech/dms/internal/pkg/cloudbeaver/model" ) +// AdminUpdateProductConfiguration is the resolver for the adminUpdateProductConfiguration field. +func (r *mutationResolver) AdminUpdateProductConfiguration(ctx context.Context, configuration any) (bool, error) { + panic(fmt.Errorf("not implemented: AdminUpdateProductConfiguration - adminUpdateProductConfiguration")) +} + +// AdminUserInfo is the resolver for the adminUserInfo field. +func (r *queryResolver) AdminUserInfo(ctx context.Context, userID string) (*model.AdminUserInfo, error) { + panic(fmt.Errorf("not implemented: AdminUserInfo - adminUserInfo")) +} + // ListUsers is the resolver for the listUsers field. -func (r *queryResolver) ListUsers(ctx context.Context, userID *string) ([]*model.AdminUserInfo, error) { +func (r *queryResolver) ListUsers(ctx context.Context, page model.PageInput, filter model.AdminUserFilterInput) ([]*model.AdminUserInfo, error) { panic(fmt.Errorf("not implemented: ListUsers - listUsers")) } -// ListRoles is the resolver for the listRoles field. -func (r *queryResolver) ListRoles(ctx context.Context, roleID *string) ([]*model.AdminRoleInfo, error) { - panic(fmt.Errorf("not implemented: ListRoles - listRoles")) +// ListTeams is the resolver for the listTeams field. +func (r *queryResolver) ListTeams(ctx context.Context, teamID *string) ([]*model.AdminTeamInfo, error) { + panic(fmt.Errorf("not implemented: ListTeams - listTeams")) } // ListPermissions is the resolver for the listPermissions field. @@ -25,8 +36,23 @@ func (r *queryResolver) ListPermissions(ctx context.Context) ([]*model.AdminPerm panic(fmt.Errorf("not implemented: ListPermissions - listPermissions")) } +// ListAuthRoles is the resolver for the listAuthRoles field. +func (r *queryResolver) ListAuthRoles(ctx context.Context) ([]string, error) { + panic(fmt.Errorf("not implemented: ListAuthRoles - listAuthRoles")) +} + +// ListTeamRoles is the resolver for the listTeamRoles field. +func (r *queryResolver) ListTeamRoles(ctx context.Context) ([]string, error) { + panic(fmt.Errorf("not implemented: ListTeamRoles - listTeamRoles")) +} + +// ListTeamMetaParameters is the resolver for the listTeamMetaParameters field. +func (r *queryResolver) ListTeamMetaParameters(ctx context.Context) ([]*model.ObjectPropertyInfo, error) { + panic(fmt.Errorf("not implemented: ListTeamMetaParameters - listTeamMetaParameters")) +} + // CreateUser is the resolver for the createUser field. -func (r *queryResolver) CreateUser(ctx context.Context, userID string) (*model.AdminUserInfo, error) { +func (r *queryResolver) CreateUser(ctx context.Context, userID string, enabled bool, authRole *string) (*model.AdminUserInfo, error) { panic(fmt.Errorf("not implemented: CreateUser - createUser")) } @@ -35,49 +61,59 @@ func (r *queryResolver) DeleteUser(ctx context.Context, userID string) (*bool, e panic(fmt.Errorf("not implemented: DeleteUser - deleteUser")) } -// CreateRole is the resolver for the createRole field. -func (r *queryResolver) CreateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) { - panic(fmt.Errorf("not implemented: CreateRole - createRole")) +// CreateTeam is the resolver for the createTeam field. +func (r *queryResolver) CreateTeam(ctx context.Context, teamID string, teamName *string, description *string) (*model.AdminTeamInfo, error) { + panic(fmt.Errorf("not implemented: CreateTeam - createTeam")) } -// UpdateRole is the resolver for the updateRole field. -func (r *queryResolver) UpdateRole(ctx context.Context, roleID string, roleName *string, description *string) (*model.AdminRoleInfo, error) { - panic(fmt.Errorf("not implemented: UpdateRole - updateRole")) +// UpdateTeam is the resolver for the updateTeam field. +func (r *queryResolver) UpdateTeam(ctx context.Context, teamID string, teamName *string, description *string) (*model.AdminTeamInfo, error) { + panic(fmt.Errorf("not implemented: UpdateTeam - updateTeam")) } -// DeleteRole is the resolver for the deleteRole field. -func (r *queryResolver) DeleteRole(ctx context.Context, roleID string) (*bool, error) { - panic(fmt.Errorf("not implemented: DeleteRole - deleteRole")) +// DeleteTeam is the resolver for the deleteTeam field. +func (r *queryResolver) DeleteTeam(ctx context.Context, teamID string, force *bool) (*bool, error) { + panic(fmt.Errorf("not implemented: DeleteTeam - deleteTeam")) } -// GrantUserRole is the resolver for the grantUserRole field. -func (r *queryResolver) GrantUserRole(ctx context.Context, userID string, roleID string) (*bool, error) { - panic(fmt.Errorf("not implemented: GrantUserRole - grantUserRole")) +// GrantUserTeam is the resolver for the grantUserTeam field. +func (r *queryResolver) GrantUserTeam(ctx context.Context, userID string, teamID string) (*bool, error) { + panic(fmt.Errorf("not implemented: GrantUserTeam - grantUserTeam")) } -// RevokeUserRole is the resolver for the revokeUserRole field. -func (r *queryResolver) RevokeUserRole(ctx context.Context, userID string, roleID string) (*bool, error) { - panic(fmt.Errorf("not implemented: RevokeUserRole - revokeUserRole")) +// RevokeUserTeam is the resolver for the revokeUserTeam field. +func (r *queryResolver) RevokeUserTeam(ctx context.Context, userID string, teamID string) (*bool, error) { + panic(fmt.Errorf("not implemented: RevokeUserTeam - revokeUserTeam")) } // SetSubjectPermissions is the resolver for the setSubjectPermissions field. -func (r *queryResolver) SetSubjectPermissions(ctx context.Context, roleID string, permissions []string) ([]*model.AdminPermissionInfo, error) { +func (r *queryResolver) SetSubjectPermissions(ctx context.Context, subjectID string, permissions []string) ([]*model.AdminPermissionInfo, error) { panic(fmt.Errorf("not implemented: SetSubjectPermissions - setSubjectPermissions")) } // SetUserCredentials is the resolver for the setUserCredentials field. -func (r *queryResolver) SetUserCredentials(ctx context.Context, userID string, providerID string, credentials interface{}) (*bool, error) { +func (r *queryResolver) SetUserCredentials(ctx context.Context, userID string, providerID string, credentials any) (*bool, error) { panic(fmt.Errorf("not implemented: SetUserCredentials - setUserCredentials")) } +// DeleteUserCredentials is the resolver for the deleteUserCredentials field. +func (r *queryResolver) DeleteUserCredentials(ctx context.Context, userID string, providerID string) (*bool, error) { + panic(fmt.Errorf("not implemented: DeleteUserCredentials - deleteUserCredentials")) +} + // EnableUser is the resolver for the enableUser field. func (r *queryResolver) EnableUser(ctx context.Context, userID string, enabled bool) (*bool, error) { panic(fmt.Errorf("not implemented: EnableUser - enableUser")) } -// AllConnections is the resolver for the allConnections field. -func (r *queryResolver) AllConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: AllConnections - allConnections")) +// SetUserAuthRole is the resolver for the setUserAuthRole field. +func (r *queryResolver) SetUserAuthRole(ctx context.Context, userID string, authRole *string) (*bool, error) { + panic(fmt.Errorf("not implemented: SetUserAuthRole - setUserAuthRole")) +} + +// SetUserTeamRole is the resolver for the setUserTeamRole field. +func (r *queryResolver) SetUserTeamRole(ctx context.Context, userID string, teamID string, teamRole *string) (*bool, error) { + panic(fmt.Errorf("not implemented: SetUserTeamRole - setUserTeamRole")) } // SearchConnections is the resolver for the searchConnections field. @@ -85,38 +121,28 @@ func (r *queryResolver) SearchConnections(ctx context.Context, hostNames []strin panic(fmt.Errorf("not implemented: SearchConnections - searchConnections")) } -// CreateConnectionConfiguration is the resolver for the createConnectionConfiguration field. -func (r *queryResolver) CreateConnectionConfiguration(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CreateConnectionConfiguration - createConnectionConfiguration")) -} - -// CopyConnectionConfiguration is the resolver for the copyConnectionConfiguration field. -func (r *queryResolver) CopyConnectionConfiguration(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CopyConnectionConfiguration - copyConnectionConfiguration")) -} - -// UpdateConnectionConfiguration is the resolver for the updateConnectionConfiguration field. -func (r *queryResolver) UpdateConnectionConfiguration(ctx context.Context, id string, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: UpdateConnectionConfiguration - updateConnectionConfiguration")) -} - -// DeleteConnectionConfiguration is the resolver for the deleteConnectionConfiguration field. -func (r *queryResolver) DeleteConnectionConfiguration(ctx context.Context, id string) (*bool, error) { - panic(fmt.Errorf("not implemented: DeleteConnectionConfiguration - deleteConnectionConfiguration")) -} - // GetConnectionSubjectAccess is the resolver for the getConnectionSubjectAccess field. -func (r *queryResolver) GetConnectionSubjectAccess(ctx context.Context, connectionID *string) ([]*model.AdminConnectionGrantInfo, error) { +func (r *queryResolver) GetConnectionSubjectAccess(ctx context.Context, projectID string, connectionID *string) ([]*model.AdminConnectionGrantInfo, error) { panic(fmt.Errorf("not implemented: GetConnectionSubjectAccess - getConnectionSubjectAccess")) } // SetConnectionSubjectAccess is the resolver for the setConnectionSubjectAccess field. -func (r *queryResolver) SetConnectionSubjectAccess(ctx context.Context, connectionID string, subjects []string) (*bool, error) { +func (r *queryResolver) SetConnectionSubjectAccess(ctx context.Context, projectID string, connectionID string, subjects []string) (*bool, error) { panic(fmt.Errorf("not implemented: SetConnectionSubjectAccess - setConnectionSubjectAccess")) } +// AddConnectionsAccess is the resolver for the addConnectionsAccess field. +func (r *queryResolver) AddConnectionsAccess(ctx context.Context, projectID string, connectionIds []string, subjects []string) (*bool, error) { + panic(fmt.Errorf("not implemented: AddConnectionsAccess - addConnectionsAccess")) +} + +// DeleteConnectionsAccess is the resolver for the deleteConnectionsAccess field. +func (r *queryResolver) DeleteConnectionsAccess(ctx context.Context, projectID string, connectionIds []string, subjects []string) (*bool, error) { + panic(fmt.Errorf("not implemented: DeleteConnectionsAccess - deleteConnectionsAccess")) +} + // GetSubjectConnectionAccess is the resolver for the getSubjectConnectionAccess field. -func (r *queryResolver) GetSubjectConnectionAccess(ctx context.Context, subjectID *string) ([]*model.AdminConnectionGrantInfo, error) { +func (r *queryResolver) GetSubjectConnectionAccess(ctx context.Context, subjectID string) ([]*model.AdminConnectionGrantInfo, error) { panic(fmt.Errorf("not implemented: GetSubjectConnectionAccess - getSubjectConnectionAccess")) } @@ -141,7 +167,7 @@ func (r *queryResolver) ListAuthProviderConfigurations(ctx context.Context, prov } // SaveAuthProviderConfiguration is the resolver for the saveAuthProviderConfiguration field. -func (r *queryResolver) SaveAuthProviderConfiguration(ctx context.Context, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters interface{}) (*model.AdminAuthProviderConfiguration, error) { +func (r *queryResolver) SaveAuthProviderConfiguration(ctx context.Context, providerID string, id string, displayName *string, disabled *bool, iconURL *string, description *string, parameters any) (*model.AdminAuthProviderConfiguration, error) { panic(fmt.Errorf("not implemented: SaveAuthProviderConfiguration - saveAuthProviderConfiguration")) } @@ -161,10 +187,15 @@ func (r *queryResolver) DeleteUserMetaParameter(ctx context.Context, id string) } // SetUserMetaParameterValues is the resolver for the setUserMetaParameterValues field. -func (r *queryResolver) SetUserMetaParameterValues(ctx context.Context, userID string, parameters interface{}) (bool, error) { +func (r *queryResolver) SetUserMetaParameterValues(ctx context.Context, userID string, parameters any) (bool, error) { panic(fmt.Errorf("not implemented: SetUserMetaParameterValues - setUserMetaParameterValues")) } +// SetTeamMetaParameterValues is the resolver for the setTeamMetaParameterValues field. +func (r *queryResolver) SetTeamMetaParameterValues(ctx context.Context, teamID string, parameters any) (bool, error) { + panic(fmt.Errorf("not implemented: SetTeamMetaParameterValues - setTeamMetaParameterValues")) +} + // ConfigureServer is the resolver for the configureServer field. func (r *queryResolver) ConfigureServer(ctx context.Context, configuration model.ServerConfigInput) (bool, error) { panic(fmt.Errorf("not implemented: ConfigureServer - configureServer")) diff --git a/internal/pkg/cloudbeaver/resolver/service.auth_gen.go b/internal/pkg/cloudbeaver/resolver/service.auth_gen.go index 26ac07bb2..c3307a14d 100644 --- a/internal/pkg/cloudbeaver/resolver/service.auth_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.auth_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -11,15 +12,30 @@ import ( ) // SetUserConfigurationParameter is the resolver for the setUserConfigurationParameter field. -func (r *mutationResolver) SetUserConfigurationParameter(ctx context.Context, name string, value interface{}) (bool, error) { +func (r *mutationResolver) SetUserConfigurationParameter(ctx context.Context, name string, value any) (bool, error) { panic(fmt.Errorf("not implemented: SetUserConfigurationParameter - setUserConfigurationParameter")) } +// SetUserPreferences is the resolver for the setUserPreferences field. +func (r *mutationResolver) SetUserPreferences(ctx context.Context, preferences any) (*model.UserInfo, error) { + panic(fmt.Errorf("not implemented: SetUserPreferences - setUserPreferences")) +} + +// FederatedLogin is the resolver for the federatedLogin field. +func (r *mutationResolver) FederatedLogin(ctx context.Context, provider string, configuration *string, linkUser *bool, forceSessionsLogout *bool) (*model.FederatedAuthInfo, error) { + panic(fmt.Errorf("not implemented: FederatedLogin - federatedLogin")) +} + // AuthLogin is the resolver for the authLogin field. -func (r *queryResolver) AuthLogin(ctx context.Context, provider string, configuration *string, credentials interface{}, linkUser *bool) (*model.AuthInfo, error) { +func (r *queryResolver) AuthLogin(ctx context.Context, provider string, configuration *string, credentials any, linkUser *bool, forceSessionsLogout *bool) (*model.AuthInfo, error) { panic(fmt.Errorf("not implemented: AuthLogin - authLogin")) } +// FederatedAuthTaskResult is the resolver for the federatedAuthTaskResult field. +func (r *queryResolver) FederatedAuthTaskResult(ctx context.Context, taskID string) (*model.FederatedAuthResult, error) { + panic(fmt.Errorf("not implemented: FederatedAuthTaskResult - federatedAuthTaskResult")) +} + // AuthUpdateStatus is the resolver for the authUpdateStatus field. func (r *queryResolver) AuthUpdateStatus(ctx context.Context, authID string, linkUser *bool) (*model.AuthInfo, error) { panic(fmt.Errorf("not implemented: AuthUpdateStatus - authUpdateStatus")) @@ -30,6 +46,11 @@ func (r *queryResolver) AuthLogout(ctx context.Context, provider *string, config panic(fmt.Errorf("not implemented: AuthLogout - authLogout")) } +// AuthLogoutExtended is the resolver for the authLogoutExtended field. +func (r *queryResolver) AuthLogoutExtended(ctx context.Context, provider *string, configuration *string) (*model.LogoutInfo, error) { + panic(fmt.Errorf("not implemented: AuthLogoutExtended - authLogoutExtended")) +} + // ActiveUser is the resolver for the activeUser field. func (r *queryResolver) ActiveUser(ctx context.Context) (*model.UserInfo, error) { panic(fmt.Errorf("not implemented: ActiveUser - activeUser")) diff --git a/internal/pkg/cloudbeaver/resolver/service.core_gen.go b/internal/pkg/cloudbeaver/resolver/service.core_gen.go index cc5d31e4f..3a165e26c 100644 --- a/internal/pkg/cloudbeaver/resolver/service.core_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.core_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -25,6 +26,11 @@ func (r *mutationResolver) TouchSession(ctx context.Context) (*bool, error) { panic(fmt.Errorf("not implemented: TouchSession - touchSession")) } +// UpdateSession is the resolver for the updateSession field. +func (r *mutationResolver) UpdateSession(ctx context.Context) (*model.SessionInfo, error) { + panic(fmt.Errorf("not implemented: UpdateSession - updateSession")) +} + // RefreshSessionConnections is the resolver for the refreshSessionConnections field. func (r *mutationResolver) RefreshSessionConnections(ctx context.Context) (*bool, error) { panic(fmt.Errorf("not implemented: RefreshSessionConnections - refreshSessionConnections")) @@ -36,42 +42,37 @@ func (r *mutationResolver) ChangeSessionLanguage(ctx context.Context, locale *st } // CreateConnection is the resolver for the createConnection field. -func (r *mutationResolver) CreateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { +func (r *mutationResolver) CreateConnection(ctx context.Context, config model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: CreateConnection - createConnection")) } // UpdateConnection is the resolver for the updateConnection field. -func (r *mutationResolver) UpdateConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { +func (r *mutationResolver) UpdateConnection(ctx context.Context, config model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: UpdateConnection - updateConnection")) } // DeleteConnection is the resolver for the deleteConnection field. -func (r *mutationResolver) DeleteConnection(ctx context.Context, id string) (bool, error) { +func (r *mutationResolver) DeleteConnection(ctx context.Context, id string, projectID *string) (bool, error) { panic(fmt.Errorf("not implemented: DeleteConnection - deleteConnection")) } -// CreateConnectionFromTemplate is the resolver for the createConnectionFromTemplate field. -func (r *mutationResolver) CreateConnectionFromTemplate(ctx context.Context, templateID string, connectionName *string) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: CreateConnectionFromTemplate - createConnectionFromTemplate")) -} - // CreateConnectionFolder is the resolver for the createConnectionFolder field. -func (r *mutationResolver) CreateConnectionFolder(ctx context.Context, parentFolderPath *string, folderName string) (*model.ConnectionFolderInfo, error) { +func (r *mutationResolver) CreateConnectionFolder(ctx context.Context, parentFolderPath *string, folderName string, projectID *string) (*model.ConnectionFolderInfo, error) { panic(fmt.Errorf("not implemented: CreateConnectionFolder - createConnectionFolder")) } // DeleteConnectionFolder is the resolver for the deleteConnectionFolder field. -func (r *mutationResolver) DeleteConnectionFolder(ctx context.Context, folderPath string) (bool, error) { +func (r *mutationResolver) DeleteConnectionFolder(ctx context.Context, folderPath string, projectID *string) (bool, error) { panic(fmt.Errorf("not implemented: DeleteConnectionFolder - deleteConnectionFolder")) } // CopyConnectionFromNode is the resolver for the copyConnectionFromNode field. -func (r *mutationResolver) CopyConnectionFromNode(ctx context.Context, nodePath string, config *model.ConnectionConfig) (*model.ConnectionInfo, error) { +func (r *mutationResolver) CopyConnectionFromNode(ctx context.Context, nodePath string, config *model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: CopyConnectionFromNode - copyConnectionFromNode")) } // TestConnection is the resolver for the testConnection field. -func (r *mutationResolver) TestConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { +func (r *mutationResolver) TestConnection(ctx context.Context, config model.ConnectionConfig, projectID *string) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: TestConnection - testConnection")) } @@ -81,17 +82,17 @@ func (r *mutationResolver) TestNetworkHandler(ctx context.Context, config model. } // InitConnection is the resolver for the initConnection field. -func (r *mutationResolver) InitConnection(ctx context.Context, id string, credentials interface{}, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool) (*model.ConnectionInfo, error) { +func (r *mutationResolver) InitConnection(ctx context.Context, id string, projectID *string, credentials any, networkCredentials []*model.NetworkHandlerConfigInput, saveCredentials *bool, sharedCredentials *bool, selectedSecretID *string) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: InitConnection - initConnection")) } // CloseConnection is the resolver for the closeConnection field. -func (r *mutationResolver) CloseConnection(ctx context.Context, id string) (*model.ConnectionInfo, error) { +func (r *mutationResolver) CloseConnection(ctx context.Context, id string, projectID *string) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: CloseConnection - closeConnection")) } // SetConnectionNavigatorSettings is the resolver for the setConnectionNavigatorSettings field. -func (r *mutationResolver) SetConnectionNavigatorSettings(ctx context.Context, id string, settings model.NavigatorSettingsInput) (*model.ConnectionInfo, error) { +func (r *mutationResolver) SetConnectionNavigatorSettings(ctx context.Context, id string, projectID *string, settings model.NavigatorSettingsInput) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: SetConnectionNavigatorSettings - setConnectionNavigatorSettings")) } @@ -105,19 +106,19 @@ func (r *mutationResolver) AsyncTaskInfo(ctx context.Context, id string, removeO panic(fmt.Errorf("not implemented: AsyncTaskInfo - asyncTaskInfo")) } -// OpenConnection is the resolver for the openConnection field. -func (r *mutationResolver) OpenConnection(ctx context.Context, config model.ConnectionConfig) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: OpenConnection - openConnection")) +// ServerConfig is the resolver for the serverConfig field. +func (r *queryResolver) ServerConfig(ctx context.Context) (*model.ServerConfig, error) { + panic(fmt.Errorf("not implemented: ServerConfig - serverConfig")) } -// AsyncTaskStatus is the resolver for the asyncTaskStatus field. -func (r *mutationResolver) AsyncTaskStatus(ctx context.Context, id string) (*model.AsyncTaskInfo, error) { - panic(fmt.Errorf("not implemented: AsyncTaskStatus - asyncTaskStatus")) +// SystemInfo is the resolver for the systemInfo field. +func (r *queryResolver) SystemInfo(ctx context.Context) ([]*model.ObjectPropertyInfo, error) { + panic(fmt.Errorf("not implemented: SystemInfo - systemInfo")) } -// ServerConfig is the resolver for the serverConfig field. -func (r *queryResolver) ServerConfig(ctx context.Context) (*model.ServerConfig, error) { - panic(fmt.Errorf("not implemented: ServerConfig - serverConfig")) +// ProductSettings is the resolver for the productSettings field. +func (r *queryResolver) ProductSettings(ctx context.Context) (*model.ProductSettings, error) { + panic(fmt.Errorf("not implemented: ProductSettings - productSettings")) } // SessionState is the resolver for the sessionState field. @@ -146,30 +147,25 @@ func (r *queryResolver) NetworkHandlers(ctx context.Context) ([]*model.NetworkHa } // UserConnections is the resolver for the userConnections field. -func (r *queryResolver) UserConnections(ctx context.Context, id *string) ([]*model.ConnectionInfo, error) { +func (r *queryResolver) UserConnections(ctx context.Context, projectID *string, id *string, projectIds []string) ([]*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: UserConnections - userConnections")) } -// TemplateConnections is the resolver for the templateConnections field. -func (r *queryResolver) TemplateConnections(ctx context.Context) ([]*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: TemplateConnections - templateConnections")) -} - // ConnectionFolders is the resolver for the connectionFolders field. -func (r *queryResolver) ConnectionFolders(ctx context.Context, path *string) ([]*model.ConnectionFolderInfo, error) { +func (r *queryResolver) ConnectionFolders(ctx context.Context, projectID *string, path *string) ([]*model.ConnectionFolderInfo, error) { panic(fmt.Errorf("not implemented: ConnectionFolders - connectionFolders")) } -// ConnectionState is the resolver for the connectionState field. -func (r *queryResolver) ConnectionState(ctx context.Context, id string) (*model.ConnectionInfo, error) { - panic(fmt.Errorf("not implemented: ConnectionState - connectionState")) -} - // ConnectionInfo is the resolver for the connectionInfo field. -func (r *queryResolver) ConnectionInfo(ctx context.Context, id string) (*model.ConnectionInfo, error) { +func (r *queryResolver) ConnectionInfo(ctx context.Context, projectID string, id string) (*model.ConnectionInfo, error) { panic(fmt.Errorf("not implemented: ConnectionInfo - connectionInfo")) } +// ListProjects is the resolver for the listProjects field. +func (r *queryResolver) ListProjects(ctx context.Context) ([]*model.ProjectInfo, error) { + panic(fmt.Errorf("not implemented: ListProjects - listProjects")) +} + // ReadSessionLog is the resolver for the readSessionLog field. func (r *queryResolver) ReadSessionLog(ctx context.Context, maxEntries *int, clearEntries *bool) ([]*model.LogEntry, error) { panic(fmt.Errorf("not implemented: ReadSessionLog - readSessionLog")) diff --git a/internal/pkg/cloudbeaver/resolver/service.data.transfer_gen.go b/internal/pkg/cloudbeaver/resolver/service.data.transfer_gen.go index 7cf5ebbb7..8ff33f4f9 100644 --- a/internal/pkg/cloudbeaver/resolver/service.data.transfer_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.data.transfer_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -15,13 +16,23 @@ func (r *queryResolver) DataTransferAvailableStreamProcessors(ctx context.Contex panic(fmt.Errorf("not implemented: DataTransferAvailableStreamProcessors - dataTransferAvailableStreamProcessors")) } +// DataTransferAvailableImportStreamProcessors is the resolver for the dataTransferAvailableImportStreamProcessors field. +func (r *queryResolver) DataTransferAvailableImportStreamProcessors(ctx context.Context) ([]*model.DataTransferProcessorInfo, error) { + panic(fmt.Errorf("not implemented: DataTransferAvailableImportStreamProcessors - dataTransferAvailableImportStreamProcessors")) +} + +// DataTransferDefaultExportSettings is the resolver for the dataTransferDefaultExportSettings field. +func (r *queryResolver) DataTransferDefaultExportSettings(ctx context.Context) (*model.DataTransferDefaultExportSettings, error) { + panic(fmt.Errorf("not implemented: DataTransferDefaultExportSettings - dataTransferDefaultExportSettings")) +} + // DataTransferExportDataFromContainer is the resolver for the dataTransferExportDataFromContainer field. -func (r *queryResolver) DataTransferExportDataFromContainer(ctx context.Context, connectionID string, containerNodePath string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) { +func (r *queryResolver) DataTransferExportDataFromContainer(ctx context.Context, projectID *string, connectionID string, containerNodePath string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) { panic(fmt.Errorf("not implemented: DataTransferExportDataFromContainer - dataTransferExportDataFromContainer")) } // DataTransferExportDataFromResults is the resolver for the dataTransferExportDataFromResults field. -func (r *queryResolver) DataTransferExportDataFromResults(ctx context.Context, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) { +func (r *queryResolver) DataTransferExportDataFromResults(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, parameters model.DataTransferParameters) (*model.AsyncTaskInfo, error) { panic(fmt.Errorf("not implemented: DataTransferExportDataFromResults - dataTransferExportDataFromResults")) } diff --git a/internal/pkg/cloudbeaver/resolver/service.metadata_gen.go b/internal/pkg/cloudbeaver/resolver/service.metadata_gen.go index 501ac2fe1..8dad59e1b 100644 --- a/internal/pkg/cloudbeaver/resolver/service.metadata_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.metadata_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -9,6 +10,11 @@ import ( ) // MetadataGetNodeDdl is the resolver for the metadataGetNodeDDL field. -func (r *queryResolver) MetadataGetNodeDdl(ctx context.Context, nodeID string, options interface{}) (*string, error) { +func (r *queryResolver) MetadataGetNodeDdl(ctx context.Context, nodeID string, options any) (*string, error) { panic(fmt.Errorf("not implemented: MetadataGetNodeDdl - metadataGetNodeDDL")) } + +// MetadataGetNodeExtendedDdl is the resolver for the metadataGetNodeExtendedDDL field. +func (r *queryResolver) MetadataGetNodeExtendedDdl(ctx context.Context, nodeID string) (*string, error) { + panic(fmt.Errorf("not implemented: MetadataGetNodeExtendedDdl - metadataGetNodeExtendedDDL")) +} diff --git a/internal/pkg/cloudbeaver/resolver/service.navigator_gen.go b/internal/pkg/cloudbeaver/resolver/service.navigator_gen.go index 770af631e..e120b6e90 100644 --- a/internal/pkg/cloudbeaver/resolver/service.navigator_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.navigator_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -10,6 +11,11 @@ import ( "github.com/actiontech/dms/internal/pkg/cloudbeaver/model" ) +// NavReloadNode is the resolver for the navReloadNode field. +func (r *mutationResolver) NavReloadNode(ctx context.Context, nodePath string) (*model.NavigatorNodeInfo, error) { + panic(fmt.Errorf("not implemented: NavReloadNode - navReloadNode")) +} + // NavRenameNode is the resolver for the navRenameNode field. func (r *mutationResolver) NavRenameNode(ctx context.Context, nodePath string, newName string) (*string, error) { panic(fmt.Errorf("not implemented: NavRenameNode - navRenameNode")) @@ -21,10 +27,15 @@ func (r *mutationResolver) NavDeleteNodes(ctx context.Context, nodePaths []strin } // NavMoveNodesToFolder is the resolver for the navMoveNodesToFolder field. -func (r *mutationResolver) NavMoveNodesToFolder(ctx context.Context, nodePaths []string, folderPath string) (*bool, error) { +func (r *mutationResolver) NavMoveNodesToFolder(ctx context.Context, nodePaths []string, folderPath string) (bool, error) { panic(fmt.Errorf("not implemented: NavMoveNodesToFolder - navMoveNodesToFolder")) } +// NavSetFolderFilter is the resolver for the navSetFolderFilter field. +func (r *mutationResolver) NavSetFolderFilter(ctx context.Context, nodePath string, include []string, exclude []string) (bool, error) { + panic(fmt.Errorf("not implemented: NavSetFolderFilter - navSetFolderFilter")) +} + // NavNodeChildren is the resolver for the navNodeChildren field. func (r *queryResolver) NavNodeChildren(ctx context.Context, parentPath string, offset *int, limit *int, onlyFolders *bool) ([]*model.NavigatorNodeInfo, error) { panic(fmt.Errorf("not implemented: NavNodeChildren - navNodeChildren")) @@ -46,6 +57,6 @@ func (r *queryResolver) NavRefreshNode(ctx context.Context, nodePath string) (*b } // NavGetStructContainers is the resolver for the navGetStructContainers field. -func (r *queryResolver) NavGetStructContainers(ctx context.Context, connectionID string, contextID *string, catalog *string) (*model.DatabaseStructContainers, error) { +func (r *queryResolver) NavGetStructContainers(ctx context.Context, projectID *string, connectionID string, contextID *string, catalog *string) (*model.DatabaseStructContainers, error) { panic(fmt.Errorf("not implemented: NavGetStructContainers - navGetStructContainers")) } diff --git a/internal/pkg/cloudbeaver/resolver/service.rm_gen.go b/internal/pkg/cloudbeaver/resolver/service.rm_gen.go index ad6c0247f..e2b3f1d39 100644 --- a/internal/pkg/cloudbeaver/resolver/service.rm_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.rm_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -26,15 +27,75 @@ func (r *mutationResolver) RmDeleteResource(ctx context.Context, projectID strin } // RmWriteResourceStringContent is the resolver for the rmWriteResourceStringContent field. -func (r *mutationResolver) RmWriteResourceStringContent(ctx context.Context, projectID string, resourcePath string, data string) (string, error) { +func (r *mutationResolver) RmWriteResourceStringContent(ctx context.Context, projectID string, resourcePath string, data string, forceOverwrite bool) (string, error) { panic(fmt.Errorf("not implemented: RmWriteResourceStringContent - rmWriteResourceStringContent")) } +// RmCreateProject is the resolver for the rmCreateProject field. +func (r *mutationResolver) RmCreateProject(ctx context.Context, projectID *string, projectName string, description *string) (*model.RMProject, error) { + panic(fmt.Errorf("not implemented: RmCreateProject - rmCreateProject")) +} + +// RmDeleteProject is the resolver for the rmDeleteProject field. +func (r *mutationResolver) RmDeleteProject(ctx context.Context, projectID string) (bool, error) { + panic(fmt.Errorf("not implemented: RmDeleteProject - rmDeleteProject")) +} + +// RmSetProjectPermissions is the resolver for the rmSetProjectPermissions field. +func (r *mutationResolver) RmSetProjectPermissions(ctx context.Context, projectID string, permissions []*model.RMSubjectProjectPermissions) (bool, error) { + panic(fmt.Errorf("not implemented: RmSetProjectPermissions - rmSetProjectPermissions")) +} + +// RmSetSubjectProjectPermissions is the resolver for the rmSetSubjectProjectPermissions field. +func (r *mutationResolver) RmSetSubjectProjectPermissions(ctx context.Context, subjectID string, permissions []*model.RMProjectPermissions) (bool, error) { + panic(fmt.Errorf("not implemented: RmSetSubjectProjectPermissions - rmSetSubjectProjectPermissions")) +} + +// RmAddProjectsPermissions is the resolver for the rmAddProjectsPermissions field. +func (r *mutationResolver) RmAddProjectsPermissions(ctx context.Context, projectIds []string, subjectIds []string, permissions []string) (*bool, error) { + panic(fmt.Errorf("not implemented: RmAddProjectsPermissions - rmAddProjectsPermissions")) +} + +// RmDeleteProjectsPermissions is the resolver for the rmDeleteProjectsPermissions field. +func (r *mutationResolver) RmDeleteProjectsPermissions(ctx context.Context, projectIds []string, subjectIds []string, permissions []string) (*bool, error) { + panic(fmt.Errorf("not implemented: RmDeleteProjectsPermissions - rmDeleteProjectsPermissions")) +} + +// RmSetResourceProperty is the resolver for the rmSetResourceProperty field. +func (r *mutationResolver) RmSetResourceProperty(ctx context.Context, projectID string, resourcePath string, name string, value *string) (bool, error) { + panic(fmt.Errorf("not implemented: RmSetResourceProperty - rmSetResourceProperty")) +} + // RmListProjects is the resolver for the rmListProjects field. func (r *queryResolver) RmListProjects(ctx context.Context) ([]*model.RMProject, error) { panic(fmt.Errorf("not implemented: RmListProjects - rmListProjects")) } +// RmListSharedProjects is the resolver for the rmListSharedProjects field. +func (r *queryResolver) RmListSharedProjects(ctx context.Context) ([]*model.RMProject, error) { + panic(fmt.Errorf("not implemented: RmListSharedProjects - rmListSharedProjects")) +} + +// RmProject is the resolver for the rmProject field. +func (r *queryResolver) RmProject(ctx context.Context, projectID string) (*model.RMProject, error) { + panic(fmt.Errorf("not implemented: RmProject - rmProject")) +} + +// RmListProjectPermissions is the resolver for the rmListProjectPermissions field. +func (r *queryResolver) RmListProjectPermissions(ctx context.Context) ([]*model.AdminPermissionInfo, error) { + panic(fmt.Errorf("not implemented: RmListProjectPermissions - rmListProjectPermissions")) +} + +// RmListProjectGrantedPermissions is the resolver for the rmListProjectGrantedPermissions field. +func (r *queryResolver) RmListProjectGrantedPermissions(ctx context.Context, projectID string) ([]*model.AdminObjectGrantInfo, error) { + panic(fmt.Errorf("not implemented: RmListProjectGrantedPermissions - rmListProjectGrantedPermissions")) +} + +// RmListSubjectProjectsPermissionGrants is the resolver for the rmListSubjectProjectsPermissionGrants field. +func (r *queryResolver) RmListSubjectProjectsPermissionGrants(ctx context.Context, subjectID string) ([]*model.AdminObjectGrantInfo, error) { + panic(fmt.Errorf("not implemented: RmListSubjectProjectsPermissionGrants - rmListSubjectProjectsPermissionGrants")) +} + // RmListResources is the resolver for the rmListResources field. func (r *queryResolver) RmListResources(ctx context.Context, projectID string, folder *string, nameMask *string, readProperties *bool, readHistory *bool) ([]*model.RMResource, error) { panic(fmt.Errorf("not implemented: RmListResources - rmListResources")) diff --git a/internal/pkg/cloudbeaver/resolver/service.sql_gen.go b/internal/pkg/cloudbeaver/resolver/service.sql_gen.go index b67adeb55..9f2133a91 100644 --- a/internal/pkg/cloudbeaver/resolver/service.sql_gen.go +++ b/internal/pkg/cloudbeaver/resolver/service.sql_gen.go @@ -2,6 +2,7 @@ package resolver // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.81 import ( "context" @@ -11,57 +12,77 @@ import ( ) // SQLContextCreate is the resolver for the sqlContextCreate field. -func (r *mutationResolver) SQLContextCreate(ctx context.Context, connectionID string, defaultCatalog *string, defaultSchema *string) (*model.SQLContextInfo, error) { +func (r *mutationResolver) SQLContextCreate(ctx context.Context, projectID *string, connectionID string, defaultCatalog *string, defaultSchema *string) (*model.SQLContextInfo, error) { panic(fmt.Errorf("not implemented: SQLContextCreate - sqlContextCreate")) } // SQLContextSetDefaults is the resolver for the sqlContextSetDefaults field. -func (r *mutationResolver) SQLContextSetDefaults(ctx context.Context, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) (bool, error) { +func (r *mutationResolver) SQLContextSetDefaults(ctx context.Context, projectID *string, connectionID string, contextID string, defaultCatalog *string, defaultSchema *string) (bool, error) { panic(fmt.Errorf("not implemented: SQLContextSetDefaults - sqlContextSetDefaults")) } // SQLContextDestroy is the resolver for the sqlContextDestroy field. -func (r *mutationResolver) SQLContextDestroy(ctx context.Context, connectionID string, contextID string) (bool, error) { +func (r *mutationResolver) SQLContextDestroy(ctx context.Context, projectID *string, connectionID string, contextID string) (bool, error) { panic(fmt.Errorf("not implemented: SQLContextDestroy - sqlContextDestroy")) } // AsyncSQLExecuteQuery is the resolver for the asyncSqlExecuteQuery field. -func (r *mutationResolver) AsyncSQLExecuteQuery(ctx context.Context, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) { +func (r *mutationResolver) AsyncSQLExecuteQuery(ctx context.Context, projectID *string, connectionID string, contextID string, sql string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat, readLogs *bool) (*model.AsyncTaskInfo, error) { panic(fmt.Errorf("not implemented: AsyncSQLExecuteQuery - asyncSqlExecuteQuery")) } // AsyncReadDataFromContainer is the resolver for the asyncReadDataFromContainer field. -func (r *mutationResolver) AsyncReadDataFromContainer(ctx context.Context, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) { +func (r *mutationResolver) AsyncReadDataFromContainer(ctx context.Context, projectID *string, connectionID string, contextID string, containerNodePath string, resultID *string, filter *model.SQLDataFilter, dataFormat *model.ResultDataFormat) (*model.AsyncTaskInfo, error) { panic(fmt.Errorf("not implemented: AsyncReadDataFromContainer - asyncReadDataFromContainer")) } +// GetTransactionLogInfo is the resolver for the getTransactionLogInfo field. +func (r *mutationResolver) GetTransactionLogInfo(ctx context.Context, projectID string, connectionID string, contextID string) (*model.TransactionLogInfos, error) { + panic(fmt.Errorf("not implemented: GetTransactionLogInfo - getTransactionLogInfo")) +} + // SQLResultClose is the resolver for the sqlResultClose field. -func (r *mutationResolver) SQLResultClose(ctx context.Context, connectionID string, contextID string, resultID string) (bool, error) { +func (r *mutationResolver) SQLResultClose(ctx context.Context, projectID *string, connectionID string, contextID string, resultID string) (bool, error) { panic(fmt.Errorf("not implemented: SQLResultClose - sqlResultClose")) } +// AsyncUpdateResultsDataBatch is the resolver for the asyncUpdateResultsDataBatch field. +func (r *mutationResolver) AsyncUpdateResultsDataBatch(ctx context.Context, projectID string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.AsyncTaskInfo, error) { + panic(fmt.Errorf("not implemented: AsyncUpdateResultsDataBatch - asyncUpdateResultsDataBatch")) +} + // UpdateResultsDataBatch is the resolver for the updateResultsDataBatch field. -func (r *mutationResolver) UpdateResultsDataBatch(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.SQLExecuteInfo, error) { +func (r *mutationResolver) UpdateResultsDataBatch(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (*model.SQLExecuteInfo, error) { panic(fmt.Errorf("not implemented: UpdateResultsDataBatch - updateResultsDataBatch")) } // UpdateResultsDataBatchScript is the resolver for the updateResultsDataBatchScript field. -func (r *mutationResolver) UpdateResultsDataBatchScript(ctx context.Context, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (string, error) { +func (r *mutationResolver) UpdateResultsDataBatchScript(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, updatedRows []*model.SQLResultRow, deletedRows []*model.SQLResultRow, addedRows []*model.SQLResultRow) (string, error) { panic(fmt.Errorf("not implemented: UpdateResultsDataBatchScript - updateResultsDataBatchScript")) } // ReadLobValue is the resolver for the readLobValue field. -func (r *mutationResolver) ReadLobValue(ctx context.Context, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) (string, error) { +func (r *mutationResolver) ReadLobValue(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, lobColumnIndex int, row []*model.SQLResultRow) (string, error) { panic(fmt.Errorf("not implemented: ReadLobValue - readLobValue")) } +// SQLReadLobValue is the resolver for the sqlReadLobValue field. +func (r *mutationResolver) SQLReadLobValue(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, lobColumnIndex int, row model.SQLResultRow) (string, error) { + panic(fmt.Errorf("not implemented: SQLReadLobValue - sqlReadLobValue")) +} + +// SQLReadStringValue is the resolver for the sqlReadStringValue field. +func (r *mutationResolver) SQLReadStringValue(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, columnIndex int, row model.SQLResultRow) (string, error) { + panic(fmt.Errorf("not implemented: SQLReadStringValue - sqlReadStringValue")) +} + // AsyncSQLExecuteResults is the resolver for the asyncSqlExecuteResults field. func (r *mutationResolver) AsyncSQLExecuteResults(ctx context.Context, taskID string) (*model.SQLExecuteInfo, error) { panic(fmt.Errorf("not implemented: AsyncSQLExecuteResults - asyncSqlExecuteResults")) } // AsyncSQLExplainExecutionPlan is the resolver for the asyncSqlExplainExecutionPlan field. -func (r *mutationResolver) AsyncSQLExplainExecutionPlan(ctx context.Context, connectionID string, contextID string, query string, configuration interface{}) (*model.AsyncTaskInfo, error) { +func (r *mutationResolver) AsyncSQLExplainExecutionPlan(ctx context.Context, projectID *string, connectionID string, contextID string, query string, configuration any) (*model.AsyncTaskInfo, error) { panic(fmt.Errorf("not implemented: AsyncSQLExplainExecutionPlan - asyncSqlExplainExecutionPlan")) } @@ -70,28 +91,58 @@ func (r *mutationResolver) AsyncSQLExplainExecutionPlanResult(ctx context.Contex panic(fmt.Errorf("not implemented: AsyncSQLExplainExecutionPlanResult - asyncSqlExplainExecutionPlanResult")) } +// AsyncSQLRowDataCount is the resolver for the asyncSqlRowDataCount field. +func (r *mutationResolver) AsyncSQLRowDataCount(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string) (*model.AsyncTaskInfo, error) { + panic(fmt.Errorf("not implemented: AsyncSQLRowDataCount - asyncSqlRowDataCount")) +} + +// AsyncSQLRowDataCountResult is the resolver for the asyncSqlRowDataCountResult field. +func (r *mutationResolver) AsyncSQLRowDataCountResult(ctx context.Context, taskID string) (int, error) { + panic(fmt.Errorf("not implemented: AsyncSQLRowDataCountResult - asyncSqlRowDataCountResult")) +} + +// SQLGetDynamicTrace is the resolver for the sqlGetDynamicTrace field. +func (r *mutationResolver) SQLGetDynamicTrace(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string) ([]*model.DynamicTraceProperty, error) { + panic(fmt.Errorf("not implemented: SQLGetDynamicTrace - sqlGetDynamicTrace")) +} + +// AsyncSQLSetAutoCommit is the resolver for the asyncSqlSetAutoCommit field. +func (r *mutationResolver) AsyncSQLSetAutoCommit(ctx context.Context, projectID string, connectionID string, contextID string, autoCommit bool) (*model.AsyncTaskInfo, error) { + panic(fmt.Errorf("not implemented: AsyncSQLSetAutoCommit - asyncSqlSetAutoCommit")) +} + +// AsyncSQLCommitTransaction is the resolver for the asyncSqlCommitTransaction field. +func (r *mutationResolver) AsyncSQLCommitTransaction(ctx context.Context, projectID string, connectionID string, contextID string) (*model.AsyncTaskInfo, error) { + panic(fmt.Errorf("not implemented: AsyncSQLCommitTransaction - asyncSqlCommitTransaction")) +} + +// AsyncSQLRollbackTransaction is the resolver for the asyncSqlRollbackTransaction field. +func (r *mutationResolver) AsyncSQLRollbackTransaction(ctx context.Context, projectID string, connectionID string, contextID string) (*model.AsyncTaskInfo, error) { + panic(fmt.Errorf("not implemented: AsyncSQLRollbackTransaction - asyncSqlRollbackTransaction")) +} + // SQLDialectInfo is the resolver for the sqlDialectInfo field. -func (r *queryResolver) SQLDialectInfo(ctx context.Context, connectionID string) (*model.SQLDialectInfo, error) { +func (r *queryResolver) SQLDialectInfo(ctx context.Context, projectID *string, connectionID string) (*model.SQLDialectInfo, error) { panic(fmt.Errorf("not implemented: SQLDialectInfo - sqlDialectInfo")) } // SQLListContexts is the resolver for the sqlListContexts field. -func (r *queryResolver) SQLListContexts(ctx context.Context, connectionID *string, contextID *string) ([]*model.SQLContextInfo, error) { +func (r *queryResolver) SQLListContexts(ctx context.Context, projectID *string, connectionID *string, contextID *string) ([]*model.SQLContextInfo, error) { panic(fmt.Errorf("not implemented: SQLListContexts - sqlListContexts")) } // SQLCompletionProposals is the resolver for the sqlCompletionProposals field. -func (r *queryResolver) SQLCompletionProposals(ctx context.Context, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) ([]*model.SQLCompletionProposal, error) { +func (r *queryResolver) SQLCompletionProposals(ctx context.Context, projectID *string, connectionID string, contextID string, query string, position int, maxResults *int, simpleMode *bool) ([]*model.SQLCompletionProposal, error) { panic(fmt.Errorf("not implemented: SQLCompletionProposals - sqlCompletionProposals")) } // SQLFormatQuery is the resolver for the sqlFormatQuery field. -func (r *queryResolver) SQLFormatQuery(ctx context.Context, connectionID string, contextID string, query string) (string, error) { +func (r *queryResolver) SQLFormatQuery(ctx context.Context, projectID *string, connectionID string, contextID string, query string) (string, error) { panic(fmt.Errorf("not implemented: SQLFormatQuery - sqlFormatQuery")) } // SQLSupportedOperations is the resolver for the sqlSupportedOperations field. -func (r *queryResolver) SQLSupportedOperations(ctx context.Context, connectionID string, contextID string, resultsID string, attributeIndex int) ([]*model.DataTypeLogicalOperation, error) { +func (r *queryResolver) SQLSupportedOperations(ctx context.Context, projectID *string, connectionID string, contextID string, resultsID string, attributeIndex int) ([]*model.DataTypeLogicalOperation, error) { panic(fmt.Errorf("not implemented: SQLSupportedOperations - sqlSupportedOperations")) } @@ -101,16 +152,21 @@ func (r *queryResolver) SQLEntityQueryGenerators(ctx context.Context, nodePathLi } // SQLGenerateEntityQuery is the resolver for the sqlGenerateEntityQuery field. -func (r *queryResolver) SQLGenerateEntityQuery(ctx context.Context, generatorID string, options interface{}, nodePathList []string) (string, error) { +func (r *queryResolver) SQLGenerateEntityQuery(ctx context.Context, generatorID string, options any, nodePathList []string) (string, error) { panic(fmt.Errorf("not implemented: SQLGenerateEntityQuery - sqlGenerateEntityQuery")) } // SQLParseScript is the resolver for the sqlParseScript field. -func (r *queryResolver) SQLParseScript(ctx context.Context, connectionID string, script string) (*model.SQLScriptInfo, error) { +func (r *queryResolver) SQLParseScript(ctx context.Context, projectID *string, connectionID string, script string) (*model.SQLScriptInfo, error) { panic(fmt.Errorf("not implemented: SQLParseScript - sqlParseScript")) } // SQLParseQuery is the resolver for the sqlParseQuery field. -func (r *queryResolver) SQLParseQuery(ctx context.Context, connectionID string, script string, position int) (*model.SQLScriptQuery, error) { +func (r *queryResolver) SQLParseQuery(ctx context.Context, projectID *string, connectionID string, script string, position int) (*model.SQLScriptQuery, error) { panic(fmt.Errorf("not implemented: SQLParseQuery - sqlParseQuery")) } + +// SQLGenerateGroupingQuery is the resolver for the sqlGenerateGroupingQuery field. +func (r *queryResolver) SQLGenerateGroupingQuery(ctx context.Context, projectID *string, contextID string, connectionID string, resultsID string, columnNames []string, functions []string, showDuplicatesOnly *bool) (string, error) { + panic(fmt.Errorf("not implemented: SQLGenerateGroupingQuery - sqlGenerateGroupingQuery")) +} diff --git a/internal/pkg/cloudbeaver/schema/schema.graphqls b/internal/pkg/cloudbeaver/schema/schema.graphqls index a3dee4ffa..191dc13f0 100644 --- a/internal/pkg/cloudbeaver/schema/schema.graphqls +++ b/internal/pkg/cloudbeaver/schema/schema.graphqls @@ -2,6 +2,14 @@ scalar Object # Date/Time scalar DateTime +scalar Date + +input PageInput { + limit: Int + offset: Int +} + +directive @since(version: String!) repeatable on OBJECT|SCALAR|QUERY|MUTATION|FIELD|VARIABLE_DEFINITION|OBJECT|FIELD_DEFINITION|ARGUMENT_DEFINITION|INTERFACE|ENUM|ENUM_VALUE|INPUT_OBJECT|INPUT_FIELD_DEFINITION type Query diff --git a/internal/pkg/cloudbeaver/schema/service.admin.graphqls b/internal/pkg/cloudbeaver/schema/service.admin.graphqls index db85a8cb9..1b1987cd7 100644 --- a/internal/pkg/cloudbeaver/schema/service.admin.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.admin.graphqls @@ -1,7 +1,7 @@ enum AdminSubjectType { user, - role + team } type AdminConnectionGrantInfo { @@ -11,6 +11,22 @@ type AdminConnectionGrantInfo { subjectType: AdminSubjectType! } +type AdminUserTeamGrantInfo @since(version: "24.0.5"){ + userId: ID! + teamRole: String +} + +type AdminObjectPermissions { + objectId: ID! + permissions: [String!]! +} + +type AdminObjectGrantInfo { + subjectId: ID! + subjectType: AdminSubjectType! + objectPermissions: AdminObjectPermissions! +} + type AdminConnectionSearchInfo { displayName: String! host: String! @@ -24,24 +40,33 @@ type AdminUserInfo { metaParameters: Object! configurationParameters: Object! - grantedRoles: [ID!]! + grantedTeams: [ID!]! grantedConnections: [AdminConnectionGrantInfo!]! origins: [ObjectOrigin!]! linkedAuthProviders: [String!]! enabled: Boolean! + authRole: String + + disableDate: DateTime @since(version: "25.0.2") + disabledBy: String @since(version: "25.0.2") + disableReason: String @since(version: "25.0.2") + } -type AdminRoleInfo { - roleId: ID! - roleName: String +type AdminTeamInfo { + teamId: ID! + teamName: String description: String + metaParameters: Object! + grantedUsers: [ID!]! + grantedUsersInfo: [AdminUserTeamGrantInfo!]! @since(version: "24.0.5") grantedConnections: [AdminConnectionGrantInfo!]! - rolePermissions: [ID!]! + teamPermissions: [ID!]! } type AdminPermissionInfo { @@ -68,6 +93,8 @@ type AdminAuthProviderConfiguration { signOutLink: String redirectLink: String metadataLink: String + acsLink: String + entityIdLink: String @since(version: "24.2.1") } type WebFeatureSet { @@ -81,7 +108,7 @@ type WebFeatureSet { input ServerConfigInput { serverName: String - serverURL: String + serverURL: String @deprecated adminName: String adminPassword: String @@ -92,67 +119,114 @@ input ServerConfigInput { publicCredentialsSaveEnabled: Boolean adminCredentialsSaveEnabled: Boolean resourceManagerEnabled: Boolean + secretManagerEnabled: Boolean @since(version: "24.3.2") enabledFeatures: [ID!] enabledAuthProviders: [ID!] disabledDrivers: [ID!] sessionExpireTime: Int + forceHttps: Boolean @since(version: "25.1.3") + supportedHosts: [String!] @since(version: "25.1.3") + bindSessionToIp: String @since(version: "25.1.4") } -extend type Query { - - #### Users and roles +input AdminUserFilterInput { + userIdMask: String + enabledState: Boolean +} - listUsers(userId: ID): [AdminUserInfo!]! - listRoles(roleId: ID): [AdminRoleInfo!]! +extend type Query { + #### Users and teams + + "Returns information about user by userId" + adminUserInfo(userId: ID!): AdminUserInfo! + "Returns all users with pagination and filter" + listUsers(page: PageInput!, filter: AdminUserFilterInput!): [AdminUserInfo!]! + "Returns information about team by teamId. If teamId is not provided, returns information about all teams" + listTeams(teamId: ID): [AdminTeamInfo!]! + "Returns all permissions" listPermissions: [AdminPermissionInfo!]! - - createUser(userId: ID!): AdminUserInfo! + "Returns all auth roles based on the license" + listAuthRoles: [String!]! + "Returns all team roles" + listTeamRoles: [String!]! + "Returns teams meta parameters for displaying in the UI" + listTeamMetaParameters: [ObjectPropertyInfo!]! + + "Creates a new user with the specified userId" + createUser(userId: ID!, enabled: Boolean!, authRole: String): AdminUserInfo! + "Deletes user by userId" deleteUser(userId: ID!): Boolean - createRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - updateRole(roleId: ID!, roleName: String, description: String): AdminRoleInfo! - deleteRole(roleId: ID!): Boolean + "Creates a new team with the specified teamId" + createTeam(teamId: ID!, teamName: String, description: String): AdminTeamInfo! + "Updates team information by teamId" + updateTeam(teamId: ID!, teamName: String, description: String): AdminTeamInfo! + "Deletes team by teamId" + deleteTeam(teamId: ID!, force: Boolean): Boolean - grantUserRole(userId: ID!, roleId: ID!): Boolean - revokeUserRole(userId: ID!, roleId: ID!): Boolean + "Grants user to team with the specified userId and teamId" + grantUserTeam(userId: ID!, teamId: ID!): Boolean + "Revokes user from team with the specified userId and teamId" + revokeUserTeam(userId: ID!, teamId: ID!): Boolean - setSubjectPermissions(roleId: ID!, permissions: [ID!]!): [AdminPermissionInfo!]! + "Sets permissions to the subject (user or team) with the specified subjectId" + setSubjectPermissions(subjectId: ID!, permissions: [ID!]!): [AdminPermissionInfo!]! + "Sets user credentials for the specified userId and providerId" setUserCredentials(userId: ID!, providerId: ID!, credentials: Object!): Boolean + "Deletes user credentials for the specified userId and providerId" + deleteUserCredentials(userId: ID!, providerId: ID!): Boolean + + "Enables or disables user by userId" enableUser(userId: ID!, enabled: Boolean!): Boolean - #### Connection management + "Sets user auth role for the specified userId" + setUserAuthRole(userId: ID!, authRole: String): Boolean - # All connection configurations - allConnections( id: ID ): [ ConnectionInfo! ]! + "Sets user team role for the specified userId and teamId" + setUserTeamRole(userId: ID!, teamId: ID!, teamRole: String): Boolean @since(version: "24.0.5") - searchConnections( hostNames: [String!]! ): [AdminConnectionSearchInfo!]! + #### Connection management - createConnectionConfiguration( config: ConnectionConfig! ): ConnectionInfo! - copyConnectionConfiguration( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! - updateConnectionConfiguration( id: ID!, config: ConnectionConfig! ): ConnectionInfo! - deleteConnectionConfiguration( id: ID! ): Boolean + "Finds available connections by host names" + searchConnections( hostNames: [String!]! ): [AdminConnectionSearchInfo!]! # Permissions - getConnectionSubjectAccess(connectionId: ID): [AdminConnectionGrantInfo!]! - setConnectionSubjectAccess(connectionId: ID!, subjects: [ID!]!): Boolean + "Returns all subjects (users and teams) that have access to the specified connection" + getConnectionSubjectAccess(projectId: ID!, connectionId: ID): [AdminConnectionGrantInfo!]! + + "Sets access to the connection for the specified subjects (users and teams)" + setConnectionSubjectAccess(projectId: ID!, connectionId: ID!, subjects: [ID!]!): Boolean @deprecated(reason: "use addConnectionsAccess (23.2.2)") - getSubjectConnectionAccess(subjectId: ID): [AdminConnectionGrantInfo!]! - setSubjectConnectionAccess(subjectId: ID!, connections: [ID!]!): Boolean + "Sets access to the connections for the specified subjects (users and teams)" + addConnectionsAccess(projectId: ID!, connectionIds: [ID!]!, subjects: [ID!]!): Boolean @since(version: "23.2.2") + + "Deletes access to the connections for the specified subjects (users and teams)" + deleteConnectionsAccess(projectId: ID!, connectionIds: [ID!]!, subjects: [ID!]!): Boolean @since(version: "23.2.2") + + "Returns all connections that the subject (user or team) has access to" + getSubjectConnectionAccess(subjectId: ID!): [AdminConnectionGrantInfo!]! + + "Sets access for a subject (user or team) to the specified connections" + setSubjectConnectionAccess(subjectId: ID!, connections: [ID!]!): Boolean @deprecated(reason: "23.2.2") #### Feature sets + "Returns all available feature sets that can be enabled or disabled" listFeatureSets: [WebFeatureSet!]! #### Auth providers and configurations + "Returns all properties of the auth provider with the specified providerId" listAuthProviderConfigurationParameters(providerId: ID!): [ObjectPropertyInfo!]! + "Returns all auth provider configurations for the specified providerId. If providerId is not provided, returns all configurations" listAuthProviderConfigurations(providerId: ID): [AdminAuthProviderConfiguration!]! + "Saves auth provider configuration with the specified parameters" saveAuthProviderConfiguration( providerId: ID!, id: ID!, @@ -160,22 +234,37 @@ extend type Query { disabled: Boolean, iconURL: String description: String - parameters: Object): AdminAuthProviderConfiguration! + parameters: Object + ): AdminAuthProviderConfiguration! + + "Deletes auth provider configuration by id" deleteAuthProviderConfiguration(id: ID!): Boolean! #### User profile + "Not implemented yet" saveUserMetaParameter(id: ID!, displayName: String!, description: String, required: Boolean!): ObjectPropertyInfo! + "Not implemented yet" deleteUserMetaParameter(id: ID!): Boolean! + "Sets user meta parameters values for the specified userId" setUserMetaParameterValues(userId: ID!, parameters: Object!): Boolean! + "Sets team meta parameters values for the specified teamId" + setTeamMetaParameterValues(teamId: ID!, parameters: Object!): Boolean! + #### Global configuration + "Saves server configuration" configureServer(configuration: ServerConfigInput!): Boolean! - # Changes default navigator settings + "Changes default navigator settings" setDefaultNavigatorSettings( settings: NavigatorSettingsInput!): Boolean! } + +extend type Mutation { + "Updates product configuration" + adminUpdateProductConfiguration(configuration: Object!): Boolean! @since(version: "23.3.4") +} diff --git a/internal/pkg/cloudbeaver/schema/service.auth.graphqls b/internal/pkg/cloudbeaver/schema/service.auth.graphqls index 80ca5b496..24960ec2d 100644 --- a/internal/pkg/cloudbeaver/schema/service.auth.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.auth.graphqls @@ -30,16 +30,22 @@ type AuthProviderConfiguration { id: ID! displayName: String! disabled: Boolean! + authRoleProvided: Boolean iconURL: String description: String - # URL to external authentication service. - # If specified then it is external auhentication provider (SSO). - # Otherwise authLogin function must be called. + """ + URL to external authentication service. + If specified then it is external authentication provider (SSO). + Otherwise authLogin function must be called. + """ signInLink: String signOutLink: String + redirectLink: String metadataLink: String + acsLink: String + entityIdLink: String @since(version: "24.2.1") } type AuthProviderCredentialsProfile { @@ -56,94 +62,154 @@ type AuthProviderInfo { description: String defaultProvider: Boolean! + trusted: Boolean! + private: Boolean! + authHidden: Boolean! @since(version: "24.2.4") + supportProvisioning: Boolean! - # Configurable providers must be configured first. See configurations field. + "Configurable providers must be configured first. See configurations field." configurable: Boolean! + "Federated providers means authorization must occur asynchronously through redirects." + federated: Boolean! - # Provider configurations (applicable only if configurable=true) + "Provider configurations (applicable only if configurable=true)" configurations: [AuthProviderConfiguration!] + templateConfiguration: AuthProviderConfiguration! @since(version: "24.1.2") + credentialProfiles: [AuthProviderCredentialsProfile!]! requiredFeatures: [String!]! + + required: Boolean! } + type AuthInfo { - redirectLink: String + redirectLink: String @deprecated - authId: String + authId: String @deprecated - authStatus: AuthStatus! + authStatus: AuthStatus! @deprecated userTokens: [UserAuthToken!] } +type FederatedAuthInfo @since(version: "25.0.3") { + redirectLink: String! + taskInfo: AsyncTaskInfo! +} + +type FederatedAuthResult @since(version: "25.0.3") { + userTokens: [UserAuthToken!]! @since(version: "25.0.3") +} + +type LogoutInfo @since(version: "23.3.3") { + redirectLinks: [String!]! +} + type UserAuthToken { - # Auth provider used for authorization + "Auth provider used for authorization" authProvider: ID! - # Auth provider configuration ID + "Auth provider configuration ID" authConfiguration: ID - # Authorization time + "Authorization time" loginTime: DateTime! - # User identity (aka user name) specific to auth provider + "User identity (aka user name) specific to auth provider" userId: String! - # User display name specific to auth provider + "User display name specific to auth provider" displayName: String! - # Optional login message + "Optional login message" message: String - # Auth origin + "Auth origin" origin: ObjectOrigin! } type UserInfo { - # User unique identifier + "User unique identifier" userId: ID! - # Human readable display name. It is taken from the first auth provider which was used for user login. + "Human readable display name. It is taken from the first auth provider which was used for user login." displayName: String + "User auth role ID. Optional." + authRole: ID + "All authentication tokens used during current session" authTokens: [UserAuthToken!]! linkedAuthProviders: [String!]! - # User profile properties map + "User profile properties map" metaParameters: Object! - - # USer configuiraiton parameters + "User configuration parameters" configurationParameters: Object! + "User teams" + teams: [UserTeamInfo!]! + + "Indicates whether the user is anonymous (not authenticated)." + isAnonymous: Boolean! @since(version: "24.2.3") +} + +type UserTeamInfo { + teamId: String! + teamName: String! + teamRole: String } extend type Query { - # Authorize user using specified auth provider. If linkUser=true then associates new - authLogin(provider: ID!, configuration: ID, credentials: Object, linkUser: Boolean): AuthInfo! + """ + Authorizes the user using specified auth provider. + Associates new credentials with the active user when linkUser=true. + Kills another user sessions if forceSessionsLogout=true. + """ + authLogin(provider: ID!, configuration: ID, credentials: Object, linkUser: Boolean, forceSessionsLogout: Boolean): AuthInfo! - authUpdateStatus(authId: ID!, linkUser: Boolean): AuthInfo! + "Returns result of federated authentication task" + federatedAuthTaskResult(taskId: String!): FederatedAuthResult! @since(version: "25.0.3") - # Logouts user. If provider not specified then all authorizations are revoked from session. - authLogout(provider: ID, configuration: ID): Boolean + authUpdateStatus(authId: ID!, linkUser: Boolean): AuthInfo! @deprecated - # Active user information. null is no user was authorized within session + "Same as authLogoutExtended but without additional information" + authLogout(provider: ID, configuration: ID): Boolean @deprecated(reason: "use authLogoutExtended instead") + + "Logouts user. If provider not specified then all authorizations are revoked from session. Contains additional information" + authLogoutExtended(provider: ID, configuration: ID): LogoutInfo! @since(version: "23.3.3") + + "Active user information. null is no user was authorized within session" activeUser: UserInfo + "Returns list of all available auth providers" authProviders: [AuthProviderInfo!]! + "Changes the local password of the current user" authChangeLocalPassword(oldPassword: String!, newPassword: String!): Boolean! + "Returns properties that can be shown in user profile" listUserProfileProperties: [ObjectPropertyInfo!]! } + extend type Mutation { - # Set user config parameter. If parameter value is null then removes the parameter + "Set user config parameter. If parameter value is null then removes the parameter" setUserConfigurationParameter(name: String!, value: Object): Boolean! - + "Updates user preferences" + setUserPreferences(preferences: Object!): UserInfo! @since(version: "24.0.1") + + "Creates async task for federated login. Returns redirect link to the task info page." + federatedLogin( + provider: ID!, + configuration: ID, + linkUser: Boolean, + forceSessionsLogout: Boolean + ): FederatedAuthInfo! @since(version: "25.0.3") } diff --git a/internal/pkg/cloudbeaver/schema/service.core.graphqls b/internal/pkg/cloudbeaver/schema/service.core.graphqls index 1894c49a2..42066205e 100644 --- a/internal/pkg/cloudbeaver/schema/service.core.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.core.graphqls @@ -3,233 +3,398 @@ # General stuff #################################################### -# Property - +""" +Information about the object property used to generate its UI +""" type ObjectPropertyInfo { - # ID + "Unique property identifier" id: String - # Human readable name + "Human-readable name" displayName: String - # Property description + "Property description" description: String - # Property category (may be used if object has a lot of properties) + "Usage hint for the property" + hint: String @since(version: "23.2.3") + "Property category (may be used if object has a lot of properties)" category: String - # Property data type (int, String, etc) + "Property data type (e.g., int, String)" dataType: String - - # Property value. Note: for some properties value reading may take a lot of time (e.g. RowCount for tables) + "Property value (can be resource-intensive for some properties, e.g., RowCount for tables)" value: Object - - # List of values this property can take. Makes sense only for enumerable properties + "List of allowed values (for enumerable properties)" validValues: [ Object ] - # Default property value + "Default property value" defaultValue: Object - - # Property value length + "Property value length" length: ObjectPropertyLength! - - # Supported features (system, hidden, inherited, foreign, expensive, etc) + "List of supported features (e.g., system, hidden, inherited, foreign, expensive)" features: [ String! ]! - # Order position + "Order position" order: Int! + "Supported configuration types (for driver properties)" + supportedConfigurationTypes: [ String! ] + "Is the property required" + required: Boolean! @since(version: "23.3.1") + "List of preference scopes (e.g., global, user)" + scopes: [String!] + "Dynamic conditions for the property (e.g., visibility or read-only)" + conditions: [Condition!] @since(version: "25.0.1") } enum ObjectPropertyLength { - # 1 character + "1 character" TINY, - # 20 characters + "20 characters" SHORT, - # <= 64 characters + "<= 64 characters" MEDIUM, - # Full line length. The default + "Full line length. The default" LONG, - # Multi-line long text + "Multi-line long text" MULTILINE } -# Async types +"Represents a dynamic condition for a property, such as visibility or read-only state" +type Condition @since(version: "25.0.1") { + "The logical expression that defines when the condition applies" + expression: String! + "The type of condition (e.g., HIDE or READ_ONLY)" + conditionType: ConditionType! +} +enum ConditionType @since(version: "25.0.1") { + "hiding property condition" + HIDE, + "restriction for setting a property value" + READ_ONLY +} + +""" +Async types +""" type AsyncTaskInfo { + "Task unique identifier" id: String! + "Async task name" name: String + "Indicates if the task is currently running" running: Boolean! + "Current status of the async task" status: String + "Error information if the task failed" error: ServerError - result: SQLExecuteInfo @deprecated # Deprecated. Use asyncSqlExecuteResults instead - # Task result. - # Can be some kind of identifier to obtain real result using another API function + """ + Task result. + Can be some kind of identifier to obtain real result using another API function + """ taskResult: Object } -# Various server errors descriptor +"Various server errors descriptor" type ServerError { + "Error message text" message: String + "Retrieves the vendor-specific error code" errorCode: String + "Type/category of the error" errorType: String + "Stack trace for debugging" stackTrace: String + "Nested error that caused this error (recursive)" causedBy: ServerError } type ServerMessage { + "The time when the server message was created" time: String + "The content of the message" message: String } -# Languages supported by server - +"Languages supported by server" type ServerLanguage { + "ISO 639-1 or similar language code (e.g., \"en\", \"ru\")" isoCode: String! + "Display name of the language in the current locale (e.g., \"English\")" displayName: String + "Native name of the language (e.g., \"English\", \"Русский\")" nativeName: String } -type WebServiceConfig { - id: String! - name: String! - description: String! - bundleVersion: String! +"Password policy configuration" +type PasswordPolicyConfig @since(version: "23.3.3") { + "Minimum password length" + minLength: Int! + "Minimum number of digits required" + minNumberCount: Int! + "Minimum number of symbols required" + minSymbolCount: Int! + "Require both uppercase and lowercase letters" + requireMixedCase: Boolean! } +"Product information" type ProductInfo { + "ID of the product" id: ID! + "The product version" version: String! + "The product name" name: String! + "The product description" description: String + "The build timestamp of the product" buildTime: String! + "The release timestamp of the product" releaseTime: String! + "Information about the product license" licenseInfo: String + "Information about the latest available version" latestVersionInfo: String + "URL for purchasing the product" + productPurchaseURL: String } +"Server configuration" type ServerConfig { + "Server name" name: String! + "Version of the server" version: String! + "ID of the server workspace" workspaceId: ID! - serverURL: String! + "Defines if the anonymous access is enabled" + anonymousAccessEnabled: Boolean! + "Defines if non-admin users can create connections" + supportsCustomConnections: Boolean! + "Defines if resource manager is enabled" + resourceManagerEnabled: Boolean! - rootURI: String! + "Defines if secret manager is enabled" + secretManagerEnabled: Boolean! @since(version: "24.3.2") - hostName: String! - - anonymousAccessEnabled: Boolean - authenticationEnabled: Boolean @deprecated - supportsCustomConnections: Boolean - supportsConnectionBrowser: Boolean - supportsWorkspaces: Boolean - resourceManagerEnabled: Boolean - - publicCredentialsSaveEnabled: Boolean - adminCredentialsSaveEnabled: Boolean + "Defines is it is possible to save user database credentials" + publicCredentialsSaveEnabled: Boolean! + "Defines is it is possible to save global database credentials" + adminCredentialsSaveEnabled: Boolean! + "Defines if the server requires a license" licenseRequired: Boolean! + "Defines if the server license is valid" licenseValid: Boolean! + "Returns information about the server license status" + licenseStatus: String @since(version: "24.1.5") - sessionExpireTime: Int - localHostAddress: String - - configurationMode: Boolean - developmentMode: Boolean - redirectOnFederatedAuth: Boolean + "Defines if the server is in configuration mode" + configurationMode: Boolean! + "Defines if the server is in development mode" + developmentMode: Boolean! + "Defines if the server is distributed" + distributed: Boolean! + "List of enabled features" enabledFeatures: [ID!]! - enabledAuthProviders: [ID!]! + "List of disabled beta features" + disabledBetaFeatures: [ID!] @since(version: "24.0.5") + "List of server features" + serverFeatures: [ID!] @since(version: "24.3.0") + "List of supported languages" supportedLanguages: [ ServerLanguage! ]! - services: [ WebServiceConfig ] + "Product configuration" productConfiguration: Object! + "Product information" productInfo: ProductInfo! + "Navigator settings for the server" defaultNavigatorSettings: NavigatorSettings! + "List of disabled drivers (IDs of DriverInfo)" disabledDrivers: [ID!]! + "Resource quotas (e.g., max amount of running SQL queries)" resourceQuotas: Object! } +type ProductSettingsGroup @since(version: "24.0.1") { + id: ID! + displayName: String! +} + +type ProductSettings @since(version: "24.0.1") { + groups: [ProductSettingsGroup!]! + "each property is associated with a group by category" + settings: [ObjectPropertyInfo!]! +} + type SessionInfo { + "The time when the session was created" createTime: String! + "The last time the session was accessed" lastAccessTime: String! + "The current locale of the session" locale: String! + "Indicates whether the session cache has expired" cacheExpired: Boolean! - serverMessages: [ ServerMessage ] + "List of active connections in the session" connections: [ ConnectionInfo! ]! + "Action parameters for the session (e.g., opening a connection)" actionParameters: Object + + "Indicates if the session is valid" + valid: Boolean! + "Remaining time before the session expires (in seconds)" + remainingTime: Int! } #################################################### -# Drivers and connections +"Drivers and connections" #################################################### type DatabaseAuthModel { + "Auth model unique ID" id: ID! + "Display name of the auth model" displayName: String! + "Description of the auth model" description: String + "Path to the auth model icon" icon: String - # checks if the auth model needs a configuration on a local file system + "Checks if the auth model needs a configuration on a local file system" requiresLocalConfiguration: Boolean + "Returns id of the required auth provider if the auth model requires it" + requiredAuth: String + "List of properties for the auth model that can be displayed in the UI" properties: [ObjectPropertyInfo!]! } type DriverInfo { + """ + Driver unique full ID. It is `providerId + "." + driverId`. + It is recommended to use providerId and driverId separately. + """ id: ID! + "Name of the driver" name: String + "Description of the driver" description: String + "Path to the driver icon" icon: String + "Path to the driver icon for big size" iconBig: String - # Driver provider ID - providerId: ID - # Driver Java class name + "Driver ID. It is unique within provider" + driverId: ID! + "Driver provider ID. It is globally unique" + providerId: ID! + "Driver Java class name" driverClassName: String + "Default host for the driver" defaultHost: String + "Default port for the driver" defaultPort: String + "Default database name for the driver" defaultDatabase: String + "Default server name for the driver" defaultServer: String + "Default user name for the driver" defaultUser: String + "Default connection URL for the driver" sampleURL: String + "Returns link to the driver documentation page" driverInfoURL: String + "Returns link to the driver properties page" driverPropertiesURL: String + "Defines if the database for this driver is embedded" embedded: Boolean + "Defines if the driver is enabled" enabled: Boolean! - requiresServerName: Boolean - - # this fields must be removed and be replaced by DriverAuthModel - allowsEmptyPassword: Boolean @deprecated - + "Defines if the driver page requires server name field" + requiresServerName: Boolean @deprecated(reason: "use mainProperties instead") + "Defines if the driver page requires database name field" + requiresDatabaseName: Boolean @deprecated(reason: "use mainProperties instead") + "Defines if host, port, database, server name fields are using a custom page" + useCustomPage: Boolean! @since(version: "24.1.2") + + "Defines if driver license is required" licenseRequired: Boolean + "Driver license information" license: String + "Defines if the driver is a custom driver" custom: Boolean - # Driver score for ordering, biggest first + "Driver score for ordering, biggest first" promotedScore: Int - # Never used? - #connectionProperties: Object - #defaultConnectionProperties: Object - - # Driver properties. - # Note: it is expensive property and it may produce database server roundtrips. - # Call it only when you really need it. - # These properties are for advanced users in usually shouldn't be specified for new connections. + """ + Driver properties. + Note: it is expensive property and it may produce database server roundtrips. + Call it only when you really need it. + These properties are for advanced users in usually shouldn't be specified for new connections. + """ driverProperties: [ObjectPropertyInfo!]! - # Driver parameters (map name->value) + "Driver parameters (map name->value)" driverParameters: Object! - # Additional driver provider properties - # These properties can be configured by user on main connection page - # to provide important connection settings + """ + Main driver properties. + Contains info about main fields (host, port, database, server name) that are used in main connection page + """ + mainProperties: [ObjectPropertyInfo!]! @since(version: "24.1.2") + + """ + Additional driver provider properties. + These properties can be configured by user on main connection page to provide important connection settings + """ providerProperties: [ObjectPropertyInfo!]! - # False for drivers which do not support authentication - anonymousAccess: Boolean + "Expert driver settings properties. Returns properties (like keep-alive interval) that are not often used and can be hidden in UI" + expertSettingsProperties: [ObjectPropertyInfo!]! @since(version: "25.2.1") + "False for drivers which do not support authentication." + anonymousAccess: Boolean + "Default auth model that is used for this driver (see authModels)" defaultAuthModel: ID! + "List of auth models that can be used with this driver (see authModels)" applicableAuthModels: [ID!]! - + "List of network handlers that can be used with this driver (SSH/SSL)" applicableNetworkHandlers: [ID]! + "Configuration types are used in UI to determine how to display connection settings (show host/port/database fields or use URL field)" + configurationTypes: [DriverConfigurationType]! + + "Defines if the driver can be downloaded remotely" + downloadable: Boolean! @since(version: "24.3.3") + "Defines if the driver is installed on the server" + driverInstalled: Boolean! + "List of driver libraries that are used for connecting to the database" + driverLibraries: [DriverLibraryInfo!]! + "Defines if embedded driver is safe to use in the server" + safeEmbeddedDriver: Boolean! @since(version: "25.0.0") +} + +"Driver library information. Used to display driver files in UI" +type DriverLibraryInfo { + "Driver library unique ID" + id: ID! + "Driver library name" + name: String! + "Path to the driver library icon" + icon: String + "List of files that are used by the driver" + libraryFiles: [DriverFileInfo!] +} + +"Driver file information." +type DriverFileInfo @since(version: "24.3.2") { + "Driver file unique ID" + id: ID! + "Driver file name" + fileName: String! + "Path to the driver file icon" + icon: String } enum ResultDataFormat { @@ -239,6 +404,13 @@ enum ResultDataFormat { timeseries } +enum DriverConfigurationType { + "Driver uses host, port, database and server name fields" + MANUAL, + "Driver uses URL field" + URL +} + ## Network handler config enum NetworkHandlerType { @@ -247,12 +419,17 @@ enum NetworkHandlerType { CONFIG } +"SSH network handler authentication type" enum NetworkHandlerAuthType { PASSWORD, PUBLIC_KEY, AGENT } +""" +Network handler descriptor. +This descriptor is used to describe network handlers (SSH/SSL) that can be used for connections. +""" type NetworkHandlerDescriptor { id: ID! codeName: String! @@ -260,26 +437,47 @@ type NetworkHandlerDescriptor { description: String secured: Boolean! type: NetworkHandlerType + "Properties that can be displayed in the UI" properties: [ObjectPropertyInfo!]! } +""" +SSH/SSL network handler config. Name without prefix only for backward compatibility +""" type NetworkHandlerConfig { id: ID! + "Defines if the network handler is enabled" enabled: Boolean! - authType: NetworkHandlerAuthType! + "SSH network handler auth type" + authType: NetworkHandlerAuthType! @deprecated(reason: "use properties") + "SSH network handler user name" userName: String + "SSH network handler user password" password: String - key: String + "SSH network handler private key" + key: String @deprecated(reason: "use secured properties") + "A flag that indicates if the password should be saved in the secure storage" savePassword: Boolean! + "Network handler properties (name/value)" properties: Object! + "Network handler secure properties (name/value). Used for passwords and keys" + secureProperties: Object! } -# Connection instance +type SecretInfo { + displayName: String! + secretId: String! +} + +"Connection instance" type ConnectionInfo { + "Connection unique ID" id: ID! + "ID of the driver that is used for this connection (see DriverInfo)" driverId: ID! - + "Connection name" name: String! + "Connection description" description: String host: String @@ -288,40 +486,89 @@ type ConnectionInfo { databaseName: String url: String - properties: Object + "Main connection properties. Contains host, port, database, server name fields" + mainPropertyValues: Object @since(version: "24.1.2") + + "Expert connection settings. Contains expert settings properties (like keep-alive interval or auto-commit) that are not often used" + expertSettingsValues: Object @since(version: "25.2.1") - template: Boolean! + "Connection keep-alive interval in seconds" + keepAliveInterval: Int! + "Defines if the connection is in auto-commit mode" + autocommit: Boolean + + properties: Object + "Indicates if the connection is already connected to the database" connected: Boolean! provided: Boolean! + "Indicates if the connection is read-only (no data modification allowed)" readOnly: Boolean! + "Forces connection URL use, host/port/database parameters will be ignored" useUrl: Boolean! + + "Forces credentials save. This flag doesn't work in shared projects." saveCredentials: Boolean! + "Shared credentials - the same for all users, stored in secure storage." + sharedCredentials: Boolean! + + sharedSecrets: [SecretInfo!]! @since(version: "23.3.5") + """ + Determines that credentials were saved for current user. + This field read is slow, it should be read only when it really needed + """ + credentialsSaved: Boolean! + """ + Determines that additional credentials are needed to connect + This field read is slow, it should be read only when it really needed + """ + authNeeded: Boolean! + "ID of the connection folder where this connection is stored" folder: ID + "Node path of the connection in the navigator" nodePath: String + "Connection time in ISO format" connectTime: String + "Connection error if any" connectionError: ServerError + "Server version that is used for this connection" serverVersion: String + "Client version that is used for this connection" clientVersion: String origin: ObjectOrigin! - authNeeded: Boolean! + "ID of the auth model that is used for this connection (see authModels)" authModel: ID authProperties: [ObjectPropertyInfo!]! providerProperties: Object! networkHandlersConfig: [NetworkHandlerConfig!]! - # Supported features (provided etc) + "Supported features (provided etc)" features: [ String! ]! navigatorSettings: NavigatorSettings! supportedDataFormats: [ ResultDataFormat! ]! + configurationType: DriverConfigurationType + + #Access properties + canViewSettings: Boolean! + canEdit: Boolean! + canDelete: Boolean! + + projectId: ID! + requiredAuth: String + defaultCatalogName: String @since(version: "25.0.5") + defaultSchemaName: String @since(version: "25.0.5") + + "List of tools that can be used with this connection. Returns empty list if no tools are available" + tools: [String!]! @since(version: "24.1.3") } type ConnectionFolderInfo { id: ID! + projectId: ID! description: String } @@ -350,6 +597,27 @@ type NavigatorSettings { hideVirtualModel: Boolean! } +type RMResourceType { + id: String! + displayName: String! + icon: String + fileExtensions: [String!]! + rootFolder: String +} + +type ProjectInfo { + id: String! + global: Boolean! + shared: Boolean! + name: String! + description: String + canEditDataSources: Boolean! + canViewDataSources: Boolean! + canEditResources: Boolean! + canViewResources: Boolean! + resourceTypes: [RMResourceType!]! +} + type LogEntry { time: DateTime type: String! @@ -373,68 +641,98 @@ input NavigatorSettingsInput { input NetworkHandlerConfigInput { id: ID! + "Defines if the network handler should be enabled" enabled: Boolean - authType: NetworkHandlerAuthType + "Network handler type (TUNNEL, PROXY, CONFIG)" + authType: NetworkHandlerAuthType @deprecated (reason: "use properties") + "Sets user name for the network handler (SSH)" userName: String + "Sets user password for the network handler (SSH)" password: String - key: String + "Sets private key for the network handler (SSH)" + key: String @deprecated(reason: "use secured properties") + "Sets a flag that indicates if the password should be saved in the secure storage" savePassword: Boolean + "Network handler properties (name/value)" properties: Object + "Network handler secure properties (name/value). Used for passwords and keys" + secureProperties: Object } -# Configuration of particular connection. Used for new connection create. Includes auth info +"Configuration of particular connection. Used for new connection create. Includes auth info" input ConnectionConfig { - # used only for testing created connection + "used only for testing created connection" connectionId: String name: String description: String - # ID of template connection - templateId: ID - # ID of database driver + "ID of database driver" driverId: ID # Custom connection parameters (all optional) - host: String port: String serverName: String databaseName: String - # Connection url jdbc:{driver}://{host}[:{port}]/[{database}] + + "Host, port, serverName, databaseName are also stored in mainPropertyValues for custom pages" + mainPropertyValues: Object @since(version: "24.1.2") + + "Keep-alive, auto-commit, read-only and other expert settings are stored in expertSettingsValues" + expertSettingsValues: Object @since(version: "25.2.1") + + "Sets connection URL jdbc:{driver}://{host}[:{port}]/[{database}]" url: String - # Properties + + "Set properties list" properties: Object - # Template connection - template: Boolean - # Read-onyl connection - readOnly: Boolean + "Set keep-alive interval" + keepAliveInterval: Int @deprecated(reason: "25.2.1 use expertPropertyValues instead") + + "Sets auto-commit connection state" + autocommit: Boolean @deprecated(reason: "25.2.1 use expertPropertyValues instead") + + "Sets read-only connection state" + readOnly: Boolean @deprecated(reason: "25.2.1 use expertPropertyValues instead") # User credentials + "Flag for saving credentials in secure storage" saveCredentials: Boolean + "Flag for using shared credentials." + sharedCredentials: Boolean + "Auth model ID that will be used for connection" authModelId: ID + "Secret ID that will be used for connection" + selectedSecretId: ID @since(version: "23.3.5") + "Credentials for the connection (usually user name and password but it may vary for different auth models)" credentials: Object - # Map of provider properties (name/value) - + "Returns map of provider properties (name/value)" providerProperties: Object - # Network handlers. Map of id->property map (name/value). - + "Returns network handlers configuration. Map of id->property map (name/value)." networkHandlersConfig: [NetworkHandlerConfigInput!] #### deprecated fields - # ID of predefined datasource - dataSourceId: ID #@deprecated + "ID of predefined datasource" + dataSourceId: ID @deprecated - # Direct user credentials - userName: String #@deprecated - userPassword: String #@deprecated + "Direct user credentials" + userName: String @deprecated(reason: "use credentials") + userPassword: String @deprecated(reason: "use credentials") - # Folder + "Defines in which connection folder the connection should be created" folder: ID + + "Configuration type (MANUAL, URL)" + configurationType: DriverConfigurationType + "Sets catalog name for the connection" + defaultCatalogName: String @since(version: "25.0.5") @deprecated(reason: "25.2.1 use expertPropertyValues instead") + "Sets schema name for the connection" + defaultSchemaName: String @since(version: "25.0.5") @deprecated(reason: "25.2.1 use expertPropertyValues instead") } #################################################### @@ -442,99 +740,108 @@ input ConnectionConfig { #################################################### extend type Query { - # Returns server config + "Returns server config" serverConfig: ServerConfig! + "Returns server system information properties" + systemInfo: [ObjectPropertyInfo!]! @since(version: "24.3.5") - # Returns session state ( initialize if not ) + "Returns product settings" + productSettings: ProductSettings! @since(version: "24.0.1") + + "Returns session state ( initialize if not )" sessionState: SessionInfo! - # Session permissions + "Returns session permissions" sessionPermissions: [ID]! - # Get driver info + "Returns list of available drivers" driverList( id: ID ): [ DriverInfo! ]! + "Returns list of available database auth models" authModels: [DatabaseAuthModel!]! + "Returns list of available network handlers" networkHandlers: [NetworkHandlerDescriptor!]! - # List of user connections. - userConnections( id: ID ): [ ConnectionInfo! ]! - # List of template connections. - templateConnections: [ ConnectionInfo! ]! + "Returns list of user connections" + userConnections( projectId: ID, id: ID, projectIds: [ID!] ): [ ConnectionInfo! ]! - # List of connection folders - connectionFolders( path: ID ): [ ConnectionFolderInfo! ]! + "Returns list of connection folders" + connectionFolders( projectId: ID, path: ID ): [ ConnectionFolderInfo! ]! - # Return connection state - connectionState( id: ID! ): ConnectionInfo! @deprecated + "Returns connection info" + connectionInfo( projectId: ID!, id: ID! ): ConnectionInfo! - # Return connection info - connectionInfo( id: ID! ): ConnectionInfo! + "Returns list of accessible user projects" + listProjects: [ ProjectInfo! ]! + "Reads session log entries" readSessionLog(maxEntries: Int, clearEntries: Boolean): [ LogEntry! ]! } extend type Mutation { - # Initialize session + "Initialize session" openSession(defaultLocale: String): SessionInfo! - # Destroy session + "Destroy session" closeSession: Boolean - # Refreshes session on server and returns its state - touchSession: Boolean + "Refreshes session on server and returns its state" + touchSession: Boolean @deprecated(reason: "use events to update session") + "Refreshes session on server and returns session state" + updateSession: SessionInfo! @since(version: "24.0.0") @deprecated(reason: "use events to update session") - # Refresh session connection list + "Refresh session connection list" refreshSessionConnections: Boolean - # Refreshes session on server and returns its state + "Change session language to specified" changeSessionLanguage(locale: String): Boolean - # Create new custom connection. Custom connections exist only within the current session. - createConnection( config: ConnectionConfig! ): ConnectionInfo! - - updateConnection( config: ConnectionConfig! ): ConnectionInfo! + "Create new custom connection" + createConnection( config: ConnectionConfig!, projectId: ID ): ConnectionInfo! - deleteConnection( id: ID! ): Boolean! + "Update specified connection" + updateConnection( config: ConnectionConfig!, projectId: ID ): ConnectionInfo! - createConnectionFromTemplate( templateId: ID!, connectionName: String ): ConnectionInfo! + "Delete specified connection" + deleteConnection( id: ID!, projectId: ID ): Boolean! - # Create new folder - createConnectionFolder(parentFolderPath: ID, folderName: String! ): ConnectionFolderInfo! + "Create new folder for connections" + createConnectionFolder(parentFolderPath: ID, folderName: String!, projectId: ID ): ConnectionFolderInfo! - deleteConnectionFolder( folderPath: ID! ): Boolean! + "Delete specified connection folder" + deleteConnectionFolder( folderPath: ID!, projectId: ID ): Boolean! - # Copies connection configuration from node - copyConnectionFromNode( nodePath: String!, config: ConnectionConfig ): ConnectionInfo! + "Copies connection configuration from node" + copyConnectionFromNode( nodePath: String!, config: ConnectionConfig, projectId: ID ): ConnectionInfo! - # Test connection configuration. Returns remote server version - testConnection( config: ConnectionConfig! ): ConnectionInfo! + "Test connection configuration. Returns remote server version" + testConnection( config: ConnectionConfig!, projectId: ID): ConnectionInfo! - # Test connection configuration. Returns remote server version + "Test network handler" testNetworkHandler( config: NetworkHandlerConfigInput! ): NetworkEndpointInfo! - # Initiate existing connection - initConnection( id: ID!, credentials: Object, networkCredentials: [NetworkHandlerConfigInput!], saveCredentials: Boolean ): ConnectionInfo! + "Initiate existing connection" + initConnection( + id: ID!, + projectId: ID, + credentials: Object, + networkCredentials: [NetworkHandlerConfigInput!], + saveCredentials:Boolean, + sharedCredentials: Boolean, + selectedSecretId:String + ): ConnectionInfo! - # Disconnect from database - closeConnection( id: ID! ): ConnectionInfo! + "Disconnect from database" + closeConnection( id: ID!, projectId: ID ): ConnectionInfo! - # Changes navigator settings for connection - setConnectionNavigatorSettings( id: ID!, settings: NavigatorSettingsInput!): ConnectionInfo! + "Change navigator settings for connection" + setConnectionNavigatorSettings( id: ID!, projectId: ID, settings: NavigatorSettingsInput!): ConnectionInfo! #### Generic async functions + "Cancel async task by ID" asyncTaskCancel(id: String!): Boolean + "Get async task info by ID" asyncTaskInfo(id: String!, removeOnFinish: Boolean!): AsyncTaskInfo! - - - #### Deprecated API - - # Create connection from template. Use createConnection instead - openConnection( config: ConnectionConfig! ): ConnectionInfo! @deprecated - - # Use asyncTaskInfo instead - asyncTaskStatus(id: String!): AsyncTaskInfo! @deprecated - } diff --git a/internal/pkg/cloudbeaver/schema/service.data.transfer.graphqls b/internal/pkg/cloudbeaver/schema/service.data.transfer.graphqls index bdf22420d..6684326f4 100644 --- a/internal/pkg/cloudbeaver/schema/service.data.transfer.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.data.transfer.graphqls @@ -14,36 +14,71 @@ type DataTransferProcessorInfo { isHTML: Boolean } +input DataTransferOutputSettingsInput { + insertBom: Boolean + encoding: String + timestampPattern: String + compress: Boolean + fileName: String +} + +type DataTransferOutputSettings { + insertBom: Boolean! + encoding: String! + timestampPattern: String! + compress: Boolean! +} + +type DataTransferDefaultExportSettings { + outputSettings : DataTransferOutputSettings! + supportedEncodings: [String!]! +} + input DataTransferParameters { - # Processor ID + "Processor ID" processorId: ID! - # General settings: - # - openNewConnection: opens new database connection for data transfer task + """ + General settings: + - openNewConnection: opens new database connection for data transfer task + """ settings: Object - # Processor properties. See DataTransferProcessorInfo.properties + "Processor properties. See DataTransferProcessorInfo.properties" processorProperties: Object! - # Data filter settings + "Consumer properties. See StreamConsumerSettings" + outputSettings: DataTransferOutputSettingsInput + "Data filter settings" filter: SQLDataFilter } extend type Query { - # Available transfer processors + "Returns available transfer processors for data transfer export" dataTransferAvailableStreamProcessors: [ DataTransferProcessorInfo! ]! + "Returns available transfer processors for data transfer import" + dataTransferAvailableImportStreamProcessors: [ DataTransferProcessorInfo! ]! + + "Returns default export settings for data transfer" + dataTransferDefaultExportSettings: DataTransferDefaultExportSettings! + + "Creates async task for data transfer export from the container node path" dataTransferExportDataFromContainer( + projectId: ID, connectionId: ID!, containerNodePath: ID!, parameters: DataTransferParameters! ): AsyncTaskInfo! + "Creates async task for data transfer export from results" dataTransferExportDataFromResults( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, parameters: DataTransferParameters! ): AsyncTaskInfo! - dataTransferRemoveDataFile(dataFileId: String!): Boolean + "Deletes data transfer file by ID" + dataTransferRemoveDataFile(dataFileId: String!): Boolean @deprecated(reason: "25.0.1") } diff --git a/internal/pkg/cloudbeaver/schema/service.metadata.graphqls b/internal/pkg/cloudbeaver/schema/service.metadata.graphqls index 0fde710b5..4135299da 100644 --- a/internal/pkg/cloudbeaver/schema/service.metadata.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.metadata.graphqls @@ -3,6 +3,9 @@ extend type Query { # Get child nodes + "Returns node DDL for the specified node ID" metadataGetNodeDDL(nodeId: ID!, options: Object): String + "Returns extended node DDL for the specified node ID (e.g., Oracle or MySQL package)" + metadataGetNodeExtendedDDL(nodeId: ID!): String } diff --git a/internal/pkg/cloudbeaver/schema/service.navigator.graphqls b/internal/pkg/cloudbeaver/schema/service.navigator.graphqls index 7ce82d263..10dd6a8e6 100644 --- a/internal/pkg/cloudbeaver/schema/service.navigator.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.navigator.graphqls @@ -24,17 +24,19 @@ type ObjectDetails { } type DatabaseObjectInfo { - # Object name + " Object name" name: String - # Description - optional + " Description - optional" description: String - # Object type. Java class name in most cases + " Object type. Java class name in most cases" type: String - # Read object properties. - # Optional parameter 'ids' filters properties by id. null means all properties. - # Note: property value reading may take a lot of time so don't read all property values always - # Examine property meta (features in particular) before reading them + """ + Read object properties. + Optional parameter 'ids' filters properties by id. null means all properties. + Note: property value reading may take a lot of time so don't read all property values always + Examine property meta (features in particular) before reading them + """ properties(filter: ObjectPropertyFilter): [ ObjectPropertyInfo ] # Optional properties @@ -45,44 +47,65 @@ type DatabaseObjectInfo { uniqueName: String state: String - # Features: script, scriptExtended, dataContainer, dataManipulator, - # entity, schema, catalog + "Features: script, scriptExtended, dataContainer, dataManipulator, entity, schema, catalog" features: [ String! ] - # Supported editors: ddl, permissions, sourceDeclaration, sourceDefinition + " Supported editors: ddl, permissions, sourceDeclaration, sourceDefinition" editors: [ String! ] } type NavigatorNodeInfo { - # Node ID - generally a full path to the node from root of tree + "Node ID - generally a full path to the node from root of tree" id: ID! - # Node human readable name + "Node URI - a unique path to a node including all parent nodes" + uri: ID! @since(version: "23.3.1") + "Node human readable name" name: String - #Node full name - fullName: String - # Node icon path + "Node full name" + fullName: String @deprecated(reason: "use name parameter (23.2.0)") + "Node plain name (23.2.0)" + plainName: String + "Node icon path" icon: String - # Node description + "Node description" description: String - # Node type + "Node type" nodeType: String - # Can this property have child nodes? - hasChildren: Boolean + "Can this property have child nodes?" + hasChildren: Boolean! + "Project id of the node" + projectId: String - # Associated object. Maybe null for non-database objects + "Associated object. Maybe null for non-database objects" object: DatabaseObjectInfo - # Supported features: item, container, leaf - # canDelete, canRename + """ + Associated object. Return value depends on the node type - connectionId for connection node, resource path for resource node, etc. + null - if node currently not support this property + """ + objectId: String @since(version: "23.2.4") + + "Supported features: item, container, leaf, canDelete, canRename" features: [ String! ] - # Object detailed info. - # If is different than properties. It doesn't perform any expensive operation and doesn't require authentication. + """ + Object detailed info. + If is different than properties. It doesn't perform any expensive operation and doesn't require authentication. + """ nodeDetails: [ ObjectPropertyInfo! ] - folder: Boolean - inline: Boolean - navigable: Boolean + folder: Boolean! + inline: Boolean! + navigable: Boolean! + filtered: Boolean! + + "Reads node filter. Expensive invocation, read only when it is really needed" + filter: NavigatorNodeFilter +} + +type NavigatorNodeFilter { + include: [String!] + exclude: [String!] } type DatabaseCatalog { @@ -91,6 +114,7 @@ type DatabaseCatalog { } type DatabaseStructContainers { + parentNode: NavigatorNodeInfo catalogList: [ DatabaseCatalog! ]! schemaList: [ NavigatorNodeInfo! ]! supportsCatalogChange: Boolean! @@ -103,34 +127,45 @@ type DatabaseStructContainers { extend type Query { - # Get child nodes + "Returns child nodes based on parent node path" navNodeChildren( parentPath: ID!, offset: Int, limit: Int, onlyFolders: Boolean): [ NavigatorNodeInfo! ]! - # Get child nodes - navNodeParents(nodePath: ID!): [ NavigatorNodeInfo! ]! + "Returns parent nodes for the specified node path" + navNodeParents( nodePath: ID! ): [ NavigatorNodeInfo! ]! + "Returns node info for the specified node path" navNodeInfo( nodePath: ID! ): NavigatorNodeInfo! - navRefreshNode( nodePath: ID! ): Boolean + "Refreshes node based on the node path" + navRefreshNode( nodePath: ID! ): Boolean @deprecated # Use navReloadNode method from Mutation (24.2.4) # contextId currently not using - navGetStructContainers( connectionId: ID!, contextId: ID, catalog: ID ): DatabaseStructContainers! + navGetStructContainers( projectId: ID, connectionId: ID!, contextId: ID, catalog: ID ): DatabaseStructContainers! } extend type Mutation { - # Rename node and returns new node name + "Reloads node and returns updated node info" + navReloadNode( nodePath: ID! ): NavigatorNodeInfo! + + "Renames node and returns new node name" navRenameNode( nodePath: ID!, newName: String! ): String - # Deletes nodes with specified IDs and returns number of deleted nodes + "Deletes nodes with specified IDs and returns number of deleted nodes" navDeleteNodes( nodePaths: [ID!]! ): Int - # Moves nodes with specified IDs to the connection folder - navMoveNodesToFolder(nodePaths: [ID!]!, folderPath: ID!): Boolean + "Moves nodes with specified IDs to the connection folder" + navMoveNodesToFolder( nodePaths: [ID!]!, folderPath: ID!): Boolean! + + """ + Sets filter for the folder node. If both include and exclude are null then filter is removed. + Node must be refreshed after applying filters. Node children can be changed + """ + navSetFolderFilter( nodePath: ID!, include: [String!], exclude: [String!]): Boolean! } \ No newline at end of file diff --git a/internal/pkg/cloudbeaver/schema/service.rm.graphqls b/internal/pkg/cloudbeaver/schema/service.rm.graphqls index d74b84027..005470b9b 100644 --- a/internal/pkg/cloudbeaver/schema/service.rm.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.rm.graphqls @@ -1,60 +1,126 @@ # Metadata queries type RMProject { - id: String! + id: ID! name: String! description: String shared: Boolean! + global: Boolean! createTime: DateTime! creator: String! + projectPermissions: [String!]! + resourceTypes: [RMResourceType!]! } type RMResource { name: String! folder: Boolean! length: Int! + # Properties map + properties: Object +} + +input RMSubjectProjectPermissions { + subjectId: String! + permissions: [String!]! +} + + +input RMProjectPermissions { + projectId: String! + permissions: [String!]! } extend type Query { - # List accessible projects + "List accessible projects for a current user" rmListProjects: [RMProject!]! - # List accessible projects + "List shared projects for a current user" + rmListSharedProjects: [RMProject!]! + + "Returns project information by projectId" + rmProject(projectId: String!): RMProject! + + "Returns available project permissions. Can be read only by users with admin permissions" + rmListProjectPermissions: [AdminPermissionInfo!]! + + "Returns project permissions for the specified project. Can be read only by users with admin permissions" + rmListProjectGrantedPermissions(projectId: String!): [AdminObjectGrantInfo!]! + + "Returns all project grants bysubjectId. Can be read only by users with admin permissions" + rmListSubjectProjectsPermissionGrants(subjectId: String!): [AdminObjectGrantInfo!]! + + "Returns resources in the specified project and folder. If folder is not specified, returns resources in the root folder" rmListResources( projectId: String!, folder: String, nameMask: String, readProperties: Boolean, - readHistory: Boolean): [RMResource!]! + readHistory: Boolean + ): [RMResource!]! - # Reads resource contents as string in UTF-8 + "Reads resource contents as string in UTF-8" rmReadResourceAsString( projectId: String!, - resourcePath: String!): String! + resourcePath: String! + ): String! } extend type Mutation { - + "Creates a new resource in the specified project and folder. If isFolder is true then creates a folder, otherwise creates a file" rmCreateResource( projectId: String!, resourcePath: String!, - isFolder: Boolean!): String! + isFolder: Boolean! + ): String! + "Moves resource to the specified new path in the same project. Can be used to rename a resource" rmMoveResource( projectId: String!, oldResourcePath: String!, - newResourcePath: String): String! + newResourcePath: String + ): String! + "Deletes resource by path in the specified project. If recursive is true then deletes all sub-resources in the folder" rmDeleteResource( projectId: String!, resourcePath: String!, - recursive: Boolean!): Boolean + recursive: Boolean! + ): Boolean + """ + Writes string content to the resource. + If forceOverwrite is true then overwrites existing resource, otherwise throws an error if resource already exists + """ rmWriteResourceStringContent( projectId: String!, resourcePath: String!, - data: String!): String! + data: String!, + forceOverwrite: Boolean! + ): String! + + "Creates a new project with the specified projectId and projectName." + rmCreateProject( + projectId: ID, + projectName: String!, + description: String + ): RMProject! + + "Deletes project by projectId. Returns true if project was deleted, false if project not found" + rmDeleteProject(projectId: ID!): Boolean! + + rmSetProjectPermissions(projectId: String!, permissions: [RMSubjectProjectPermissions!]!): Boolean! @deprecated(reason: "use setConnectionSubjectAccess") + + rmSetSubjectProjectPermissions(subjectId: String!, permissions: [RMProjectPermissions!]!): Boolean! @deprecated + + "Adds project permissions to the specified projects based on subject IDs and permissions. Returns true if permissions were added successfully." + rmAddProjectsPermissions(projectIds: [ID!]!, subjectIds: [ID!]!, permissions:[String!]! ): Boolean @since(version: "23.2.2") + "Deletes project permissions from the specified projects based on subject IDs and permissions. Returns true if permissions were deleted successfully." + rmDeleteProjectsPermissions(projectIds: [ID!]!, subjectIds: [ID!]!, permissions:[String!]!): Boolean @since(version: "23.2.2") + + "Sets resource property by name. If value is null then removes the property (e.g., sets relation between resource and connection)." + rmSetResourceProperty(projectId: String!, resourcePath: String!, name: ID!, value: String): Boolean! } \ No newline at end of file diff --git a/internal/pkg/cloudbeaver/schema/service.sql.graphqls b/internal/pkg/cloudbeaver/schema/service.sql.graphqls index 3c3d66543..fe9ba8235 100644 --- a/internal/pkg/cloudbeaver/schema/service.sql.graphqls +++ b/internal/pkg/cloudbeaver/schema/service.sql.graphqls @@ -42,7 +42,9 @@ type SQLCompletionProposal { type SQLContextInfo { id: ID! + projectId: ID! connectionId: ID! + autoCommit: Boolean defaultCatalog: String defaultSchema: String @@ -59,7 +61,7 @@ input SQLDataFilterConstraint { } input SQLDataFilter { - # Row offset. We use Float because offset may be bigger than 32 bit. + "Row offset. We use Float because offset may be bigger than 32 bit." offset: Float limit: Int @@ -78,18 +80,27 @@ type SQLResultColumn { dataKind: String typeName: String fullTypeName: String - # Column value max length. We use Float because it may be bigger than 32 bit. + "Column value max length. We use Float because it may be bigger than 32 bit" maxLength: Float scale: Int precision: Int required: Boolean! + autoGenerated: Boolean! readOnly: Boolean! readOnlyStatus: String - # Operations supported for this attribute + "Operations supported for this attribute" supportedOperations: [DataTypeLogicalOperation!]! + + "Description of the column" + description: String @since(version: "25.1.3") +} + +type SQLResultRowMetaData { + data: [Object]! + metaData: Object } type DatabaseDocument { @@ -100,17 +111,32 @@ type DatabaseDocument { } type SQLResultSet { + "Result set ID" id: ID! + "Returns list of columns in the result set" columns: [ SQLResultColumn ] - rows: [ [ Object ] ] + "Returns list of rows in the result set. Each row is an array of column values" + rows: [ [ Object ] ] @deprecated(reason: "use rowsWithMetaData (23.3.5)") + "Returns list of rows in the result set. Each row contains data and metadata" + rowsWithMetaData: [SQLResultRowMetaData] @since(version: "23.3.5") # True means that resultset was generated by single entity query # New rows can be added, old rows can be deleted singleEntity: Boolean! # server always returns hasMoreData = false hasMoreData: Boolean! - # can't update data or load LOB file if hasRowIdentifier = false + "Identifies if result set has row identifier. If true then it is possible update data or load LOB files" hasRowIdentifier: Boolean! + "Identifies if result has children collections. If true then children collections can be read from the result set" + hasChildrenCollection: Boolean! + "Identifies if result set supports dynamic trace. If true then dynamic trace can be read from the result set" + hasDynamicTrace: Boolean! @since(version: "24.1.2") + "Identifies if result set supports data filter. If true then data filter can be applied to the result set" + isSupportsDataFilter: Boolean! + "Identifies if result set is read-only. If true then no updates are allowed" + readOnly: Boolean! @since(version: "25.0.1") + "Status of read-only result set. If readOnly is true then this field contains reason why result set is read-only" + readOnlyStatus: String @since(version: "25.0.1") } type SQLQueryResults { @@ -132,6 +158,10 @@ type SQLExecuteInfo { duration: Int! # Actual conditions applied to query filterText: String +# # original sql query without SQLDataFilter +# originalQuery: String + # Full query that was executed, contains all used filters + fullQuery: String # Results results: [ SQLQueryResults! ]! } @@ -139,6 +169,12 @@ type SQLExecuteInfo { input SQLResultRow { data: [ Object ]! updateValues: Object + metaData: Object +} + +input SQLResultRowMetaDataInput { + data: [Object] + metaData: Object! } type DataTypeLogicalOperation { @@ -191,18 +227,49 @@ type SQLScriptQuery { start: Int! end: Int! } + +#################################################### +# Dynamic trace info +#################################################### +type DynamicTraceProperty { + name: String! + value: String + description: String +} + +#################################################### +# Transactional info +#################################################### +type TransactionLogInfoItem { + id: Int! + time: DateTime! + type: String! + queryString: String! + durationMs: Int! + rows: Int! + result: String! +} +type TransactionLogInfos { + count: Int! + transactionLogInfos: [TransactionLogInfoItem!]! +} + + #################################################### # Query and Mutation #################################################### extend type Query { - sqlDialectInfo( connectionId: ID! ): SQLDialectInfo + "Returns SQL dialect info for the specified connection" + sqlDialectInfo( projectId: ID, connectionId: ID! ): SQLDialectInfo - # Lists SQL contexts for a connection (optional) or returns the particular context info - sqlListContexts( connectionId: ID, contextId: ID ): [ SQLContextInfo ]! + "Lists SQL contexts for a connection (optional) or returns the particular context info" + sqlListContexts( projectId: ID, connectionId: ID, contextId: ID ): [ SQLContextInfo ]! + "Returns proposals for SQL completion at the specified position in the query" sqlCompletionProposals( + projectId: ID, connectionId: ID!, contextId: ID!, query: String!, @@ -211,68 +278,95 @@ extend type Query { simpleMode: Boolean ): [ SQLCompletionProposal ] + "Formats SQL query and returns formatted query string" sqlFormatQuery( + projectId: ID, connectionId: ID!, contextId: ID!, query: String! ): String! + "Returns suported operations for the specified attribute index in the results" sqlSupportedOperations( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, attributeIndex: Int! ): [DataTypeLogicalOperation!]! - # List of all available entity query generators - sqlEntityQueryGenerators(nodePathList: [String!]! - ): [SQLQueryGenerator!]! - - # Options: - # fullyQualifiedNames: Boolean - # compactSQL: Boolean - # showComments: Boolean - # showPermissions: Boolean - # showFullDdl: Boolean - # excludeAutoGeneratedColumn: Boolean - # useCustomDataFormat: Boolean + "Returns list of all available entity query generators" + sqlEntityQueryGenerators(nodePathList: [String!]!): [SQLQueryGenerator!]! + + """ + Generates SQL query for the specified entity query generator. + Available options: + fullyQualifiedNames - Use fully qualified names for entities + compactSQL - Use compact SQL format + showComments - Show comments in generated SQL + showPermissions - Show permissions in generated SQL + showFullDdl - Show full DDL in generated SQL + excludeAutoGeneratedColumn - Exclude auto-generated columns in generated SQL + useCustomDataFormat - Use custom data format for generated SQL + """ sqlGenerateEntityQuery( generatorId: String!, options: Object!, nodePathList: [String!]! ): String! + "Parses SQL script and returns script info with queries start and end positions" sqlParseScript( + projectId: ID, connectionId: ID!, script: String! ): SQLScriptInfo! + "Parses SQL query and returns query info with start and end positions" sqlParseQuery( + projectId: ID, connectionId: ID!, script: String!, position: Int! ): SQLScriptQuery! + + "Generates SQL query for grouping data in the specified results" + sqlGenerateGroupingQuery( + projectId: ID, + contextId: ID!, + connectionId: ID!, + resultsId: ID!, + columnNames: [String!], + functions: [String!], + showDuplicatesOnly: Boolean + ): String! } extend type Mutation { - sqlContextCreate( connectionId: ID!, defaultCatalog: String, defaultSchema: String ): SQLContextInfo! + "Creates SQL context for the specified connection" + sqlContextCreate( projectId: ID, connectionId: ID!, defaultCatalog: String, defaultSchema: String ): SQLContextInfo! - sqlContextSetDefaults( connectionId: ID!, contextId: ID!, defaultCatalog: ID, defaultSchema: ID ): Boolean! + "Sets SQL context defaults" + sqlContextSetDefaults( projectId: ID, connectionId: ID!, contextId: ID!, defaultCatalog: ID, defaultSchema: ID ): Boolean! - sqlContextDestroy( connectionId: ID!, contextId: ID! ): Boolean! + "Destroys SQL context and closes all results" + sqlContextDestroy( projectId: ID, connectionId: ID!, contextId: ID! ): Boolean! - # Execute SQL and return results + "Creates async task for executing SQL query" asyncSqlExecuteQuery( + projectId: ID, connectionId: ID!, contextId: ID!, sql: String!, resultId: ID, filter: SQLDataFilter, - dataFormat: ResultDataFormat # requested data format. May be ignored by server + dataFormat: ResultDataFormat, # requested data format. May be ignored by server + readLogs: Boolean # added 23.2.1 ): AsyncTaskInfo! - # Read data from table + "Creates async task for reading data from the container node" asyncReadDataFromContainer( + projectId: ID, connectionId: ID!, contextId: ID!, containerNodePath: ID!, @@ -281,11 +375,31 @@ extend type Mutation { dataFormat: ResultDataFormat ): AsyncTaskInfo! - # Close results (free resources) - sqlResultClose(connectionId: ID!, contextId: ID!, resultId: ID!): Boolean! + "Returns transaction log info for the specified project, connection and context" + getTransactionLogInfo( + projectId: ID!, + connectionId: ID!, + contextId: ID! + ): TransactionLogInfos! + + "Closes SQL results (free resources)" + sqlResultClose(projectId: ID, connectionId: ID!, contextId: ID!, resultId: ID!): Boolean! + + "Creates async task for updating results data in batch mode" + asyncUpdateResultsDataBatch( + projectId: ID!, + connectionId: ID!, + contextId: ID!, + resultsId: ID!, + + updatedRows: [SQLResultRow!], + deletedRows: [SQLResultRow!], + addedRows: [SQLResultRow!], + ): AsyncTaskInfo! @since(version: "25.0.0") - # Update multiple cell values + "Synchronously updates results data in batch mode" updateResultsDataBatch( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, @@ -293,10 +407,11 @@ extend type Mutation { updatedRows: [ SQLResultRow! ], deletedRows: [ SQLResultRow! ], addedRows: [ SQLResultRow! ], - ): SQLExecuteInfo! + ): SQLExecuteInfo! @deprecated(reason: "use async function (25.0.0)") - # Return SQL script for cell values update + "Returns SQL script for cell values update" updateResultsDataBatchScript( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, @@ -306,27 +421,90 @@ extend type Mutation { addedRows: [ SQLResultRow! ], ): String! - #Return BLOB name + "Returns BLOB value" readLobValue( + projectId: ID, connectionId: ID!, contextId: ID!, resultsId: ID!, lobColumnIndex: Int!, row: [ SQLResultRow! ]! - ): String! + ): String! @deprecated(reason: "use sqlReadLobValue (23.3.3)") + + "Returns BLOB value as Base64 encoded string" + sqlReadLobValue( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID!, + lobColumnIndex: Int!, + row: SQLResultRow! + ): String! @since(version: "23.3.3") - # Returns SQLExecuteInfo + "Returns full string value ignoring any limits" + sqlReadStringValue( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID!, + columnIndex: Int!, + row: SQLResultRow! + ): String! @since(version: "23.3.3") + + "Returns SQL execution results for async SQL execute task" asyncSqlExecuteResults(taskId: ID!): SQLExecuteInfo ! - # Read data from table + "Creates async task to generating SQL execution plan" asyncSqlExplainExecutionPlan( + projectId: ID, connectionId: ID!, contextId: ID!, query: String!, configuration: Object! ): AsyncTaskInfo! - # Returns SQLExecutionPlan + "Returns SQL execution plan for async SQL explain task" asyncSqlExplainExecutionPlanResult(taskId: ID!): SQLExecutionPlan ! + "Creates async task to count rows in SQL results" + asyncSqlRowDataCount( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID! + ): AsyncTaskInfo! + + "Returns row count for async SQL row data count task" + asyncSqlRowDataCountResult(taskId: ID!): Int! + + "Reads dynamic trace from provided database results" + sqlGetDynamicTrace( + projectId: ID, + connectionId: ID!, + contextId: ID!, + resultsId: ID! + ): [DynamicTraceProperty!]! @since(version: "24.1.2") + + "Creates async task to set auto-commit mode" + asyncSqlSetAutoCommit( + projectId: ID!, + connectionId: ID!, + contextId: ID!, + autoCommit: Boolean! + ): AsyncTaskInfo! @since(version: "24.0.1") + + "Creates async task to commit transaction" + asyncSqlCommitTransaction( + projectId: ID!, + connectionId: ID!, + contextId: ID! + ): AsyncTaskInfo! @since(version: "24.0.1") + + "Creates async task to rollback transaction" + asyncSqlRollbackTransaction( + projectId: ID!, + connectionId: ID!, + contextId: ID! + ): AsyncTaskInfo! @since(version: "24.0.1") + } diff --git a/internal/pkg/locale/active.en.toml b/internal/pkg/locale/active.en.toml new file mode 100644 index 000000000..c828dfc8f --- /dev/null +++ b/internal/pkg/locale/active.en.toml @@ -0,0 +1,223 @@ +CbOpAuditBlockedSQL = "Audit blocked SQL:" +CbOpAuditResult = "Audit result" +CbOpDataSource = "Db instance" +CbOpDetailAddData = "Added data in db instance(%s): %s" +CbOpDetailDelData = "Deleted data in db instance(%s): %s" +CbOpDetailUpdateData = "Updated data in db instance(%s): %s" +CbOpDetails = "Operation details" +CbOpExecutionResult = "Execution result" +CbOpExecutionTimeMs = "Execution time (ms)" +CbOpOperationIP = "Operation IP" +CbOpOperationTime = "Operation time" +CbOpOperator = "Operator" +CbOpProjectName = "Project name" +CbOpResultRowCount = "Result rows" +CbOpSessionID = "Session ID" +CbOpSuccessRate = "Success rate:" +CbOpTotalExecutions = "Total executions:" +CbOpUnsuccessfulExecutions = "Unsuccessful SQL:" +DBServiceAuditLevel = "Highest audit level for workbench queries [error|warn|notice|normal]" +DBServiceDB2DbName = "DB name (DB2 required)" +DBServiceDataExportRuleTemplateName = "Data Export audit rule template (need to fill out the audit rule template first)" +DBServiceDbName = "DB instance name" +DBServiceDbType = "DB instance type" +DBServiceDesc = "DB instance description" +DBServiceEnvironmentTag = "EnvironmentTag" +DBServiceHost = "DB instance host" +DBServiceNoProblem = "None" +DBServiceOpsTime = "Maintenance time (Optional,9:30-11:00;14:10-18:30)" +DBServiceOracleService = "Service name (Oracle required)" +DBServicePassword = "DB instance password" +DBServicePort = "DB instance port" +DBServiceProblem = "Problem" +DBServiceProjName = "Project name (Existing in the platform)" +DBServiceRuleTemplateName = "Audit rule template (Existing in the project)" +DBServiceSQLQueryRuleTemplateName = "SQL Workbench audit rule template (need to fill out the audit rule template first)" +DBServiceSyncExpand = "DB instance synchronization expansion service" +DBServiceSyncVersion = "Version (Supports DMP5.23.04.0 and above)" +DBServiceUser = "DB instance connection user" +DataExportWorkflowNameDuplicateErr = "Duplicate workflow name, please modify the workflow name and resubmit." +DataWorkflowDefault = "❓ Data Export Workflow Unknown Requests" +DataWorkflowExportFailed = "⚠️ Data Export Workflow Execute Failed" +DataWorkflowExportSuccess = "✅ Data Export Workflow Execute Succeeded" +DataWorkflowReject = "❌ Data Export Workflow Rejected" +DataWorkflowWaitExporting = "⏳ Data Export Workflow Waiting Export" +DataWorkflowWaiting = "🔍 Data Export Workflow Pending " +DescOpPermissionAuditWorkflow = "Approve/reject workflow; Users with this permission can approve/reject workflow" +DescOpPermissionAuthDBServiceData = "Authorize db instance data permissions; Users with this permission can authorize db instance data permissions" +DescOpPermissionCreateOptimization = "Create SQL optimization; Users with this permission can create SQL optimization" +DescOpPermissionCreatePipeline = "Configure pipeline; Users with this permission can configure pipelines for DB instances." +DescOpPermissionCreateProject = "Create project; Configure project resources" +DescOpPermissionCreateWorkflow = "Create/edit workflow; Users with this permission can create/edit workflow" +DescOpPermissionExecuteWorkflow = "Execute workflow; Users with this permission can execute workflow" +DescOpPermissionExportApprovalReject = "Approve/reject data export workflow; Users with this permission can approve/reject data export workflow" +DescOpPermissionExportCreate = "Create data export task; Users with this permission can create data export task or workflow" +DescOpPermissionGlobalManagement = "It has the highest system permissions and can perform operations such as system configuration and user management" +DescOpPermissionGlobalView = "Be responsible for system operation audits, data compliance checks and other work" +DescOpPermissionOrdinaryUser = "Basic function operation permissions, allowing for daily business operations" +DescOpPermissionProjectAdmin = "Project management; Users with this permission can manage all resources under the project" +DescOpPermissionSQLQuery = "SQL workbench query; Users with this permission can execute SQL query" +DescOpPermissionSaveAuditPlan = "View others' created scan task; Users with this permission can view others' created scan task" +DescOpPermissionViewOthersAuditPlan = "Create/edit scan task; Users with this permission can create/edit scan task" +DescOpPermissionViewOthersOptimization = "View others' created SQL optimization; Users with this permission can view others' created SQL optimization" +DescOpPermissionViewOthersWorkflow = "View others' created workflow; Users with this permission can view others' created workflow" +DescOpPermissionViewSQLInsight = "View performance insights; Users with this permission can view performance insights" +DescRoleDevEngineer = "Users with this permission can create/edit workflow, execute SQL query, configure pipelines, create SQL optimization" +DescRoleDevManager = "Users with this permission can view others' created workflow, approve/reject workflow, configure pipelines, view others' created SQL optimization" +DescRoleOpsEngineer = "Users with this permission can view others' created workflow, execute workflow, create scan task, view others' created scan task, create data export task" +DescRoleProjectAdmin = "Project admin" +IDBPCErrDB2DbNameInvalid = "DB2 database name is incorrect" +IDBPCErrDataExportRuleTemplateInvalid = "Data Export audit rule template does not exist or is incompatible with the db instance type" +IDBPCErrDbTypeInvalid = "DB instance type is invalid or corresponding plugin is not installed" +IDBPCErrEnvironmentTagInvalid = "Project environment tag check error or does not exist" +IDBPCErrInvalidInput = "Each column is required unless specified" +IDBPCErrMissingOrInvalidCols = "Missing or invalid columns: %s" +IDBPCErrOptTimeInvalid = "Maintenance time is invalid" +IDBPCErrOracleServiceNameInvalid = "Oracle service name is incorrect" +IDBPCErrProjNonExist = "Project does not exist" +IDBPCErrProjNotActive = "Project status is abnormal" +IDBPCErrProjNotAllowed = "Project is not in operation" +IDBPCErrRuleTemplateBaseCheck = "Audit rule templates need to be added before workbench and data export audit template will take effect" +IDBPCErrRuleTemplateInvalid = "Audit rule template does not exist or is incompatible with the db instance type" +IDBPCErrSQLQueryRuleTemplateInvalid = "SQL Workbench audit rule template does not exist or is incompatible with the db instance type" +LicenseAuthorizedDurationDay = "Authorized days" +LicenseDmsVersion = "DMS Version" +LicenseDurationOfRunning = "Running days" +LicenseEstimatedMaturity = "Expiration date" +LicenseInstanceNum = "Instance num" +LicenseInstanceNumOfType = "Instance num of type:[%v]" +LicenseMachineInfo = "Machine info" +LicenseMachineInfoOfNode = "Machine info of node:[%s]" +LicenseResourceTypeUser = "User" +LicenseUnlimited = "Unlimited" +LicenseUserNum = "User num" +NameOpPermissionAuditWorkflow = "Approve go online workflow" +NameOpPermissionAuthDBServiceData = "Account Management" +NameOpPermissionCreateOptimization = "Create SQL optimization" +NameOpPermissionCreatePipeline = "Configure pipeline" +NameOpPermissionCreateProject = "Project Director" +NameOpPermissionCreateWorkflow = "Create go online workflow" +NameOpPermissionDesensitization = "Desensitization rule configuration permissions" +NameOpPermissionExecuteWorkflow = "Execute go online workflow" +NameOpPermissionExportApprovalReject = "Approve export workflow" +NameOpPermissionExportCreate = "Create data export workflow" +NameOpPermissionGlobalManagement = "System Administrator" +NameOpPermissionGlobalView = "Audit Administrator" +NameOpPermissionManageApprovalTemplate = "Management approval process template" +NameOpPermissionManageAuditRuleTemplate = "Management audit rule template" +NameOpPermissionManageMember = "Manage members and permissions" +NameOpPermissionManageProjectDataSource = "Manage the project data source" +NameOpPermissionManageRoleMange = "Role management authority" +NameOpPermissionManageSQLMangeWhiteList = "Manage SQL exceptions" +NameOpPermissionMangeAuditSQLWhiteList = "Review SQL exceptions" +NameOpPermissionOrdinaryUser = "Ordinary User" +NameOpPermissionProjectAdmin = "Project management" +NameOpPermissionPushRule = "Manage push rules" +NameOpPermissionSQLQuery = "SQL workbench operation permission" +NameOpPermissionSaveAuditPlan = "Configuration sql management" +NameOpPermissionVersionManage = "Configuration version" +NameOpPermissionViewExportTask = "View all exported tasks" +NameOpPermissionViewIDEAuditRecord = "View all IDE review records" +NameOpPermissionViewOperationRecord = "View all operation records" +NameOpPermissionViewOptimizationRecord = "View all optimization records" +NameOpPermissionViewOthersAuditPlan = "View all sql management" +NameOpPermissionViewOthersOptimization = "View others' created SQL optimization" +NameOpPermissionViewOthersWorkflow = "View all workflow" +NameOpPermissionViewPipeline = "View all pipelines" +NameOpPermissionViewSQLInsight = "View performance insights" +NameOpPermissionViewVersionManage = "View version records created by others" +NamePermissionViewQuickAuditRecord = "View all quick review records" +NameRoleDevEngineer = "Developer" +NameRoleDevManager = "Development manager" +NameRoleOpsEngineer = "Operation engineer" +NameRoleProjectAdmin = "Project admin" +NotifyDataWorkflowBodyApprovalReminder = "⏰ The export workflow has been approved. Please complete the export within 1 day, otherwise it will expire and cannot be executed" +NotifyDataWorkflowBodyConfigUrl = "Please add a global URL in the system settings - global configuration" +NotifyDataWorkflowBodyHead = "\n📋 Data Export Workflow Topic: %v\n📍 ProjectName: %v\n🆔 Workflow ID: %v\n📝 Workflow Description: %v\n👤 Applicant: %v\n⏰ Creation Time: %v" +NotifyDataWorkflowBodyInstanceAndSchema = "🗄️ Data Source: %v\n📊 Schema: %v" +NotifyDataWorkflowBodyLink = "🔗 Data Export Workflow Link: %v" +NotifyDataWorkflowBodyReason = "❌ Rejection Reason: %v" +NotifyDataWorkflowBodyReport = "⭐ Data Export Workflow Audit Score: %v" +NotifyDataWorkflowBodyStartEnd = "▶️ Execute Start Time: %v\n◀️ Execute End Time: %v" +NotifyDataWorkflowBodyWorkFlowErr = "⚠️ Failed to read data export workflow task content, please check the workflow status through the SQLE interface" +OAuth2AutoCreateUserErr = "Failed to automatically create user: %v" +OAuth2AutoCreateUserWithoutDefaultPwdErr = "Failed to automatically create user: default password not configured" +OAuth2BackendLogoutFailed = "; Failed to log out of third-party platform session: %v" +OAuth2BackendLogoutSuccess = "; Successfully logged out of third-party platform session" +OAuth2GetConfigErr = "Failed to get OAuth2 configuration: %v" +OAuth2GetTokenErr = "Error obtaining token during OAuth2 flow: %v" +OAuth2GetUserInfoErr = "Error retrieving OAuth2 user information: %v" +OAuth2HandleTokenErr = "Error processing OAuth2 token: %v" +OAuth2ProcessErr = "OAuth2 flow error: %v" +OAuth2QueryBindUserByOAuthIDErr = "Error querying bound user by OAuth2 user ID: %v" +OAuth2QueryBindUserBySameNameErr = "Error querying user with the same name by OAuth2 user ID: %v" +OAuth2SameNameUserIsBoundErr = "The user with the same name found via OAuth2 user ID %q is already bound" +OAuth2SyncSessionErr = "Failed to synchronize OAuth2 session: %v" +OAuth2UserNotBoundAndDisableManuallyBindErr = "No user associated with %q was found and manual binding is disabled; please contact the system administrator" +OAuth2UserNotBoundAndNoPermErr = "This OAuth2 user is not bound and has no login permissions" +OAuth2UserStatIsDisableErr = "User %q is disabled" +OpRecordConfigCompanyNotice = "Update company notice" +OpRecordConfigFeishu = "Update Feishu configuration" +OpRecordConfigLDAP = "Update LDAP configuration" +OpRecordConfigLogin = "Update login configuration" +OpRecordConfigOAuth2 = "Update OAuth2 configuration" +OpRecordConfigSMTP = "Update SMTP configuration" +OpRecordConfigSms = "Update SMS configuration" +OpRecordConfigSystemVariables = "Update system variables configuration" +OpRecordConfigWebhook = "Update Webhook configuration" +OpRecordConfigWechat = "Update WeChat Work configuration" +OpRecordCurrentUserUpdate = "Update account basic info" +OpRecordDBServiceCreate = "Create data source" +OpRecordDBServiceCreateWithName = "Create data source %s" +OpRecordDBServiceDelete = "Delete data source %s" +OpRecordDBServiceImport = "Import data sources" +OpRecordDBServiceUpdate = "Update data source %s" +OpRecordDataExportApproveWithName = "Approve data export workflow %s" +OpRecordDataExportCancel = "Cancel data export workflow" +OpRecordDataExportCancelWithName = "Cancel data export workflow %s" +OpRecordDataExportCreate = "Create data export workflow" +OpRecordDataExportCreateWithName = "Create data export workflow %s" +OpRecordDataExportExportWithName = "Execute data export %s" +OpRecordDataExportRejectWithName = "Reject data export workflow %s" +OpRecordMemberCreate = "Add member" +OpRecordMemberCreateWithName = "Add member %s" +OpRecordMemberDelete = "Delete member %s" +OpRecordMemberGroupCreate = "Add member group" +OpRecordMemberGroupCreateWithName = "Add member group %s" +OpRecordMemberGroupDelete = "Delete member group %s" +OpRecordMemberGroupUpdate = "Update member group %s" +OpRecordMemberUpdate = "Update member %s" +OpRecordProjectArchive = "Archive project %s" +OpRecordProjectCreate = "Create project" +OpRecordProjectCreateWithName = "Create project %s" +OpRecordProjectDelete = "Delete project %s" +OpRecordProjectUnarchive = "Unarchive project %s" +OpRecordProjectUpdate = "Update project %s" +OpRecordRoleCreate = "Create role" +OpRecordRoleCreateWithName = "Create role %s" +OpRecordRoleDelete = "Delete role %s" +OpRecordRoleUpdate = "Update role %s" +OpRecordUserCreate = "Create user" +OpRecordUserCreateWithName = "Create user %s" +OpRecordUserDelete = "Delete user %s" +OpRecordUserUpdate = "Update user %s" +ProjectAvailable = "Available" +ProjectBusiness = "Available business" +ProjectCreateTime = "Create time" +ProjectDesc = "Project description" +ProjectName = "Project name" +ProjectNotAvailable = "Unavailable" +ProjectStatus = "Project status" +SqlWorkbenchAuditCallSQLEErr = "The audit service is busy or unavailable. Please try again later." +SqlWorkbenchMaintenanceTimeBlocked = "Currently outside maintenance window (maintenance hours: %s). Non-query operations are prohibited. Please operate during maintenance hours or submit a change request." +SqlWorkbenchAuditDBServiceMappingNotFoundErr = "Current data source was not found. Please confirm it exists, reselect it, and try again." +SqlWorkbenchAuditGetDBServiceErr = "Current data source configuration was not found. Please confirm the data source exists and try again." +SqlWorkbenchAuditGetDBServiceMappingErr = "We couldn't get the current data source information. Please reselect the data source and try again." +SqlWorkbenchAuditGetDMSUserErr = "Your login session may have expired. Please sign in again and retry." +SqlWorkbenchAuditMissingSQLOrDatasourceErr = "SQL or data source was not detected. Please select a data source and enter SQL, then try again." +SqlWorkbenchAuditNotEnabledErr = "SQL audit is not enabled for this data source. Please enable SQL audit before running." +SqlWorkbenchAuditParseReqErr = "We couldn't parse the request content. Please try again later." +SqlWorkbenchAuditReadReqBodyErr = "We couldn't get the request content, possibly due to network instability. Please try again later." +StatDisable = "Disabled" +StatOK = "Normal" +StatUnknown = "Unknown" diff --git a/internal/pkg/locale/active.zh.toml b/internal/pkg/locale/active.zh.toml new file mode 100644 index 000000000..23f55bc90 --- /dev/null +++ b/internal/pkg/locale/active.zh.toml @@ -0,0 +1,223 @@ +CbOpAuditBlockedSQL = "审核拦截的异常SQL:" +CbOpAuditResult = "审核结果" +CbOpDataSource = "数据源" +CbOpDetailAddData = "在数据源:%s中添加了以下数据:%s" +CbOpDetailDelData = "在数据源:%s中删除了以下数据:%s" +CbOpDetailUpdateData = "在数据源:%s中更新了以下数据:%s" +CbOpDetails = "操作详情" +CbOpExecutionResult = "执行结果" +CbOpExecutionTimeMs = "执行时间(毫秒)" +CbOpOperationIP = "操作IP" +CbOpOperationTime = "操作时间" +CbOpOperator = "操作人" +CbOpProjectName = "项目名" +CbOpResultRowCount = "结果集返回行数" +CbOpSessionID = "会话ID" +CbOpSuccessRate = "执行成功率:" +CbOpTotalExecutions = "执行总量:" +CbOpUnsuccessfulExecutions = "执行不成功的SQL:" +DBServiceAuditLevel = "工作台查询的最高审核等级[error|warn|notice|normal]" +DBServiceDB2DbName = "数据库名(DB2需填)" +DBServiceDataExportRuleTemplateName = "数据导出审核规则模板(需要先填写审核规则模板)" +DBServiceDbName = "数据源名称" +DBServiceDbType = "数据源类型" +DBServiceDesc = "数据源描述" +DBServiceEnvironmentTag = "所属环境" +DBServiceHost = "数据源地址" +DBServiceNoProblem = "无" +DBServiceOpsTime = "运维时间(非必填,9:30-11:00;14:10-18:30)" +DBServiceOracleService = "服务名(Oracle需填)" +DBServicePassword = "数据源密码" +DBServicePort = "数据源端口" +DBServiceProblem = "问题" +DBServiceProjName = "所属项目(平台已有的项目名称)" +DBServiceRuleTemplateName = "审核规则模板(项目已有的规则模板)" +DBServiceSQLQueryRuleTemplateName = "工作台操作审核规则模板(需要先填写审核规则模板)" +DBServiceSyncExpand = "数据源同步扩展服务" +DBServiceSyncVersion = "版本(支持DMP5.23.04.0及以上版本)" +DBServiceUser = "数据源连接用户" +DataExportWorkflowNameDuplicateErr = "工单名称重复了,请您修改工单名称后重新提交工单。" +DataWorkflowDefault = "❓数据导出工单未知请求" +DataWorkflowExportFailed = "⚠️ 数据导出失败" +DataWorkflowExportSuccess = "✅ 数据导出成功" +DataWorkflowReject = "❌ 数据导出工单被驳回" +DataWorkflowWaitExporting = "⏳ 数据导出工单待导出" +DataWorkflowWaiting = "🔍 数据导出工单待审批" +DescOpPermissionAuditWorkflow = "审核/驳回工单;拥有该权限的用户可以审核/驳回工单" +DescOpPermissionAuthDBServiceData = "授权数据源数据权限;拥有该权限的用户可以授权数据源数据权限" +DescOpPermissionCreateOptimization = "创建智能调优;拥有该权限的用户可以创建智能调优" +DescOpPermissionCreatePipeline = "配置流水线;拥有该权限的用户可以为数据源配置流水线" +DescOpPermissionCreateProject = "创建项目、配置项目资源" +DescOpPermissionCreateWorkflow = "创建/编辑工单;拥有该权限的用户可以创建/编辑工单" +DescOpPermissionExecuteWorkflow = "上线工单;拥有该权限的用户可以上线工单" +DescOpPermissionExportApprovalReject = "审批/驳回数据导出工单;拥有该权限的用户可以执行审批导出数据工单或者驳回导出数据工单" +DescOpPermissionExportCreate = "创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单" +DescOpPermissionGlobalManagement = "具备系统最高权限,可进行系统配置、用户管理等操作" +DescOpPermissionGlobalView = "负责系统操作审计、数据合规检查等工作" +DescOpPermissionOrdinaryUser = "基础功能操作权限,可进行日常业务操作" +DescOpPermissionProjectAdmin = "项目管理;拥有该权限的用户可以管理项目下的所有资源" +DescOpPermissionSQLQuery = "SQL工作台查询;拥有该权限的用户可以执行SQL工作台查询" +DescOpPermissionSaveAuditPlan = "创建/编辑扫描任务;拥有该权限的用户可以创建/编辑扫描任务" +DescOpPermissionViewOthersAuditPlan = "查看他人创建的扫描任务;拥有该权限的用户可以查看他人创建的扫描任务" +DescOpPermissionViewOthersOptimization = "查看他人创建的智能调优;拥有该权限的用户可以查看他人创建的智能调优" +DescOpPermissionViewOthersWorkflow = "查看他人创建的工单;拥有该权限的用户可以查看他人创建的工单" +DescOpPermissionViewSQLInsight = "查看性能洞察;拥有该权限的用户可以查看性能洞察的数据" +DescRoleDevEngineer = "拥有该权限的用户可以创建/编辑工单,SQL工作台查询,配置流水线,创建智能调优" +DescRoleDevManager = "拥有该权限的用户可以创建/编辑工单,审核/驳回工单,配置流水线,查看他人创建的智能调优" +DescRoleOpsEngineer = "拥有该权限的用户可以上线工单,查看他人创建的工单,创建智能扫描,查看他人的扫描任务,数据导出" +DescRoleProjectAdmin = "project admin" +IDBPCErrDB2DbNameInvalid = "DB2数据库名错误" +IDBPCErrDataExportRuleTemplateInvalid = "数据导出审核规则模板不存在或数据源类型不匹配" +IDBPCErrDbTypeInvalid = "数据源类型不规范或对应插件未安装" +IDBPCErrEnvironmentTagInvalid = "项目环境标签检查错误或不存在" +IDBPCErrInvalidInput = "若无特别说明每列均为必填" +IDBPCErrMissingOrInvalidCols = "缺失或不规范的列:%s" +IDBPCErrOptTimeInvalid = "运维时间不规范" +IDBPCErrOracleServiceNameInvalid = "Oracle服务名错误" +IDBPCErrProjNonExist = "所属项目不存在" +IDBPCErrProjNotActive = "所属项目状态异常" +IDBPCErrProjNotAllowed = "所属项目不是操作中的项目" +IDBPCErrRuleTemplateBaseCheck = "需要先添加审核规则模板,工作台和数据导出审核模板才会生效" +IDBPCErrRuleTemplateInvalid = "审核规则模板不存在或数据源类型不匹配" +IDBPCErrSQLQueryRuleTemplateInvalid = "工作台操作审核规则模板不存在或数据源类型不匹配" +LicenseAuthorizedDurationDay = "授权运行时长(天)" +LicenseDmsVersion = "DMS版本" +LicenseDurationOfRunning = "已运行时长(天)" +LicenseEstimatedMaturity = "预计到期时间" +LicenseInstanceNum = "实例数" +LicenseInstanceNumOfType = "[%v]类型实例数" +LicenseMachineInfo = "机器信息" +LicenseMachineInfoOfNode = "节点[%s]机器信息" +LicenseResourceTypeUser = "用户" +LicenseUnlimited = "无限制" +LicenseUserNum = "用户数" +NameOpPermissionAuditWorkflow = "审批上线工单" +NameOpPermissionAuthDBServiceData = "账号管理" +NameOpPermissionCreateOptimization = "创建智能调优" +NameOpPermissionCreatePipeline = "流水线增删改" +NameOpPermissionCreateProject = "项目总监" +NameOpPermissionCreateWorkflow = "创建上线工单" +NameOpPermissionDesensitization = "脱敏规则配置权限" +NameOpPermissionExecuteWorkflow = "执行上线工单" +NameOpPermissionExportApprovalReject = "审批导出工单" +NameOpPermissionExportCreate = "创建导出工单" +NameOpPermissionGlobalManagement = "系统管理员" +NameOpPermissionGlobalView = "审计管理员" +NameOpPermissionManageApprovalTemplate = "管理审批流程模版" +NameOpPermissionManageAuditRuleTemplate = "管理审核规则模版" +NameOpPermissionManageMember = "管理成员与权限" +NameOpPermissionManageProjectDataSource = "管理项目数据源" +NameOpPermissionManageRoleMange = "角色管理权限" +NameOpPermissionManageSQLMangeWhiteList = "管控SQL例外" +NameOpPermissionMangeAuditSQLWhiteList = "审核SQL例外" +NameOpPermissionOrdinaryUser = "普通用户" +NameOpPermissionProjectAdmin = "项目管理" +NameOpPermissionPushRule = "管理推送规则" +NameOpPermissionSQLQuery = "SQL工作台操作权限" +NameOpPermissionSaveAuditPlan = "配置SQL管控" +NameOpPermissionVersionManage = "配置版本" +NameOpPermissionViewExportTask = "查看所有导出任务" +NameOpPermissionViewIDEAuditRecord = "查看所有IDE审核记录" +NameOpPermissionViewOperationRecord = "查看所有操作记录" +NameOpPermissionViewOptimizationRecord = "查看所有优化记录" +NameOpPermissionViewOthersAuditPlan = "访问所有管控SQL" +NameOpPermissionViewOthersOptimization = "查看他人创建的智能调优" +NameOpPermissionViewOthersWorkflow = "查看所有工单" +NameOpPermissionViewPipeline = "查看所有流水线" +NameOpPermissionViewSQLInsight = "查看性能洞察" +NameOpPermissionViewVersionManage = "查看他人创建的版本记录" +NamePermissionViewQuickAuditRecord = "查看所有快捷审核记录" +NameRoleDevEngineer = "开发工程师" +NameRoleDevManager = "开发主管" +NameRoleOpsEngineer = "运维工程师" +NameRoleProjectAdmin = "项目管理员" +NotifyDataWorkflowBodyApprovalReminder = "⏰ 导出工单已审批通过,请在1天内完成导出,过期后将无法执行" +NotifyDataWorkflowBodyConfigUrl = "请在系统设置-全局配置中补充全局url" +NotifyDataWorkflowBodyHead = "\n📋 数据导出工单主题: %v\n📍 所属项目: %v\n🆔 数据导出工单ID: %v\n📝 数据导出工单描述: %v\n👤 申请人: %v\n⏰ 创建时间: %v\n" +NotifyDataWorkflowBodyInstanceAndSchema = "🗄️ 数据源: %v\n📊 schema: %v\n" +NotifyDataWorkflowBodyLink = "🔗 数据导出工单链接: %v" +NotifyDataWorkflowBodyReason = "❌ 驳回原因: %v" +NotifyDataWorkflowBodyReport = "⭐ 数据导出工单审核得分: %v" +NotifyDataWorkflowBodyStartEnd = "▶️ 数据导出开始时间: %v\n◀️ 数据导出结束时间: %v" +NotifyDataWorkflowBodyWorkFlowErr = "❌ 读取工单任务内容失败,请通过SQLE界面确认工单状态" +OAuth2AutoCreateUserErr = "自动创建用户失败: %v" +OAuth2AutoCreateUserWithoutDefaultPwdErr = "自动创建用户失败,默认密码未配置" +OAuth2BackendLogoutFailed = ";注销第三方平台会话失败: %v" +OAuth2BackendLogoutSuccess = ";已注销第三方平台会话" +OAuth2GetConfigErr = "获取OAuth2配置失败: %v" +OAuth2GetTokenErr = "OAuth2流程获取Token错误: %v" +OAuth2GetUserInfoErr = "获取 OAuth2 用户信息错误: %v" +OAuth2HandleTokenErr = "处理 OAuth2 Token 错误: %v" +OAuth2ProcessErr = "OAuth2流程错误: %v" +OAuth2QueryBindUserByOAuthIDErr = "通过 OAuth2 用户ID查询绑定用户错误: %v" +OAuth2QueryBindUserBySameNameErr = "通过 OAuth2 用户ID查询同名用户错误: %v" +OAuth2SameNameUserIsBoundErr = "通过 OAuth2 用户ID %q 查询到的同名用户已经被绑定" +OAuth2SyncSessionErr = "同步OAuth2会话失败: %v" +OAuth2UserNotBoundAndDisableManuallyBindErr = "未查询到 %q 关联的用户且关闭了手动绑定功能,请联系系统管理员" +OAuth2UserNotBoundAndNoPermErr = "该OAuth2用户未绑定且没有登陆权限" +OAuth2UserStatIsDisableErr = "用户 %q 被禁用" +OpRecordConfigCompanyNotice = "更新系统公告" +OpRecordConfigFeishu = "更新飞书配置" +OpRecordConfigLDAP = "更新LDAP配置" +OpRecordConfigLogin = "更新登录配置" +OpRecordConfigOAuth2 = "更新OAuth2配置" +OpRecordConfigSMTP = "更新SMTP配置" +OpRecordConfigSms = "更新短信配置" +OpRecordConfigSystemVariables = "更新系统变量配置" +OpRecordConfigWebhook = "更新Webhook配置" +OpRecordConfigWechat = "更新企业微信配置" +OpRecordCurrentUserUpdate = "更新个人中心账号基本信息" +OpRecordDBServiceCreate = "创建数据源" +OpRecordDBServiceCreateWithName = "创建数据源 %s" +OpRecordDBServiceDelete = "删除数据源 %s" +OpRecordDBServiceImport = "导入数据源" +OpRecordDBServiceUpdate = "更新数据源 %s" +OpRecordDataExportApproveWithName = "审批通过数据导出工单 %s" +OpRecordDataExportCancel = "取消数据导出工单" +OpRecordDataExportCancelWithName = "取消数据导出工单 %s" +OpRecordDataExportCreate = "创建数据导出工单" +OpRecordDataExportCreateWithName = "创建数据导出工单 %s" +OpRecordDataExportExportWithName = "执行数据导出 %s" +OpRecordDataExportRejectWithName = "驳回数据导出工单 %s" +OpRecordMemberCreate = "添加成员" +OpRecordMemberCreateWithName = "添加成员 %s" +OpRecordMemberDelete = "删除成员 %s" +OpRecordMemberGroupCreate = "添加成员组" +OpRecordMemberGroupCreateWithName = "添加成员组 %s" +OpRecordMemberGroupDelete = "删除成员组 %s" +OpRecordMemberGroupUpdate = "更新成员组 %s" +OpRecordMemberUpdate = "更新成员 %s" +OpRecordProjectArchive = "归档项目 %s" +OpRecordProjectCreate = "创建项目" +OpRecordProjectCreateWithName = "创建项目 %s" +OpRecordProjectDelete = "删除项目 %s" +OpRecordProjectUnarchive = "取消归档项目 %s" +OpRecordProjectUpdate = "更新项目 %s" +OpRecordRoleCreate = "创建角色" +OpRecordRoleCreateWithName = "创建角色 %s" +OpRecordRoleDelete = "删除角色 %s" +OpRecordRoleUpdate = "更新角色 %s" +OpRecordUserCreate = "创建用户" +OpRecordUserCreateWithName = "创建用户 %s" +OpRecordUserDelete = "删除用户 %s" +OpRecordUserUpdate = "更新用户 %s" +ProjectAvailable = "可用" +ProjectBusiness = "所属业务" +ProjectCreateTime = "创建时间" +ProjectDesc = "项目描述" +ProjectName = "项目名称" +ProjectNotAvailable = "不可用" +ProjectStatus = "项目状态" +SqlWorkbenchAuditCallSQLEErr = "审核服务当前繁忙或不可用,请稍后重试。" +SqlWorkbenchMaintenanceTimeBlocked = "当前处于非运维时间(运维时间:%s),禁止执行非查询类操作。请在运维时间内操作或提交上线工单。" +SqlWorkbenchAuditDBServiceMappingNotFoundErr = "未找到当前数据源,请确认数据源存在并重新选择后重试。" +SqlWorkbenchAuditGetDBServiceErr = "未找到当前数据源配置,请确认数据源存在后重试。" +SqlWorkbenchAuditGetDBServiceMappingErr = "当前数据源信息获取失败,请重新选择数据源后重试。" +SqlWorkbenchAuditGetDMSUserErr = "当前登录状态可能已过期,请重新登录后再试。" +SqlWorkbenchAuditMissingSQLOrDatasourceErr = "未检测到 SQL 或数据源,请确认已选择数据源并输入 SQL 后重试。" +SqlWorkbenchAuditNotEnabledErr = "该数据源尚未开启 SQL 审核,请先在数据源配置中开启“SQL 审核”后再执行。" +SqlWorkbenchAuditParseReqErr = "请求内容解析失败,请稍后重试。" +SqlWorkbenchAuditReadReqBodyErr = "请求内容获取失败,可能网络不稳定,请稍后重试。" +StatDisable = "被禁用" +StatOK = "正常" +StatUnknown = "未知" diff --git a/internal/pkg/locale/locale.go b/internal/pkg/locale/locale.go new file mode 100644 index 000000000..be6ebd58a --- /dev/null +++ b/internal/pkg/locale/locale.go @@ -0,0 +1,20 @@ +package locale + +import ( + "embed" + + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" +) + +//go:embed active.*.toml +var localeFS embed.FS + +var Bundle *i18nPkg.Bundle + +func MustInit(l i18nPkg.Log) { + b, err := i18nPkg.NewBundleFromTomlDir(localeFS, l) + if err != nil { + panic(err) + } + Bundle = b +} diff --git a/internal/pkg/locale/message_zh.go b/internal/pkg/locale/message_zh.go new file mode 100644 index 000000000..19ed3f3fa --- /dev/null +++ b/internal/pkg/locale/message_zh.go @@ -0,0 +1,315 @@ +package locale + +import ( + "github.com/nicksnyder/go-i18n/v2/i18n" +) + +// 在该文件中添加 i18n.Message 后还需生成对应语言文件(active.*.toml),脚本写在Makefile中了,使用步骤如下: +// 1. 安装需要的工具,已安装则跳过: +// make install_i18n_tool +// 2. 将新增的i18n.Message提取到语言文件(active.*.toml)中: +// make extract_i18n +// 3. 生成待翻译的临时文件(translate.en.toml): +// make start_trans_i18n +// 4. 人工介入将 translate.en.toml 文件中的文本翻译替换 +// 5. 根据翻译好的文本更新英文文件(active.en.toml): +// make end_trans_i18n + +// Stat +var ( + StatOK = &i18n.Message{ID: "StatOK", Other: "正常"} + StatDisable = &i18n.Message{ID: "StatDisable", Other: "被禁用"} + StatUnknown = &i18n.Message{ID: "StatUnknown", Other: "未知"} +) + +// OpPermission +var ( + NameOpPermissionCreateProject = &i18n.Message{ID: "NameOpPermissionCreateProject", Other: "项目总监"} + NameOpPermissionProjectAdmin = &i18n.Message{ID: "NameOpPermissionProjectAdmin", Other: "项目管理"} + NameOpPermissionCreateWorkflow = &i18n.Message{ID: "NameOpPermissionCreateWorkflow", Other: "创建上线工单"} + NameOpPermissionAuditWorkflow = &i18n.Message{ID: "NameOpPermissionAuditWorkflow", Other: "审批上线工单"} + NameOpPermissionAuthDBServiceData = &i18n.Message{ID: "NameOpPermissionAuthDBServiceData", Other: "账号管理"} + NameOpPermissionExecuteWorkflow = &i18n.Message{ID: "NameOpPermissionExecuteWorkflow", Other: "执行上线工单"} + NameOpPermissionViewOthersWorkflow = &i18n.Message{ID: "NameOpPermissionViewOthersWorkflow", Other: "查看所有工单"} + NameOpPermissionViewOthersAuditPlan = &i18n.Message{ID: "NameOpPermissionViewOthersAuditPlan", Other: "访问所有管控SQL"} + NameOpPermissionViewSQLInsight = &i18n.Message{ID: "NameOpPermissionViewSQLInsight", Other: "查看性能洞察"} + NameOpPermissionSaveAuditPlan = &i18n.Message{ID: "NameOpPermissionSaveAuditPlan", Other: "配置SQL管控"} + NameOpPermissionSQLQuery = &i18n.Message{ID: "NameOpPermissionSQLQuery", Other: "SQL工作台操作权限"} + NameOpPermissionExportApprovalReject = &i18n.Message{ID: "NameOpPermissionExportApprovalReject", Other: "审批导出工单"} + NameOpPermissionExportCreate = &i18n.Message{ID: "NameOpPermissionExportCreate", Other: "创建导出工单"} + NameOpPermissionCreateOptimization = &i18n.Message{ID: "NameOpPermissionCreateOptimization", Other: "创建智能调优"} + NameOpPermissionGlobalManagement = &i18n.Message{ID: "NameOpPermissionGlobalManagement", Other: "系统管理员"} + NameOpPermissionGlobalView = &i18n.Message{ID: "NameOpPermissionGlobalView", Other: "审计管理员"} + NameOpPermissionViewOthersOptimization = &i18n.Message{ID: "NameOpPermissionViewOthersOptimization", Other: "查看他人创建的智能调优"} + NameOpPermissionCreatePipeline = &i18n.Message{ID: "NameOpPermissionCreatePipeline", Other: "流水线增删改"} + NameOpPermissionOrdinaryUser = &i18n.Message{ID: "NameOpPermissionOrdinaryUser", Other: "普通用户"} + NameOpPermissionViewOperationRecord = &i18n.Message{ID: "NameOpPermissionViewOperationRecord", Other: "查看所有操作记录"} + NameOpPermissionViewExportTask = &i18n.Message{ID: "NameOpPermissionViewExportTask", Other: "查看所有导出任务"} + NamePermissionViewQuickAuditRecord = &i18n.Message{ID: "NamePermissionViewQuickAuditRecord", Other: "查看所有快捷审核记录"} + NameOpPermissionViewIDEAuditRecord = &i18n.Message{ID: "NameOpPermissionViewIDEAuditRecord", Other: "查看所有IDE审核记录"} + NameOpPermissionViewOptimizationRecord = &i18n.Message{ID: "NameOpPermissionViewOptimizationRecord", Other: "查看所有优化记录"} + NameOpPermissionViewVersionManage = &i18n.Message{ID: "NameOpPermissionViewVersionManage", Other: "查看他人创建的版本记录"} + NameOpPermissionVersionManage = &i18n.Message{ID: "NameOpPermissionVersionManage", Other: "配置版本"} + NameOpPermissionViewPipeline = &i18n.Message{ID: "NameOpPermissionViewPipeline", Other: "查看所有流水线"} + NameOpPermissionManageProjectDataSource = &i18n.Message{ID: "NameOpPermissionManageProjectDataSource", Other: "管理项目数据源"} + NameOpPermissionManageAuditRuleTemplate = &i18n.Message{ID: "NameOpPermissionManageAuditRuleTemplate", Other: "管理审核规则模版"} + NameOpPermissionManageApprovalTemplate = &i18n.Message{ID: "NameOpPermissionManageApprovalTemplate", Other: "管理审批流程模版"} + NameOpPermissionManageMember = &i18n.Message{ID: "NameOpPermissionManageMember", Other: "管理成员与权限"} + NameOpPermissionPushRule = &i18n.Message{ID: "NameOpPermissionPushRule", Other: "管理推送规则"} + NameOpPermissionMangeAuditSQLWhiteList = &i18n.Message{ID: "NameOpPermissionMangeAuditSQLWhiteList", Other: "审核SQL例外"} + NameOpPermissionManageSQLMangeWhiteList = &i18n.Message{ID: "NameOpPermissionManageSQLMangeWhiteList", Other: "管控SQL例外"} + NameOpPermissionManageRoleMange = &i18n.Message{ID: "NameOpPermissionManageRoleMange", Other: "角色管理权限"} + NameOpPermissionDesensitization = &i18n.Message{ID: "NameOpPermissionDesensitization", Other: "配置脱敏任务"} + NameOpPermissionMaskingAudit = &i18n.Message{ID: "NameOpPermissionMaskingAudit", Other: "脱敏审核"} + + DescOpPermissionGlobalManagement = &i18n.Message{ID: "DescOpPermissionGlobalManagement", Other: "具备系统最高权限,可进行系统配置、用户管理等操作"} + DescOpPermissionGlobalView = &i18n.Message{ID: "DescOpPermissionGlobalView", Other: "负责系统操作审计、数据合规检查等工作"} + DescOpPermissionCreateProject = &i18n.Message{ID: "DescOpPermissionCreateProject", Other: "创建项目、配置项目资源"} + DescOpPermissionProjectAdmin = &i18n.Message{ID: "DescOpPermissionProjectAdmin", Other: "项目管理;拥有该权限的用户可以管理项目下的所有资源"} + DescOpPermissionCreateWorkflow = &i18n.Message{ID: "DescOpPermissionCreateWorkflow", Other: "创建/编辑工单;拥有该权限的用户可以创建/编辑工单"} + DescOpPermissionOrdinaryUser = &i18n.Message{ID: "DescOpPermissionOrdinaryUser", Other: "基础功能操作权限,可进行日常业务操作"} + DescOpPermissionAuditWorkflow = &i18n.Message{ID: "DescOpPermissionAuditWorkflow", Other: "审核/驳回工单;拥有该权限的用户可以审核/驳回工单"} + DescOpPermissionAuthDBServiceData = &i18n.Message{ID: "DescOpPermissionAuthDBServiceData", Other: "授权数据源数据权限;拥有该权限的用户可以授权数据源数据权限"} + DescOpPermissionExecuteWorkflow = &i18n.Message{ID: "DescOpPermissionExecuteWorkflow", Other: "上线工单;拥有该权限的用户可以上线工单"} + DescOpPermissionViewOthersWorkflow = &i18n.Message{ID: "DescOpPermissionViewOthersWorkflow", Other: "查看他人创建的工单;拥有该权限的用户可以查看他人创建的工单"} + DescOpPermissionViewOthersAuditPlan = &i18n.Message{ID: "DescOpPermissionViewOthersAuditPlan", Other: "查看他人创建的扫描任务;拥有该权限的用户可以查看他人创建的扫描任务"} + DescOpPermissionViewSQLInsight = &i18n.Message{ID: "DescOpPermissionViewSQLInsight", Other: "查看性能洞察;拥有该权限的用户可以查看性能洞察的数据"} + DescOpPermissionSaveAuditPlan = &i18n.Message{ID: "DescOpPermissionSaveAuditPlan", Other: "创建/编辑扫描任务;拥有该权限的用户可以创建/编辑扫描任务"} + DescOpPermissionSQLQuery = &i18n.Message{ID: "DescOpPermissionSQLQuery", Other: "SQL工作台查询;拥有该权限的用户可以执行SQL工作台查询"} + DescOpPermissionExportApprovalReject = &i18n.Message{ID: "DescOpPermissionExportApprovalReject", Other: "审批/驳回数据导出工单;拥有该权限的用户可以执行审批导出数据工单或者驳回导出数据工单"} + DescOpPermissionExportCreate = &i18n.Message{ID: "DescOpPermissionExportCreate", Other: "创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单"} + DescOpPermissionCreateOptimization = &i18n.Message{ID: "DescOpPermissionCreateOptimization", Other: "创建智能调优;拥有该权限的用户可以创建智能调优"} + DescOpPermissionViewOthersOptimization = &i18n.Message{ID: "DescOpPermissionViewOthersOptimization", Other: "查看他人创建的智能调优;拥有该权限的用户可以查看他人创建的智能调优"} + DescOpPermissionCreatePipeline = &i18n.Message{ID: "DescOpPermissionCreatePipeline", Other: "配置流水线;拥有该权限的用户可以为数据源配置流水线"} + DescOpPermissionViewOperationRecord = &i18n.Message{ID: "DescOpPermissionViewOperationRecord", Other: "查看所有操作记录;拥有该权限的用户可以查看平台全部操作记录"} + DescOpPermissionViewExportTask = &i18n.Message{ID: "DescOpPermissionViewExportTask", Other: "查看所有导出任务;拥有该权限的用户可以查看平台全部导出任务"} + DescPermissionViewQuickAuditRecord = &i18n.Message{ID: "DescPermissionViewQuickAuditRecord", Other: "查看所有快捷审核记录;拥有该权限的用户可以查看全部快捷审核记录"} + DescOpPermissionViewIDEAuditRecord = &i18n.Message{ID: "DescOpPermissionViewIDEAuditRecord", Other: "查看所有IDE审核记录;拥有该权限的用户可以查看全部IDE审核记录"} + DescOpPermissionViewOptimizationRecord = &i18n.Message{ID: "DescOpPermissionViewOptimizationRecord", Other: "查看所有优化记录;拥有该权限的用户可以查看全部优化记录"} + DescOpPermissionViewVersionManage = &i18n.Message{ID: "DescOpPermissionViewVersionManage", Other: "查看他人创建的版本记录;拥有该权限的用户可以查看全部版本记录"} + DescOpPermissionVersionManage = &i18n.Message{ID: "DescOpPermissionVersionManage", Other: "配置版本;拥有该权限的用户可以配置版本管理策略"} + DescOpPermissionViewPipeline = &i18n.Message{ID: "DescOpPermissionViewPipeline", Other: "查看所有流水线;拥有该权限的用户可以查看全部流水线"} + DescOpPermissionManageProjectDataSource = &i18n.Message{ID: "DescOpPermissionManageProjectDataSource", Other: "管理项目数据源;拥有该权限的用户可以管理项目下数据源"} + DescOpPermissionManageAuditRuleTemplate = &i18n.Message{ID: "DescOpPermissionManageAuditRuleTemplate", Other: "管理审核规则模版;拥有该权限的用户可以管理审核规则模版"} + DescOpPermissionManageApprovalTemplate = &i18n.Message{ID: "DescOpPermissionManageApprovalTemplate", Other: "管理审批流程模版;拥有该权限的用户可以管理审批流程模版"} + DescOpPermissionManageMember = &i18n.Message{ID: "DescOpPermissionManageMember", Other: "管理成员与权限;拥有该权限的用户可以管理项目成员与权限"} + DescOpPermissionPushRule = &i18n.Message{ID: "DescOpPermissionPushRule", Other: "管理推送规则;拥有该权限的用户可以管理推送规则"} + DescOpPermissionMangeAuditSQLWhiteList = &i18n.Message{ID: "DescOpPermissionMangeAuditSQLWhiteList", Other: "审核SQL例外;拥有该权限的用户可以管理审核SQL例外"} + DescOpPermissionManageSQLMangeWhiteList = &i18n.Message{ID: "DescOpPermissionManageSQLMangeWhiteList", Other: "管控SQL例外;拥有该权限的用户可以管理管控SQL例外"} + DescOpPermissionManageRoleMange = &i18n.Message{ID: "DescOpPermissionManageRoleMange", Other: "角色管理权限;拥有该权限的用户可以管理角色"} + DescOpPermissionDesensitization = &i18n.Message{ID: "DescOpPermissionDesensitization", Other: "配置脱敏任务;拥有该权限的用户可以管理脱敏模板、脱敏发现任务和规则配置"} + DescOpPermissionMaskingAudit = &i18n.Message{ID: "DescOpPermissionMaskingAudit", Other: "脱敏审核;拥有该权限的用户可以查看和处理脱敏审批请求"} +) + +// role +var ( + NameRoleProjectAdmin = &i18n.Message{ID: "NameRoleProjectAdmin", Other: "项目管理员"} + NameRoleDevEngineer = &i18n.Message{ID: "NameRoleDevEngineer", Other: "开发工程师"} + NameRoleDevManager = &i18n.Message{ID: "NameRoleDevManager", Other: "开发主管"} + NameRoleOpsEngineer = &i18n.Message{ID: "NameRoleOpsEngineer", Other: "运维工程师"} + + DescRoleProjectAdmin = &i18n.Message{ID: "DescRoleProjectAdmin", Other: "project admin"} + DescRoleDevEngineer = &i18n.Message{ID: "DescRoleDevEngineer", Other: "拥有该权限的用户可以创建/编辑工单,SQL工作台查询,配置流水线,创建智能调优"} + DescRoleDevManager = &i18n.Message{ID: "DescRoleDevManager", Other: "拥有该权限的用户可以创建/编辑工单,审核/驳回工单,配置流水线,查看他人创建的智能调优"} + DescRoleOpsEngineer = &i18n.Message{ID: "DescRoleOpsEngineer", Other: "拥有该权限的用户可以上线工单,查看他人创建的工单,创建智能扫描,查看他人的扫描任务,数据导出"} +) + +// license +var ( + LicenseInstanceNum = &i18n.Message{ID: "LicenseInstanceNum", Other: "实例数"} + LicenseUserNum = &i18n.Message{ID: "LicenseUserNum", Other: "用户数"} + LicenseAuthorizedDurationDay = &i18n.Message{ID: "LicenseAuthorizedDurationDay", Other: "授权运行时长(天)"} + LicenseUnlimited = &i18n.Message{ID: "LicenseUnlimited", Other: "无限制"} + LicenseDurationOfRunning = &i18n.Message{ID: "LicenseDurationOfRunning", Other: "已运行时长(天)"} + LicenseEstimatedMaturity = &i18n.Message{ID: "LicenseEstimatedMaturity", Other: "预计到期时间"} + LicenseResourceTypeUser = &i18n.Message{ID: "LicenseResourceTypeUser", Other: "用户"} + LicenseInstanceNumOfType = &i18n.Message{ID: "LicenseInstanceNumOfType", Other: "[%v]类型实例数"} + LicenseMachineInfo = &i18n.Message{ID: "LicenseMachineInfo", Other: "机器信息"} + LicenseMachineInfoOfNode = &i18n.Message{ID: "LicenseMachineInfoOfNode", Other: "节点[%s]机器信息"} + LicenseDmsVersion = &i18n.Message{ID: "LicenseDmsVersion", Other: "DMS版本"} +) + +// DB service +var ( + DBServiceDbName = &i18n.Message{ID: "DBServiceDbName", Other: "数据源名称"} + DBServiceProjName = &i18n.Message{ID: "DBServiceProjName", Other: "所属项目(平台已有的项目名称)"} + DBServiceEnvironmentTag = &i18n.Message{ID: "DBServiceEnvironmentTag", Other: "所属环境"} + DBServiceDesc = &i18n.Message{ID: "DBServiceDesc", Other: "数据源描述"} + DBServiceDbType = &i18n.Message{ID: "DBServiceDbType", Other: "数据源类型"} + DBServiceHost = &i18n.Message{ID: "DBServiceHost", Other: "数据源地址"} + DBServicePort = &i18n.Message{ID: "DBServicePort", Other: "数据源端口"} + DBServiceUser = &i18n.Message{ID: "DBServiceUser", Other: "数据源连接用户"} + DBServicePassword = &i18n.Message{ID: "DBServicePassword", Other: "数据源密码"} + DBServiceOracleService = &i18n.Message{ID: "DBServiceOracleService", Other: "服务名(Oracle需填)"} + DBServiceDB2DbName = &i18n.Message{ID: "DBServiceDB2DbName", Other: "数据库名(DB2需填)"} + DBServiceOpsTime = &i18n.Message{ID: "DBServiceOpsTime", Other: "运维时间(非必填,9:30-11:00;14:10-18:30)"} + DBServiceRuleTemplateName = &i18n.Message{ID: "DBServiceRuleTemplateName", Other: "审核规则模板(项目已有的规则模板)"} + DBServiceSQLQueryRuleTemplateName = &i18n.Message{ID: "DBServiceSQLQueryRuleTemplateName", Other: "工作台操作审核规则模板(需要先填写审核规则模板)"} + DBServiceDataExportRuleTemplateName = &i18n.Message{ID: "DBServiceDataExportRuleTemplateName", Other: "数据导出审核规则模板(需要先填写审核规则模板)"} + DBServiceAuditLevel = &i18n.Message{ID: "DBServiceAuditLevel", Other: "工作台查询的最高审核等级[error|warn|notice|normal]"} + DBServiceProblem = &i18n.Message{ID: "DBServiceProblem", Other: "问题"} + + DBServiceNoProblem = &i18n.Message{ID: "DBServiceNoProblem", Other: "无"} + IDBPCErrMissingOrInvalidCols = &i18n.Message{ID: "IDBPCErrMissingOrInvalidCols", Other: "缺失或不规范的列:%s"} + IDBPCErrInvalidInput = &i18n.Message{ID: "IDBPCErrInvalidInput", Other: "若无特别说明每列均为必填"} + IDBPCErrProjNonExist = &i18n.Message{ID: "IDBPCErrProjNonExist", Other: "所属项目不存在"} + IDBPCErrProjNotActive = &i18n.Message{ID: "IDBPCErrProjNotActive", Other: "所属项目状态异常"} + IDBPCErrProjNotAllowed = &i18n.Message{ID: "IDBPCErrProjNotAllowed", Other: "所属项目不是操作中的项目"} + IDBPCErrOptTimeInvalid = &i18n.Message{ID: "IDBPCErrOptTimeInvalid", Other: "运维时间不规范"} + IDBPCErrDbTypeInvalid = &i18n.Message{ID: "IDBPCErrDbTypeInvalid", Other: "数据源类型不规范或对应插件未安装"} + IDBPCErrOracleServiceNameInvalid = &i18n.Message{ID: "IDBPCErrOracleServiceNameInvalid", Other: "Oracle服务名错误"} + IDBPCErrDB2DbNameInvalid = &i18n.Message{ID: "IDBPCErrDB2DbNameInvalid", Other: "DB2数据库名错误"} + IDBPCErrRuleTemplateInvalid = &i18n.Message{ID: "IDBPCErrRuleTemplateInvalid", Other: "审核规则模板不存在或数据源类型不匹配"} + IDBPCErrSQLQueryRuleTemplateInvalid = &i18n.Message{ID: "IDBPCErrSQLQueryRuleTemplateInvalid", Other: "工作台操作审核规则模板不存在或数据源类型不匹配"} + IDBPCErrDataExportRuleTemplateInvalid = &i18n.Message{ID: "IDBPCErrDataExportRuleTemplateInvalid", Other: "数据导出审核规则模板不存在或数据源类型不匹配"} + IDBPCErrRuleTemplateBaseCheck = &i18n.Message{ID: "IDBPCErrRuleTemplateBaseCheck", Other: "需要先添加审核规则模板,工作台和数据导出审核模板才会生效"} + IDBPCErrEnvironmentTagInvalid = &i18n.Message{ID: "IDBPCErrEnvironmentTagInvalid", Other: "项目环境标签检查错误或不存在"} +) + +// project +var ( + ProjectName = &i18n.Message{ID: "ProjectName", Other: "项目名称"} + ProjectDesc = &i18n.Message{ID: "ProjectDesc", Other: "项目描述"} + ProjectStatus = &i18n.Message{ID: "ProjectStatus", Other: "项目状态"} + ProjectBusiness = &i18n.Message{ID: "ProjectBusiness", Other: "所属业务"} + ProjectCreateTime = &i18n.Message{ID: "ProjectCreateTime", Other: "创建时间"} + ProjectAvailable = &i18n.Message{ID: "ProjectAvailable", Other: "可用"} + ProjectNotAvailable = &i18n.Message{ID: "ProjectNotAvailable", Other: "不可用"} +) + +// cb +var ( + CbOpDetailDelData = &i18n.Message{ID: "CbOpDetailDelData", Other: "在数据源:%s中删除了以下数据:%s"} + CbOpDetailAddData = &i18n.Message{ID: "CbOpDetailAddData", Other: "在数据源:%s中添加了以下数据:%s"} + CbOpDetailUpdateData = &i18n.Message{ID: "CbOpDetailUpdateData", Other: "在数据源:%s中更新了以下数据:%s"} + + CbOpTotalExecutions = &i18n.Message{ID: "CbOpTotalExecutions", Other: "执行总量:"} + CbOpSuccessRate = &i18n.Message{ID: "CbOpSuccessRate", Other: "执行成功率:"} + CbOpAuditBlockedSQL = &i18n.Message{ID: "CbOpAuditBlockedSQL", Other: "审核拦截的异常SQL:"} + CbOpUnsuccessfulExecutions = &i18n.Message{ID: "CbOpUnsuccessfulExecutions", Other: "执行不成功的SQL:"} + + CbOpProjectName = &i18n.Message{ID: "CbOpProjectName", Other: "项目名"} + CbOpOperator = &i18n.Message{ID: "CbOpOperator", Other: "操作人"} + CbOpOperationTime = &i18n.Message{ID: "CbOpOperationTime", Other: "操作时间"} + CbOpDataSource = &i18n.Message{ID: "CbOpDataSource", Other: "数据源"} + CbOpDetails = &i18n.Message{ID: "CbOpDetails", Other: "操作详情"} + CbOpSessionID = &i18n.Message{ID: "CbOpSessionID", Other: "会话ID"} + CbOpOperationIP = &i18n.Message{ID: "CbOpOperationIP", Other: "操作IP"} + CbOpAuditResult = &i18n.Message{ID: "CbOpAuditResult", Other: "审核结果"} + CbOpExecutionResult = &i18n.Message{ID: "CbOpExecutionResult", Other: "执行结果"} + CbOpExecutionTimeMs = &i18n.Message{ID: "CbOpExecutionTimeMs", Other: "执行时间(毫秒)"} + CbOpResultRowCount = &i18n.Message{ID: "CbOpResultRowCount", Other: "结果集返回行数"} +) + +// SQL Workbench +var ( + SqlWorkbenchAuditReadReqBodyErr = &i18n.Message{ID: "SqlWorkbenchAuditReadReqBodyErr", Other: "请求内容获取失败,可能网络不稳定,请稍后重试。"} + SqlWorkbenchAuditParseReqErr = &i18n.Message{ID: "SqlWorkbenchAuditParseReqErr", Other: "请求内容解析失败,请稍后重试。"} + SqlWorkbenchAuditMissingSQLOrDatasourceErr = &i18n.Message{ID: "SqlWorkbenchAuditMissingSQLOrDatasourceErr", Other: "未检测到 SQL 或数据源,请确认已选择数据源并输入 SQL 后重试。"} + SqlWorkbenchAuditGetDMSUserErr = &i18n.Message{ID: "SqlWorkbenchAuditGetDMSUserErr", Other: "当前登录状态可能已过期,请重新登录后再试。"} + SqlWorkbenchAuditGetDBServiceMappingErr = &i18n.Message{ID: "SqlWorkbenchAuditGetDBServiceMappingErr", Other: "当前数据源信息获取失败,请重新选择数据源后重试。"} + SqlWorkbenchAuditDBServiceMappingNotFoundErr = &i18n.Message{ID: "SqlWorkbenchAuditDBServiceMappingNotFoundErr", Other: "未找到当前数据源,请确认数据源存在并重新选择后重试。"} + SqlWorkbenchAuditGetDBServiceErr = &i18n.Message{ID: "SqlWorkbenchAuditGetDBServiceErr", Other: "未找到当前数据源配置,请确认数据源存在后重试。"} + SqlWorkbenchAuditNotEnabledErr = &i18n.Message{ID: "SqlWorkbenchAuditNotEnabledErr", Other: "该数据源尚未开启 SQL 审核,请先在数据源配置中开启“SQL 审核”后再执行。"} + SqlWorkbenchAuditCallSQLEErr = &i18n.Message{ID: "SqlWorkbenchAuditCallSQLEErr", Other: "审核服务当前繁忙或不可用,请稍后重试。"} +) + +// SQL Workbench Maintenance Time +var ( + SqlWorkbenchMaintenanceTimeBlocked = &i18n.Message{ID: "SqlWorkbenchMaintenanceTimeBlocked", Other: "当前处于非运维时间(运维时间:%s),禁止执行非查询类操作。请在运维时间内操作或提交上线工单。"} +) + +// DB Service Sync Task +var ( + DBServiceSyncVersion = &i18n.Message{ID: "DBServiceSyncVersion", Other: "版本(支持DMP5.23.04.0及以上版本)"} + DBServiceSyncExpand = &i18n.Message{ID: "DBServiceSyncExpand", Other: "数据源同步扩展服务"} +) + +// OAuth2 +var ( + OAuth2GetConfigErr = &i18n.Message{ID: "OAuth2GetConfigErr", Other: "获取OAuth2配置失败: %v"} + OAuth2ProcessErr = &i18n.Message{ID: "OAuth2ProcessErr", Other: "OAuth2流程错误: %v"} + OAuth2GetTokenErr = &i18n.Message{ID: "OAuth2GetTokenErr", Other: "OAuth2流程获取Token错误: %v"} + OAuth2BackendLogoutFailed = &i18n.Message{ID: "OAuth2BackendLogoutFailed", Other: ";注销第三方平台会话失败: %v"} + OAuth2BackendLogoutSuccess = &i18n.Message{ID: "OAuth2BackendLogoutSuccess", Other: ";已注销第三方平台会话"} + OAuth2HandleTokenErr = &i18n.Message{ID: "OAuth2HandleTokenErr", Other: "处理 OAuth2 Token 错误: %v"} + OAuth2GetUserInfoErr = &i18n.Message{ID: "OAuth2GetUserInfoErr", Other: "获取 OAuth2 用户信息错误: %v"} + OAuth2QueryBindUserByOAuthIDErr = &i18n.Message{ID: "OAuth2QueryBindUserByOAuthIDErr", Other: "通过 OAuth2 用户ID查询绑定用户错误: %v"} + OAuth2QueryBindUserBySameNameErr = &i18n.Message{ID: "OAuth2QueryBindUserBySameNameErr", Other: "通过 OAuth2 用户ID查询同名用户错误: %v"} + OAuth2SameNameUserIsBoundErr = &i18n.Message{ID: "OAuth2SameNameUserIsBoundErr", Other: "通过 OAuth2 用户ID %q 查询到的同名用户已经被绑定"} + OAuth2UserNotBoundAndNoPermErr = &i18n.Message{ID: "OAuth2UserNotBoundAndNoPermErr", Other: "该OAuth2用户未绑定且没有登陆权限"} + OAuth2AutoCreateUserWithoutDefaultPwdErr = &i18n.Message{ID: "OAuth2AutoCreateUserWithoutDefaultPwdErr", Other: "自动创建用户失败,默认密码未配置"} + OAuth2AutoCreateUserErr = &i18n.Message{ID: "OAuth2AutoCreateUserErr", Other: "自动创建用户失败: %v"} + OAuth2UserNotBoundAndDisableManuallyBindErr = &i18n.Message{ID: "OAuth2UserNotBoundAndDisableManuallyBindErr", Other: "未查询到 %q 关联的用户且关闭了手动绑定功能,请联系系统管理员"} + OAuth2UserStatIsDisableErr = &i18n.Message{ID: "OAuth2UserStatIsDisableErr", Other: "用户 %q 被禁用"} + OAuth2SyncSessionErr = &i18n.Message{ID: "OAuth2SyncSessionErr", Other: "同步OAuth2会话失败: %v"} +) + +// Data Export Workflow +var ( + DataExportWorkflowNameDuplicateErr = &i18n.Message{ID: "DataExportWorkflowNameDuplicateErr", Other: "工单名称重复了,请您修改工单名称后重新提交工单。"} + DataWorkflowDefault = &i18n.Message{ID: "DataWorkflowDefault", Other: "❓数据导出工单未知请求"} + DataWorkflowExportFailed = &i18n.Message{ID: "DataWorkflowExportFailed", Other: "⚠️ 数据导出失败"} + DataWorkflowExportSuccess = &i18n.Message{ID: "DataWorkflowExportSuccess", Other: "✅ 数据导出成功"} + DataWorkflowReject = &i18n.Message{ID: "DataWorkflowReject", Other: "❌ 数据导出工单被驳回"} + DataWorkflowWaitExporting = &i18n.Message{ID: "DataWorkflowWaitExporting", Other: "⏳ 数据导出工单待导出"} + DataWorkflowWaiting = &i18n.Message{ID: "DataWorkflowWaiting", Other: "🔍 数据导出工单待审批"} + NotifyDataWorkflowBodyConfigUrl = &i18n.Message{ID: "NotifyDataWorkflowBodyConfigUrl", Other: "请在系统设置-全局配置中补充全局url"} + NotifyDataWorkflowBodyHead = &i18n.Message{ID: "NotifyDataWorkflowBodyHead", Other: "\n📋 数据导出工单主题: %v\n📍 所属项目: %v\n🆔 数据导出工单ID: %v\n📝 数据导出工单描述: %v\n👤 申请人: %v\n⏰ 创建时间: %v\n"} + NotifyDataWorkflowBodyInstanceAndSchema = &i18n.Message{ID: "NotifyDataWorkflowBodyInstanceAndSchema", Other: "🗄️ 数据源: %v\n📊 schema: %v\n"} + NotifyDataWorkflowBodyLink = &i18n.Message{ID: "NotifyDataWorkflowBodyLink", Other: "🔗 数据导出工单链接: %v"} + NotifyDataWorkflowBodyReason = &i18n.Message{ID: "NotifyDataWorkflowBodyReason", Other: "❌ 驳回原因: %v"} + NotifyDataWorkflowBodyReport = &i18n.Message{ID: "NotifyDataWorkflowBodyReport", Other: "⭐ 数据导出工单审核得分: %v"} + NotifyDataWorkflowBodyStartEnd = &i18n.Message{ID: "NotifyDataWorkflowBodyStartEnd", Other: "▶️ 数据导出开始时间: %v\n◀️ 数据导出结束时间: %v"} + NotifyDataWorkflowBodyWorkFlowErr = &i18n.Message{ID: "NotifyDataWorkflowBodyWorkFlowErr", Other: "❌ 读取工单任务内容失败,请通过SQLE界面确认工单状态"} + NotifyDataWorkflowBodyApprovalReminder = &i18n.Message{ID: "NotifyDataWorkflowBodyApprovalReminder", Other: "⏰ 导出工单已审批通过,请在1天内完成导出,过期后将无法执行"} +) + +// Operation Record +var ( + OpRecordUserCreate = &i18n.Message{ID: "OpRecordUserCreate", Other: "创建用户"} + OpRecordUserCreateWithName = &i18n.Message{ID: "OpRecordUserCreateWithName", Other: "创建用户 %s"} + OpRecordCurrentUserUpdate = &i18n.Message{ID: "OpRecordCurrentUserUpdate", Other: "更新个人中心账号基本信息"} + OpRecordUserUpdate = &i18n.Message{ID: "OpRecordUserUpdate", Other: "更新用户 %s"} + OpRecordUserDelete = &i18n.Message{ID: "OpRecordUserDelete", Other: "删除用户 %s"} + OpRecordMemberCreate = &i18n.Message{ID: "OpRecordMemberCreate", Other: "添加成员"} + OpRecordMemberCreateWithName = &i18n.Message{ID: "OpRecordMemberCreateWithName", Other: "添加成员 %s"} + OpRecordMemberUpdate = &i18n.Message{ID: "OpRecordMemberUpdate", Other: "更新成员 %s"} + OpRecordMemberDelete = &i18n.Message{ID: "OpRecordMemberDelete", Other: "删除成员 %s"} + OpRecordMemberGroupCreate = &i18n.Message{ID: "OpRecordMemberGroupCreate", Other: "添加成员组"} + OpRecordMemberGroupCreateWithName = &i18n.Message{ID: "OpRecordMemberGroupCreateWithName", Other: "添加成员组 %s"} + OpRecordMemberGroupUpdate = &i18n.Message{ID: "OpRecordMemberGroupUpdate", Other: "更新成员组 %s"} + OpRecordMemberGroupDelete = &i18n.Message{ID: "OpRecordMemberGroupDelete", Other: "删除成员组 %s"} + OpRecordRoleCreate = &i18n.Message{ID: "OpRecordRoleCreate", Other: "创建角色"} + OpRecordRoleCreateWithName = &i18n.Message{ID: "OpRecordRoleCreateWithName", Other: "创建角色 %s"} + OpRecordRoleUpdate = &i18n.Message{ID: "OpRecordRoleUpdate", Other: "更新角色 %s"} + OpRecordRoleDelete = &i18n.Message{ID: "OpRecordRoleDelete", Other: "删除角色 %s"} + OpRecordProjectCreate = &i18n.Message{ID: "OpRecordProjectCreate", Other: "创建项目"} + OpRecordProjectCreateWithName = &i18n.Message{ID: "OpRecordProjectCreateWithName", Other: "创建项目 %s"} + OpRecordProjectUpdate = &i18n.Message{ID: "OpRecordProjectUpdate", Other: "更新项目 %s"} + OpRecordProjectDelete = &i18n.Message{ID: "OpRecordProjectDelete", Other: "删除项目 %s"} + OpRecordProjectArchive = &i18n.Message{ID: "OpRecordProjectArchive", Other: "归档项目 %s"} + OpRecordProjectUnarchive = &i18n.Message{ID: "OpRecordProjectUnarchive", Other: "取消归档项目 %s"} + OpRecordDBServiceCreate = &i18n.Message{ID: "OpRecordDBServiceCreate", Other: "创建数据源"} + OpRecordDBServiceCreateWithName = &i18n.Message{ID: "OpRecordDBServiceCreateWithName", Other: "创建数据源 %s"} + OpRecordDBServiceUpdate = &i18n.Message{ID: "OpRecordDBServiceUpdate", Other: "更新数据源 %s"} + OpRecordDBServiceDelete = &i18n.Message{ID: "OpRecordDBServiceDelete", Other: "删除数据源 %s"} + OpRecordDBServiceImport = &i18n.Message{ID: "OpRecordDBServiceImport", Other: "导入数据源"} + OpRecordConfigLogin = &i18n.Message{ID: "OpRecordConfigLogin", Other: "更新登录配置"} + OpRecordConfigOAuth2 = &i18n.Message{ID: "OpRecordConfigOAuth2", Other: "更新OAuth2配置"} + OpRecordConfigLDAP = &i18n.Message{ID: "OpRecordConfigLDAP", Other: "更新LDAP配置"} + OpRecordConfigSMTP = &i18n.Message{ID: "OpRecordConfigSMTP", Other: "更新SMTP配置"} + OpRecordConfigWechat = &i18n.Message{ID: "OpRecordConfigWechat", Other: "更新企业微信配置"} + OpRecordConfigFeishu = &i18n.Message{ID: "OpRecordConfigFeishu", Other: "更新飞书配置"} + OpRecordConfigWebhook = &i18n.Message{ID: "OpRecordConfigWebhook", Other: "更新Webhook配置"} + OpRecordConfigSms = &i18n.Message{ID: "OpRecordConfigSms", Other: "更新短信配置"} + OpRecordConfigSystemVariables = &i18n.Message{ID: "OpRecordConfigSystemVariables", Other: "更新系统变量配置"} + OpRecordConfigCompanyNotice = &i18n.Message{ID: "OpRecordConfigCompanyNotice", Other: "更新系统公告"} + OpRecordDataExportCreate = &i18n.Message{ID: "OpRecordDataExportCreate", Other: "创建数据导出工单"} + OpRecordDataExportCreateWithName = &i18n.Message{ID: "OpRecordDataExportCreateWithName", Other: "创建数据导出工单 %s"} + OpRecordDataExportApproveWithName = &i18n.Message{ID: "OpRecordDataExportApproveWithName", Other: "审批通过数据导出工单 %s"} + OpRecordDataExportRejectWithName = &i18n.Message{ID: "OpRecordDataExportRejectWithName", Other: "驳回数据导出工单 %s"} + OpRecordDataExportExportWithName = &i18n.Message{ID: "OpRecordDataExportExportWithName", Other: "执行数据导出 %s"} + OpRecordDataExportCancel = &i18n.Message{ID: "OpRecordDataExportCancel", Other: "取消数据导出工单"} + OpRecordDataExportCancelWithName = &i18n.Message{ID: "OpRecordDataExportCancelWithName", Other: "取消数据导出工单 %s"} +) diff --git a/internal/pkg/utils/gzip.go b/internal/pkg/utils/gzip.go new file mode 100644 index 000000000..0dd366676 --- /dev/null +++ b/internal/pkg/utils/gzip.go @@ -0,0 +1,28 @@ +package utils + +import ( + "bytes" + "compress/gzip" + "fmt" + "io" +) + +// IsGzip 检查数据是否是 Gzip 压缩格式 +func IsGzip(data []byte) bool { + return len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b +} + +// DecodeGzipBytes 解码 Gzip 压缩的数据,返回解码后的字节数组 +func DecodeGzipBytes(data []byte) ([]byte, error) { + reader, err := gzip.NewReader(bytes.NewReader(data)) + if err != nil { + return nil, fmt.Errorf("failed to create gzip reader: %v", err) + } + defer reader.Close() + + decoded, err := io.ReadAll(reader) + if err != nil { + return nil, fmt.Errorf("failed to read gzip data: %v", err) + } + return decoded, nil +} diff --git a/internal/sql_workbench/client/sql_workbench_client.go b/internal/sql_workbench/client/sql_workbench_client.go new file mode 100644 index 000000000..c4004af31 --- /dev/null +++ b/internal/sql_workbench/client/sql_workbench_client.go @@ -0,0 +1,1133 @@ +package client + +import ( + "bytes" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "mime/multipart" + "net/http" + "regexp" + "strings" + "time" + + config "github.com/actiontech/dms/internal/sql_workbench/config" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" +) + +// SqlWorkbenchClient SQL工作台HTTP客户端 +type SqlWorkbenchClient struct { + cfg *config.SqlWorkbenchOpts + log *utilLog.Helper + httpClient *http.Client + baseURL string +} + +// NewSqlWorkbenchClient 创建SQL工作台客户端 +func NewSqlWorkbenchClient(cfg *config.SqlWorkbenchOpts, logger utilLog.Logger) *SqlWorkbenchClient { + baseURL := fmt.Sprintf("http://%s:%s", cfg.Host, cfg.Port) + + return &SqlWorkbenchClient{ + cfg: cfg, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("sql_workbench.client")), + httpClient: &http.Client{ + Timeout: 30 * time.Second, + }, + baseURL: baseURL, + } +} + +// GetPublicKey 获取RSA公钥 +func (c *SqlWorkbenchClient) GetPublicKey() (string, error) { + c.log.Infof("Attempting to get public key") + + // 构建获取公钥URL + publicKeyURL := fmt.Sprintf("%s/api/v2/encryption/publicKey", c.baseURL) + + // 创建GET请求 + req, err := http.NewRequest("GET", publicKeyURL, nil) + if err != nil { + c.log.Errorf("Failed to create get public key request: %v", err) + return "", fmt.Errorf("failed to create get public key request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send get public key request: %v", err) + return "", fmt.Errorf("failed to send get public key request: %v", err) + } + defer resp.Body.Close() + + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read get public key response: %v", err) + return "", fmt.Errorf("failed to read get public key response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Get public key failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return "", fmt.Errorf("get public key failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var publicKeyResp GetPublicKeyResponse + if err := json.Unmarshal(body, &publicKeyResp); err != nil { + c.log.Errorf("Failed to parse get public key response: %v", err) + return "", fmt.Errorf("failed to parse get public key response: %v", err) + } + + // 检查业务状态 + if !publicKeyResp.Successful { + errorMsg := "get public key failed" + if publicKeyResp.Message != nil { + errorMsg = *publicKeyResp.Message + } + c.log.Errorf("Get public key failed: %s", errorMsg) + return "", fmt.Errorf("get public key failed: %s", errorMsg) + } + + c.log.Infof("Successfully retrieved public key") + return publicKeyResp.Data, nil +} + +// Login 登录到SQL工作台 +func (c *SqlWorkbenchClient) Login(username, password, publicKey string) (*LoginResponse, error) { + c.log.Infof("Attempting to login to SQL workbench for user: %s", username) + + // 加密密码 + encryptedPassword, err := c.EncryptPasswordWithRSA(password, publicKey) + if err != nil { + c.log.Errorf("Failed to encrypt password: %v", err) + return nil, fmt.Errorf("failed to encrypt password: %v", err) + } + + // 构建登录URL + loginURL := fmt.Sprintf("%s/api/v2/iam/login?currentOrganizationId=&ignoreError=true", c.baseURL) + + // 准备multipart表单数据 + var buf bytes.Buffer + writer := multipart.NewWriter(&buf) + + // 添加表单字段,使用CreateFormField确保UTF-8编码正确 + usernameField, err := writer.CreateFormField("username") + if err != nil { + c.log.Errorf("Failed to create username field: %v", err) + return nil, fmt.Errorf("failed to create username field: %v", err) + } + if _, err := usernameField.Write([]byte(username)); err != nil { + c.log.Errorf("Failed to write username field: %v", err) + return nil, fmt.Errorf("failed to write username field: %v", err) + } + + passwordField, err := writer.CreateFormField("password") + if err != nil { + c.log.Errorf("Failed to create password field: %v", err) + return nil, fmt.Errorf("failed to create password field: %v", err) + } + if _, err := passwordField.Write([]byte(encryptedPassword)); err != nil { + c.log.Errorf("Failed to write password field: %v", err) + return nil, fmt.Errorf("failed to write password field: %v", err) + } + + if err := writer.Close(); err != nil { + c.log.Errorf("Failed to close multipart writer: %v", err) + return nil, fmt.Errorf("failed to close multipart writer: %v", err) + } + + // 创建请求 + req, err := http.NewRequest("POST", loginURL, &buf) + if err != nil { + c.log.Errorf("Failed to create login request: %v", err) + return nil, fmt.Errorf("failed to create login request: %v", err) + } + + // 设置请求头,显式指定 charset=utf-8 确保中文字符正确编码 + contentType := writer.FormDataContentType() + "; charset=utf-8" + req.Header.Set("Content-Type", contentType) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send login request: %v", err) + return nil, fmt.Errorf("failed to send login request: %v", err) + } + defer resp.Body.Close() + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read login response: %v", err) + return nil, fmt.Errorf("failed to read login response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Login failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("login failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var loginResp LoginResponse + if err := json.Unmarshal(body, &loginResp); err != nil { + c.log.Errorf("Failed to parse login response: %v", err) + return nil, fmt.Errorf("failed to parse login response: %v", err) + } + + // 检查业务状态 + if !loginResp.Successful { + errorMsg := "login failed" + if loginResp.Message != nil { + errorMsg = *loginResp.Message + } + c.log.Errorf("Login failed: %s", errorMsg) + return nil, fmt.Errorf("login failed: %s", errorMsg) + } + + loginResp.Cookie = resp.Header.Get("Set-Cookie") + + c.log.Infof("Successfully logged in to SQL workbench for user: %s", username) + return &loginResp, nil +} + +// GetOrganizations 获取组织信息 +func (c *SqlWorkbenchClient) GetOrganizations(cookie string) (*GetOrganizationsResponse, error) { + c.log.Infof("Attempting to get organizations") + + // 构建获取组织URL + organizationsURL := fmt.Sprintf("%s/api/v2/iam/users/me/organizations?currentOrganizationId=", c.baseURL) + + // 创建GET请求 + req, err := http.NewRequest("GET", organizationsURL, nil) + if err != nil { + c.log.Errorf("Failed to create get organizations request: %v", err) + return nil, fmt.Errorf("failed to create get organizations request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Cookie", cookie) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send get organizations request: %v", err) + return nil, fmt.Errorf("failed to send get organizations request: %v", err) + } + defer resp.Body.Close() + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read get organizations response: %v", err) + return nil, fmt.Errorf("failed to read get organizations response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Get organizations failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("get organizations failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var organizationsResp GetOrganizationsResponse + if err := json.Unmarshal(body, &organizationsResp); err != nil { + c.log.Errorf("Failed to parse get organizations response: %v", err) + return nil, fmt.Errorf("failed to parse get organizations response: %v", err) + } + organizationsResp.XsrfToken = resp.Header.Get("Set-Cookie") + // 检查业务状态 + if !organizationsResp.Successful { + errorMsg := "get organizations failed" + if organizationsResp.Message != nil { + errorMsg = *organizationsResp.Message + } + c.log.Errorf("Get organizations failed: %s", errorMsg) + return nil, fmt.Errorf("get organizations failed: %s", errorMsg) + } + + c.log.Infof("Successfully retrieved %d organizations", len(organizationsResp.Data.Contents)) + return &organizationsResp, nil +} + +// Environment 环境信息 +type Environment struct { + BuiltIn bool `json:"builtIn"` + CreateTime int64 `json:"createTime"` + Creator *User `json:"creator"` + Description string `json:"description"` + Enabled bool `json:"enabled"` + ID int64 `json:"id"` + LastModifier *User `json:"lastModifier"` + Name string `json:"name"` + OrganizationID int64 `json:"organizationId"` + OriginalName string `json:"originalName"` + RulesetID int64 `json:"rulesetId"` + RulesetName *string `json:"rulesetName"` + Style string `json:"style"` + UpdateTime int64 `json:"updateTime"` +} + +// GetEnvironmentsResponse 获取环境列表响应 +type GetEnvironmentsResponse struct { + Data struct { + Contents []Environment `json:"contents"` + } `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` +} + +// GetEnvironments 获取环境列表 +func (c *SqlWorkbenchClient) GetEnvironments(organizationID int64, cookie string) (*GetEnvironmentsResponse, error) { + c.log.Infof("Attempting to get environments for organization %d", organizationID) + + // 构建获取环境列表URL + environmentsURL := fmt.Sprintf("%s/api/v2/collaboration/environments?currentOrganizationId=%d&enabled=true", c.baseURL, organizationID) + + // 创建请求 + req, err := http.NewRequest("GET", environmentsURL, nil) + if err != nil { + c.log.Errorf("Failed to create get environments request: %v", err) + return nil, fmt.Errorf("failed to create get environments request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Cookie", cookie) + req.Header.Set("X-Xsrf-Token", c.ExtractCookieValue(cookie, "XSRF-TOKEN")) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send get environments request: %v", err) + return nil, fmt.Errorf("failed to send get environments request: %v", err) + } + defer resp.Body.Close() + + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read get environments response: %v", err) + return nil, fmt.Errorf("failed to read get environments response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Get environments failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("get environments failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var environmentsResp GetEnvironmentsResponse + if err := json.Unmarshal(body, &environmentsResp); err != nil { + c.log.Errorf("Failed to parse get environments response: %v", err) + return nil, fmt.Errorf("failed to parse get environments response: %v", err) + } + + // 检查业务状态 + if !environmentsResp.Successful { + c.log.Errorf("Get environments failed: %s", environmentsResp.HTTPStatus) + return nil, fmt.Errorf("get environments failed: %s", environmentsResp.HTTPStatus) + } + + c.log.Infof("Successfully got %d environments", len(environmentsResp.Data.Contents)) + return &environmentsResp, nil +} + +// CreateDatasources 创建数据源 +func (c *SqlWorkbenchClient) CreateDatasources(datasource CreateDatasourceRequest, publicKey string, cookie string, organizationID int64) (*CreateDatasourceResponse, error) { + c.log.Infof("Attempting to create datasource: %s", datasource.Name) + + // 加密密码 + encryptedPassword, err := c.EncryptPasswordWithRSA(datasource.Password, publicKey) + if err != nil { + c.log.Errorf("Failed to encrypt password for datasource %s: %v", datasource.Name, err) + return nil, fmt.Errorf("failed to encrypt password for datasource %s: %v", datasource.Name, err) + } + datasource.Password = encryptedPassword + + // 构建创建数据源URL + createDatasourceURL := fmt.Sprintf("%s/api/v2/datasource/datasources?currentOrganizationId=%d&wantCatchError=false&holdErrorTip=true", c.baseURL, organizationID) + + // 准备JSON请求体 + jsonData, err := json.Marshal(datasource) + if err != nil { + c.log.Errorf("Failed to marshal datasource data: %v", err) + return nil, fmt.Errorf("failed to marshal datasource data: %v", err) + } + + // 创建请求 + req, err := http.NewRequest("POST", createDatasourceURL, bytes.NewBuffer(jsonData)) + if err != nil { + c.log.Errorf("Failed to create create datasource request: %v", err) + return nil, fmt.Errorf("failed to create create datasource request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Cookie", cookie) + req.Header.Set("X-Xsrf-Token", c.ExtractCookieValue(cookie, "XSRF-TOKEN")) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send create datasource request: %v", err) + return nil, fmt.Errorf("failed to send create datasource request: %v", err) + } + defer resp.Body.Close() + + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read create datasource response: %v", err) + return nil, fmt.Errorf("failed to read create datasource response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Create datasource failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("create datasource failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var createDatasourceResp CreateDatasourceResponse + if err := json.Unmarshal(body, &createDatasourceResp); err != nil { + c.log.Errorf("Failed to parse create datasource response: %v", err) + return nil, fmt.Errorf("failed to parse create datasource response: %v", err) + } + + // 检查业务状态 + if !createDatasourceResp.Successful { + errorMsg := "create datasource failed" + if createDatasourceResp.Message != nil { + errorMsg = *createDatasourceResp.Message + } + c.log.Errorf("Create datasource failed: %s", errorMsg) + return nil, fmt.Errorf("create datasource failed: %s", errorMsg) + } + + c.log.Infof("Successfully created datasource: %s (ID: %d)", createDatasourceResp.Data.Name, createDatasourceResp.Data.ID) + return &createDatasourceResp, nil +} + +// UpdateDatasource 修改数据源 +func (c *SqlWorkbenchClient) UpdateDatasource(datasourceId int64, updateDatasource UpdateDatasourceRequest, publicKey string, cookie string, organizationID int64) (*CreateDatasourceResponse, error) { + c.log.Infof("Attempting to update datasource with ID: %d", datasourceId) + + if updateDatasource.Password != nil { + // 加密密码 + encryptedPassword, err := c.EncryptPasswordWithRSA(*updateDatasource.Password, publicKey) + if err != nil { + c.log.Errorf("Failed to encrypt password for datasource %s: %v", *updateDatasource.Name, err) + return nil, fmt.Errorf("failed to encrypt password for datasource %s: %v", *updateDatasource.Name, err) + } + updateDatasource.Password = &encryptedPassword + } + + // 构建修改数据源URL + updateDatasourceURL := fmt.Sprintf("%s/api/v2/datasource/datasources/%d?currentOrganizationId=%d", c.baseURL, datasourceId, organizationID) + + // 准备JSON请求体 + jsonData, err := json.Marshal(updateDatasource) + if err != nil { + c.log.Errorf("Failed to marshal update datasource data: %v", err) + return nil, fmt.Errorf("failed to marshal update datasource data: %v", err) + } + + // 创建PUT请求 + req, err := http.NewRequest("PUT", updateDatasourceURL, bytes.NewBuffer(jsonData)) + if err != nil { + c.log.Errorf("Failed to create update datasource request: %v", err) + return nil, fmt.Errorf("failed to create update datasource request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Cookie", cookie) + req.Header.Set("X-Xsrf-Token", c.ExtractCookieValue(cookie, "XSRF-TOKEN")) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send update datasource request: %v", err) + return nil, fmt.Errorf("failed to send update datasource request: %v", err) + } + defer resp.Body.Close() + + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read update datasource response: %v", err) + return nil, fmt.Errorf("failed to read update datasource response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Update datasource failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("update datasource failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var updateDatasourceResp CreateDatasourceResponse + if err := json.Unmarshal(body, &updateDatasourceResp); err != nil { + c.log.Errorf("Failed to parse update datasource response: %v", err) + return nil, fmt.Errorf("failed to parse update datasource response: %v", err) + } + + // 检查业务状态 + if !updateDatasourceResp.Successful { + errorMsg := "update datasource failed" + if updateDatasourceResp.Message != nil { + errorMsg = *updateDatasourceResp.Message + } + c.log.Errorf("Update datasource failed: %s", errorMsg) + return nil, fmt.Errorf("update datasource failed: %s", errorMsg) + } + + c.log.Infof("Successfully updated datasource: %s (ID: %d)", updateDatasourceResp.Data.Name, updateDatasourceResp.Data.ID) + return &updateDatasourceResp, nil +} + +// DeleteDatasource 删除数据源 +func (c *SqlWorkbenchClient) DeleteDatasource(id int64, cookie string, organizationID int64) (*DeleteDatasourceResponse, error) { + c.log.Infof("Attempting to delete datasource with ID: %d", id) + + // 构建删除数据源URL + deleteDatasourceURL := fmt.Sprintf("%s/api/v2/datasource/datasources/%d?currentOrganizationId=%d", c.baseURL, id, organizationID) + + // 创建DELETE请求 + req, err := http.NewRequest("DELETE", deleteDatasourceURL, nil) + if err != nil { + c.log.Errorf("Failed to create delete datasource request: %v", err) + return nil, fmt.Errorf("failed to create delete datasource request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Cookie", cookie) + req.Header.Set("X-Xsrf-Token", c.ExtractCookieValue(cookie, "XSRF-TOKEN")) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send delete datasource request: %v", err) + return nil, fmt.Errorf("failed to send delete datasource request: %v", err) + } + defer resp.Body.Close() + + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read delete datasource response: %v", err) + return nil, fmt.Errorf("failed to read delete datasource response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Delete datasource failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("delete datasource failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var deleteDatasourceResp DeleteDatasourceResponse + if err := json.Unmarshal(body, &deleteDatasourceResp); err != nil { + c.log.Errorf("Failed to parse delete datasource response: %v", err) + return nil, fmt.Errorf("failed to parse delete datasource response: %v", err) + } + + // 检查业务状态 + if !deleteDatasourceResp.Successful { + errorMsg := "delete datasource failed" + if deleteDatasourceResp.Message != nil { + errorMsg = *deleteDatasourceResp.Message + } + c.log.Errorf("Delete datasource failed: %s", errorMsg) + return nil, fmt.Errorf("delete datasource failed: %s", errorMsg) + } + + c.log.Infof("Successfully deleted datasource: %s (ID: %d)", deleteDatasourceResp.Data.Name, deleteDatasourceResp.Data.ID) + return &deleteDatasourceResp, nil +} + +// CreateUsers 创建用户 +func (c *SqlWorkbenchClient) CreateUsers(users []CreateUserRequest, publicKey string, cookie string) (*CreateUsersResponse, error) { + c.log.Infof("Attempting to create %d users", len(users)) + + // 加密所有用户的密码 + for i := range users { + encryptedPassword, err := c.EncryptPasswordWithRSA(users[i].Password, publicKey) + if err != nil { + c.log.Errorf("Failed to encrypt password for user %s: %v", users[i].AccountName, err) + return nil, fmt.Errorf("failed to encrypt password for user %s: %v", users[i].AccountName, err) + } + users[i].Password = encryptedPassword + } + + // 构建创建用户URL + createUsersURL := fmt.Sprintf("%s/api/v2/iam/users/batchCreate?currentOrganizationId=1", c.baseURL) + + // 准备JSON请求体 + jsonData, err := json.Marshal(users) + if err != nil { + c.log.Errorf("Failed to marshal users data: %v", err) + return nil, fmt.Errorf("failed to marshal users data: %v", err) + } + + // 创建请求 + req, err := http.NewRequest("POST", createUsersURL, bytes.NewBuffer(jsonData)) + if err != nil { + c.log.Errorf("Failed to create create users request: %v", err) + return nil, fmt.Errorf("failed to create create users request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Cookie", cookie) + req.Header.Set("X-Xsrf-Token", c.ExtractCookieValue(cookie, "XSRF-TOKEN")) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send create users request: %v", err) + return nil, fmt.Errorf("failed to send create users request: %v", err) + } + defer resp.Body.Close() + + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read create users response: %v", err) + return nil, fmt.Errorf("failed to read create users response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Create users failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("create users failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var createUsersResp CreateUsersResponse + if err := json.Unmarshal(body, &createUsersResp); err != nil { + c.log.Errorf("Failed to parse create users response: %v", err) + return nil, fmt.Errorf("failed to parse create users response: %v", err) + } + + // 检查业务状态 + if !createUsersResp.Successful { + errorMsg := "create users failed" + if createUsersResp.Message != nil { + errorMsg = *createUsersResp.Message + } + c.log.Errorf("Create users failed: %s", errorMsg) + return nil, fmt.Errorf("create users failed: %s", errorMsg) + } + + c.log.Infof("Successfully created %d users", len(createUsersResp.Data.Contents)) + return &createUsersResp, nil +} + +// ActivateUser 激活用户 +func (c *SqlWorkbenchClient) ActivateUser(username, currentPassword, newPassword, publicKey, cookie string) (*ActivateUserResponse, error) { + c.log.Infof("Attempting to activate user: %s", username) + + // 加密当前密码和新密码 + encryptedCurrentPassword, err := c.EncryptPasswordWithRSA(currentPassword, publicKey) + if err != nil { + c.log.Errorf("Failed to encrypt current password for user %s: %v", username, err) + return nil, fmt.Errorf("failed to encrypt current password for user %s: %v", username, err) + } + + encryptedNewPassword, err := c.EncryptPasswordWithRSA(newPassword, publicKey) + if err != nil { + c.log.Errorf("Failed to encrypt new password for user %s: %v", username, err) + return nil, fmt.Errorf("failed to encrypt new password for user %s: %v", username, err) + } + + // 构建激活用户URL + activateUserURL := fmt.Sprintf("%s/api/v2/iam/users/%s/activate?currentOrganizationId=", c.baseURL, username) + + // 准备激活用户请求 + activateUserReq := ActivateUserRequest{ + Username: username, + CurrentPassword: encryptedCurrentPassword, + NewPassword: encryptedNewPassword, + } + + // 准备JSON请求体 + jsonData, err := json.Marshal(activateUserReq) + if err != nil { + c.log.Errorf("Failed to marshal activate user data: %v", err) + return nil, fmt.Errorf("failed to marshal activate user data: %v", err) + } + + // 创建请求 + req, err := http.NewRequest("POST", activateUserURL, bytes.NewBuffer(jsonData)) + if err != nil { + c.log.Errorf("Failed to create activate user request: %v", err) + return nil, fmt.Errorf("failed to create activate user request: %v", err) + } + + // 设置请求头 + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Cookie", cookie) + req.Header.Set("X-Xsrf-Token", c.ExtractCookieValue(cookie, "XSRF-TOKEN")) + + // 发送请求 + resp, err := c.httpClient.Do(req) + if err != nil { + c.log.Errorf("Failed to send activate user request: %v", err) + return nil, fmt.Errorf("failed to send activate user request: %v", err) + } + defer resp.Body.Close() + + // 读取响应 + body, err := io.ReadAll(resp.Body) + if err != nil { + c.log.Errorf("Failed to read activate user response: %v", err) + return nil, fmt.Errorf("failed to read activate user response: %v", err) + } + + // 检查HTTP状态码 + if resp.StatusCode != http.StatusOK { + c.log.Errorf("Activate user failed with status code: %d, response: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("activate user failed with status code: %d", resp.StatusCode) + } + + // 解析响应 + var activateUserResp ActivateUserResponse + if err := json.Unmarshal(body, &activateUserResp); err != nil { + c.log.Errorf("Failed to parse activate user response: %v", err) + return nil, fmt.Errorf("failed to parse activate user response: %v", err) + } + + // 检查业务状态 + if !activateUserResp.Successful { + errorMsg := "activate user failed" + if activateUserResp.Message != nil { + errorMsg = *activateUserResp.Message + } + c.log.Errorf("Activate user failed: %s", errorMsg) + return nil, fmt.Errorf("activate user failed: %s", errorMsg) + } + + c.log.Infof("Successfully activated user: %s (ID: %d)", activateUserResp.Data.Name, activateUserResp.Data.ID) + return &activateUserResp, nil +} + +// EncryptPasswordWithRSA 使用RSA公钥加密密码(兼容JSEncrypt) +func (c *SqlWorkbenchClient) EncryptPasswordWithRSA(password, publicKey string) (string, error) { + // 解码Base64格式的公钥 + keyBytes, err := base64.StdEncoding.DecodeString(publicKey) + if err != nil { + return "", fmt.Errorf("failed to decode base64 public key: %v", err) + } + + // 解析公钥 + pub, err := x509.ParsePKIXPublicKey(keyBytes) + if err != nil { + return "", fmt.Errorf("failed to parse public key: %v", err) + } + + rsaPub, ok := pub.(*rsa.PublicKey) + if !ok { + return "", fmt.Errorf("not an RSA public key") + } + + // 使用PKCS#1 v1.5填充加密(兼容JSEncrypt) + encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPub, []byte(password)) + if err != nil { + return "", fmt.Errorf("failed to encrypt password: %v", err) + } + + // 返回Base64编码的加密结果 + return base64.StdEncoding.EncodeToString(encrypted), nil +} + +// ExtractCookieValue 从Cookie字符串中提取指定名称的值 +func (c *SqlWorkbenchClient) ExtractCookieValue(cookieStr, cookieName string) string { + if cookieStr == "" { + return "" + } + + // 使用正则表达式提取Cookie值 + pattern := fmt.Sprintf(`%s=([^;]+)`, regexp.QuoteMeta(cookieName)) + re := regexp.MustCompile(pattern) + matches := re.FindStringSubmatch(cookieStr) + + if len(matches) > 1 { + return matches[1] + } + + return "" +} + +// MergeCookies 合并XSRF-TOKEN和JSESSIONID +func (c *SqlWorkbenchClient) MergeCookies(xsrfTokenStr, jsessionIdStr string) string { + xsrfToken := c.ExtractCookieValue(xsrfTokenStr, "XSRF-TOKEN") + jsessionId := c.ExtractCookieValue(jsessionIdStr, "JSESSIONID") + + if xsrfToken == "" && jsessionId == "" { + return "" + } + + var cookies []string + if jsessionId != "" { + cookies = append(cookies, fmt.Sprintf("JSESSIONID=%s", jsessionId)) + } + if xsrfToken != "" { + cookies = append(cookies, fmt.Sprintf("XSRF-TOKEN=%s", xsrfToken)) + } + + return strings.Join(cookies, "; ") +} + +// LoginRequest 登录请求结构 +type LoginRequest struct { + Username string `form:"username"` + Password string `form:"password"` +} + +// LoginResponse 登录响应结构 +type LoginResponse struct { + Data string `json:"data"` + DurationMillis *int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID *string `json:"requestId"` + Server *string `json:"server"` + Successful bool `json:"successful"` + Timestamp *int64 `json:"timestamp"` + TraceID *string `json:"traceId"` + // 错误相关字段 + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Cookie string `json:"cookie"` + Error interface{} `json:"error"` +} + +// CreateUserRequest 创建用户请求结构 +type CreateUserRequest struct { + AccountName string `json:"accountName"` + Name string `json:"name"` + Password string `json:"password"` + Enabled bool `json:"enabled"` + RoleIDs []int64 `json:"roleIds"` +} + +// Address 地址结构 +type Address struct { + Country *string `json:"country"` + Formatted *string `json:"formatted"` + Locality *string `json:"locality"` + PostalCode *string `json:"postalCode"` + Region *string `json:"region"` + StreetAddress *string `json:"streetAddress"` +} + +// User 用户结构 +type User struct { + AccessTokenHash *string `json:"accessTokenHash"` + AccountName string `json:"accountName"` + AccountNonExpired bool `json:"accountNonExpired"` + AccountNonLocked bool `json:"accountNonLocked"` + Active bool `json:"active"` + Address Address `json:"address"` + Attributes interface{} `json:"attributes"` + Audience *string `json:"audience"` + AuthenticatedAt *int64 `json:"authenticatedAt"` + AuthenticationContextClass *string `json:"authenticationContextClass"` + AuthenticationMethods interface{} `json:"authenticationMethods"` + Authorities interface{} `json:"authorities"` + AuthorizationCodeHash *string `json:"authorizationCodeHash"` + AuthorizedActions interface{} `json:"authorizedActions"` + AuthorizedParty *string `json:"authorizedParty"` + Birthdate *string `json:"birthdate"` + BuiltIn bool `json:"builtIn"` + Claims map[string]interface{} `json:"claims"` + CreateTime int64 `json:"createTime"` + CreatorID int64 `json:"creatorId"` + CreatorName *string `json:"creatorName"` + CredentialsNonExpired bool `json:"credentialsNonExpired"` + Description *string `json:"description"` + Email *string `json:"email"` + EmailVerified *bool `json:"emailVerified"` + Enabled bool `json:"enabled"` + ExpiresAt *int64 `json:"expiresAt"` + ExtraProperties interface{} `json:"extraProperties"` + FamilyName *string `json:"familyName"` + FullName *string `json:"fullName"` + Gender *string `json:"gender"` + GivenName *string `json:"givenName"` + ID int64 `json:"id"` + IDToken *string `json:"idToken"` + IssuedAt *int64 `json:"issuedAt"` + Issuer *string `json:"issuer"` + LastLoginTime *int64 `json:"lastLoginTime"` + Locale *string `json:"locale"` + LoginTime *int64 `json:"loginTime"` + MiddleName *string `json:"middleName"` + Name string `json:"name"` + NickName *string `json:"nickName"` + Nonce *string `json:"nonce"` + OrganizationID int64 `json:"organizationId"` + OrganizationIDs interface{} `json:"organizationIds"` + OrganizationType *string `json:"organizationType"` + PhoneNumber *string `json:"phoneNumber"` + PhoneNumberVerified *bool `json:"phoneNumberVerified"` + Picture *string `json:"picture"` + PreferredUsername *string `json:"preferredUsername"` + Profile *string `json:"profile"` + ResourceManagementPermissions interface{} `json:"resourceManagementPermissions"` + RoleIDs interface{} `json:"roleIds"` + Roles interface{} `json:"roles"` + Subject *string `json:"subject"` + SystemOperationPermissions interface{} `json:"systemOperationPermissions"` + Type string `json:"type"` + UpdateTime int64 `json:"updateTime"` + UpdatedAt *int64 `json:"updatedAt"` + UserInfo interface{} `json:"userInfo"` + Username string `json:"username"` + Website *string `json:"website"` + ZoneInfo *string `json:"zoneInfo"` +} + +// CreateUsersResponse 创建用户响应结构 +type CreateUsersResponse struct { + Data struct { + Contents []User `json:"contents"` + } `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` + // 错误相关字段 + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Error interface{} `json:"error,omitempty"` +} + +// Organization 组织结构 +type Organization struct { + Builtin bool `json:"builtin"` + CreateTime int64 `json:"createTime"` + Description string `json:"description"` + DisplayName string `json:"displayName"` + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + UniqueIdentifier string `json:"uniqueIdentifier"` + UpdateTime int64 `json:"updateTime"` +} + +// GetOrganizationsResponse 获取组织响应结构 +type GetOrganizationsResponse struct { + Data struct { + Contents []Organization `json:"contents"` + } `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID *string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` + XsrfToken string `json:"xsrfToken"` + // 错误相关字段 + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Error interface{} `json:"error,omitempty"` +} + +// SSLConfig SSL配置结构 +type SSLConfig struct { + Enabled bool `json:"enabled"` + CACertObjectID *string `json:"CACertObjectId,omitempty"` + CacertObjectID *string `json:"cacertObjectId,omitempty"` + ClientCertObjectID *string `json:"clientCertObjectId,omitempty"` + ClientKeyObjectID *string `json:"clientKeyObjectId,omitempty"` +} + +// CreateDatasourceRequest 创建数据源请求结构 +type CreateDatasourceRequest struct { + CreatorID int64 `json:"creatorId"` + Type string `json:"type"` + Name string `json:"name"` + Username string `json:"username"` + Password string `json:"password"` + SysTenantUsername *string `json:"sysTenantUsername"` + ServiceName *string `json:"serviceName"` + SSLConfig SSLConfig `json:"sslConfig"` + SysTenantPassword *string `json:"sysTenantPassword"` + Properties interface{} `json:"properties"` + EnvironmentID int64 `json:"environmentId"` + JdbcURLParameters map[string]interface{} `json:"jdbcUrlParameters"` + Host string `json:"host"` + Port string `json:"port"` +} + +// UpdateDatasourceRequest 创建数据源请求结构 +type UpdateDatasourceRequest struct { + Id int64 `json:"id"` + CreatorID *int64 `json:"creatorId"` + Type string `json:"type"` + Name *string `json:"name"` + Username string `json:"username"` + Password *string `json:"password"` + SysTenantUsername *string `json:"sysTenantUsername"` + ServiceName *string `json:"serviceName"` + SSLConfig SSLConfig `json:"sslConfig"` + SysTenantPassword *string `json:"sysTenantPassword"` + Properties *interface{} `json:"properties"` + EnvironmentID int64 `json:"environmentId"` + JdbcURLParameters *map[string]interface{} `json:"jdbcUrlParameters"` + Host string `json:"host"` + Port string `json:"port"` +} + +// DataSourceStatus 数据源状态结构 +type DataSourceStatus struct { + ErrorCode *string `json:"errorCode"` + ErrorMessage *string `json:"errorMessage"` + Status string `json:"status"` + Type *string `json:"type"` +} + +// DataSource 数据源结构 +type DataSource struct { + CatalogName *string `json:"catalogName"` + CloudProvider *string `json:"cloudProvider"` + ClusterName *string `json:"clusterName"` + ConnectType string `json:"connectType"` + CreateTime int64 `json:"createTime"` + CreatorID int64 `json:"creatorId"` + CreatorName *string `json:"creatorName"` + DbObjectLastSyncTime *int64 `json:"dbObjectLastSyncTime"` + DefaultSchema string `json:"defaultSchema"` + DialectType string `json:"dialectType"` + DssDataSourceID *string `json:"dssDataSourceId"` + Enabled bool `json:"enabled"` + EnvironmentID int64 `json:"environmentId"` + EnvironmentName string `json:"environmentName"` + EnvironmentStyle string `json:"environmentStyle"` + Host string `json:"host"` + ID int64 `json:"id"` + InstanceNickName *string `json:"instanceNickName"` + JdbcURLParameters map[string]interface{} `json:"jdbcUrlParameters"` + LabelIDs interface{} `json:"labelIds"` + LastAccessTime *int64 `json:"lastAccessTime"` + Name string `json:"name"` + ObtenantName *string `json:"obtenantName"` + OrganizationID int64 `json:"organizationId"` + OwnerID *string `json:"ownerId"` + PasswordSaved bool `json:"passwordSaved"` + PermittedActions interface{} `json:"permittedActions"` + Port int64 `json:"port"` + ProjectID *string `json:"projectId"` + ProjectName *string `json:"projectName"` + Properties map[string]interface{} `json:"properties"` + QueryTimeoutSeconds int64 `json:"queryTimeoutSeconds"` + ReadonlyUsername *string `json:"readonlyUsername"` + Region *string `json:"region"` + ServiceName *string `json:"serviceName"` + SessionInitScript *string `json:"sessionInitScript"` + SetTop bool `json:"setTop"` + Sid *string `json:"sid"` + SSLConfig SSLConfig `json:"sslConfig"` + Status DataSourceStatus `json:"status"` + SupportedOperations interface{} `json:"supportedOperations"` + SysTenantUsername *string `json:"sysTenantUsername"` + Temp bool `json:"temp"` + TenantName *string `json:"tenantName"` + TenantNickName *string `json:"tenantNickName"` + Type string `json:"type"` + UpdateTime int64 `json:"updateTime"` + UserRole *string `json:"userRole"` + Username string `json:"username"` + VisibleScope string `json:"visibleScope"` +} + +// CreateDatasourceResponse 创建数据源响应结构 +type CreateDatasourceResponse struct { + Data DataSource `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` + // 错误相关字段 + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Error interface{} `json:"error,omitempty"` +} + +// DeleteDatasourceResponse 删除数据源响应结构 +type DeleteDatasourceResponse struct { + Data DataSource `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` + // 错误相关字段 + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Error interface{} `json:"error,omitempty"` +} + +// GetPublicKeyResponse 获取公钥响应结构 +type GetPublicKeyResponse struct { + Data string `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID *string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` + // 错误相关字段 + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Error interface{} `json:"error,omitempty"` +} + +// ActivateUserRequest 激活用户请求结构 +type ActivateUserRequest struct { + Username string `json:"username"` + CurrentPassword string `json:"currentPassword"` + NewPassword string `json:"newPassword"` +} + +// ActivateUserResponse 激活用户响应结构 +type ActivateUserResponse struct { + Data User `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` + // 错误相关字段 + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Error interface{} `json:"error,omitempty"` +} diff --git a/internal/sql_workbench/config/sql_workbench_options.go b/internal/sql_workbench/config/sql_workbench_options.go new file mode 100644 index 000000000..505b33d04 --- /dev/null +++ b/internal/sql_workbench/config/sql_workbench_options.go @@ -0,0 +1,8 @@ +package sql_workbench + +type SqlWorkbenchOpts struct { + Host string `yaml:"host"` + Port string `yaml:"port"` + AdminUser string `yaml:"admin_user"` + AdminPassword string `yaml:"admin_password"` +} diff --git a/internal/sql_workbench/service/operation_log_middleware.go b/internal/sql_workbench/service/operation_log_middleware.go new file mode 100644 index 000000000..60c914b3e --- /dev/null +++ b/internal/sql_workbench/service/operation_log_middleware.go @@ -0,0 +1,12 @@ +package sql_workbench + +import ( + "github.com/actiontech/dms/internal/dms/biz" +) + +// OperationLogMiddlewareConfig 配置操作日志中间件 +type OperationLogMiddlewareConfig struct { + CbOperationLogUsecase *biz.CbOperationLogUsecase + DBServiceUsecase *biz.DBServiceUsecase + SqlWorkbenchService *SqlWorkbenchService +} diff --git a/internal/sql_workbench/service/operation_log_middleware_ce.go b/internal/sql_workbench/service/operation_log_middleware_ce.go new file mode 100644 index 000000000..b489e8c3a --- /dev/null +++ b/internal/sql_workbench/service/operation_log_middleware_ce.go @@ -0,0 +1,15 @@ +//go:build !enterprise +// +build !enterprise + +package sql_workbench + +import "github.com/labstack/echo/v4" + +// GetOperationLogBodyDumpMiddleware 返回用于记录操作日志的 BodyDump 中间件 +func GetOperationLogBodyDumpMiddleware(config OperationLogMiddlewareConfig) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + return next(c) + } + } +} diff --git a/internal/sql_workbench/service/sql_workbench_service.go b/internal/sql_workbench/service/sql_workbench_service.go new file mode 100644 index 000000000..fb55f0293 --- /dev/null +++ b/internal/sql_workbench/service/sql_workbench_service.go @@ -0,0 +1,1763 @@ +package sql_workbench + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "github.com/actiontech/dms/internal/pkg/cloudbeaver" + "github.com/actiontech/dms/internal/pkg/utils" + + dmsV1 "github.com/actiontech/dms/api/dms/service/v1" + "github.com/actiontech/dms/internal/apiserver/conf" + "github.com/actiontech/dms/internal/dms/biz" + pkgConst "github.com/actiontech/dms/internal/dms/pkg/constant" + "github.com/actiontech/dms/internal/dms/storage" + "github.com/actiontech/dms/internal/pkg/locale" + dbmodel "github.com/actiontech/dms/internal/dms/storage/model" + "github.com/actiontech/dms/internal/sql_workbench/client" + config "github.com/actiontech/dms/internal/sql_workbench/config" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" + _const "github.com/actiontech/dms/pkg/dms-common/pkg/const" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" + utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" + pkgRand "github.com/actiontech/dms/pkg/rand" + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" + "golang.org/x/text/language" +) + +const SQL_WORKBENCH_URL = "/odc_query" +const SQL_WORKBENCH_PREFIX = "DMS-" +const SQL_WORKBENCH_DEFAULT_PASSWORD = "DMS123__" +const SQL_WORKBENCH_REAL_PASSWORD = "DMS123__@" +const INDIVIDUAL_SPACE = 4 + +// ODC 会话相关的 cookie 名称 +const ( + ODCSessionCookieName = "JSESSIONID" + ODCXsrfTokenCookieName = "XSRF-TOKEN" +) + +// odcSession ODC 会话缓存结构 +type odcSession struct { + dmsToken string + jsessionID string + xsrfToken string +} + +var ( + dmsUserIdODCSessionMap = make(map[string]odcSession) + odcSessionMutex = &sync.Mutex{} +) + +// generateSqlWorkbenchUsername 生成 SQL Workbench 用户名 +func (s *SqlWorkbenchService) generateSqlWorkbenchUsername(dmsUserName string) string { + return SQL_WORKBENCH_PREFIX + dmsUserName +} + +// TempDBAccount 临时数据库账号 +type TempDBAccount struct { + DBAccountUid string `json:"db_account_uid"` + AccountInfo AccountInfo `json:"account_info"` + Explanation string `json:"explanation"` + ExpiredTime string `json:"expired_time"` + DbService dmsV1.UidWithName `json:"db_service"` +} + +// AccountInfo 账号信息 +type AccountInfo struct { + User string `json:"user"` + Hostname string `json:"hostname"` + Password string `json:"password"` +} + +// ListDBAccountReply 数据库账号列表响应 +type ListDBAccountReply struct { + Data []*TempDBAccount `json:"data"` + Code int `json:"code"` + Message string `json:"message"` +} + +type SqlWorkbenchService struct { + cfg *config.SqlWorkbenchOpts + log *utilLog.Helper + client *client.SqlWorkbenchClient + userUsecase *biz.UserUsecase + dbServiceUsecase *biz.DBServiceUsecase + projectUsecase *biz.ProjectUsecase + opPermissionVerifyUsecase *biz.OpPermissionVerifyUsecase + sqlWorkbenchUserRepo biz.SqlWorkbenchUserRepo + sqlWorkbenchDatasourceRepo biz.SqlWorkbenchDatasourceRepo + proxyTargetRepo biz.ProxyTargetRepo + cbOperationLogUsecase *biz.CbOperationLogUsecase +} + +func NewAndInitSqlWorkbenchService(logger utilLog.Logger, opts *conf.DMSOptions) (*SqlWorkbenchService, error) { + var sqlWorkbenchClient *client.SqlWorkbenchClient + if opts.SqlWorkBenchOpts != nil { + sqlWorkbenchClient = client.NewSqlWorkbenchClient(opts.SqlWorkBenchOpts, logger) + } + + // 初始化存储层 + st, err := storage.NewStorage(logger, &storage.StorageConfig{ + User: opts.ServiceOpts.Database.UserName, + Password: opts.ServiceOpts.Database.Password, + Host: opts.ServiceOpts.Database.Host, + Port: opts.ServiceOpts.Database.Port, + Schema: opts.ServiceOpts.Database.Database, + Debug: opts.ServiceOpts.Database.Debug, + AutoMigrate: opts.ServiceOpts.Database.AutoMigrate, + }) + if err != nil { + return nil, fmt.Errorf("failed to initialize storage: %v", err) + } + + // 初始化事务生成器 + tx := storage.NewTXGenerator() + + // 初始化基础存储层 + opPermissionVerifyRepo := storage.NewOpPermissionVerifyRepo(logger, st) + opPermissionVerifyUsecase := biz.NewOpPermissionVerifyUsecase(logger, tx, opPermissionVerifyRepo) + + // 初始化用户相关 + userRepo := storage.NewUserRepo(logger, st) + userGroupRepo := storage.NewUserGroupRepo(logger, st) + pluginRepo := storage.NewPluginRepo(logger, st) + pluginUsecase, err := biz.NewDMSPluginUsecase(logger, pluginRepo) + if err != nil { + return nil, fmt.Errorf("failed to new dms plugin usecase: %v", err) + } + + opPermissionRepo := storage.NewOpPermissionRepo(logger, st) + opPermissionUsecase := biz.NewOpPermissionUsecase(logger, tx, opPermissionRepo, pluginUsecase) + + cloudbeaverRepo := storage.NewCloudbeaverRepo(logger, st) + loginConfigurationRepo := storage.NewLoginConfigurationRepo(logger, st) + loginConfigurationUsecase := biz.NewLoginConfigurationUsecase(logger, tx, loginConfigurationRepo) + + ldapConfigurationRepo := storage.NewLDAPConfigurationRepo(logger, st) + ldapConfigurationUsecase := biz.NewLDAPConfigurationUsecase(logger, tx, ldapConfigurationRepo) + + userUsecase := biz.NewUserUsecase(logger, tx, userRepo, userGroupRepo, pluginUsecase, opPermissionUsecase, opPermissionVerifyUsecase, loginConfigurationUsecase, ldapConfigurationUsecase, cloudbeaverRepo, nil) + + // 初始化项目相关 + memberUsecase := &biz.MemberUsecase{} + environmentTagUsecase := biz.EnvironmentTagUsecase{} + businessTagUsecase := biz.NewBusinessTagUsecase(storage.NewBusinessTagRepo(logger, st), logger) + projectRepo := storage.NewProjectRepo(logger, st) + projectUsecase := biz.NewProjectUsecase(logger, tx, projectRepo, memberUsecase, opPermissionVerifyUsecase, pluginUsecase, businessTagUsecase, &environmentTagUsecase) + + // 初始化数据源相关 + dbServiceRepo := storage.NewDBServiceRepo(logger, st) + environmentTagUsecase = *biz.NewEnvironmentTagUsecase(storage.NewEnvironmentTagRepo(logger, st), logger, projectUsecase, opPermissionVerifyUsecase) + proxyTargetRepo := storage.NewProxyTargetRepo(logger, st) + discoveryTaskRepo := storage.NewSensitiveDataDiscoveryTaskRepo(logger, st) + dbServiceUsecase := biz.NewDBServiceUsecase(logger, dbServiceRepo, discoveryTaskRepo, pluginUsecase, opPermissionVerifyUsecase, projectUsecase, proxyTargetRepo, &environmentTagUsecase) + + // 初始化SqlWorkbench相关的存储层 + sqlWorkbenchUserRepo := storage.NewSqlWorkbenchRepo(logger, st) + sqlWorkbenchDatasourceRepo := storage.NewSqlWorkbenchDatasourceRepo(logger, st) + + // 初始化操作日志相关 + cbOperationLogRepo := storage.NewCbOperationLogRepo(logger, st) + cbOperationLogUsecase := biz.NewCbOperationLogUsecase(logger, cbOperationLogRepo, opPermissionVerifyUsecase, proxyTargetRepo, biz.NewSystemVariableUsecase(logger, storage.NewSystemVariableRepo(logger, st))) + + return &SqlWorkbenchService{ + cfg: opts.SqlWorkBenchOpts, + log: utilLog.NewHelper(logger, utilLog.WithMessageKey("sql_workbench.service")), + client: sqlWorkbenchClient, + userUsecase: userUsecase, + dbServiceUsecase: dbServiceUsecase, + projectUsecase: projectUsecase, + opPermissionVerifyUsecase: opPermissionVerifyUsecase, + sqlWorkbenchUserRepo: sqlWorkbenchUserRepo, + sqlWorkbenchDatasourceRepo: sqlWorkbenchDatasourceRepo, + proxyTargetRepo: proxyTargetRepo, + cbOperationLogUsecase: cbOperationLogUsecase, + }, nil +} + +func (sqlWorkbenchService *SqlWorkbenchService) IsConfigured() bool { + if sqlWorkbenchService.cfg == nil { + return false + } + return sqlWorkbenchService.cfg != nil && sqlWorkbenchService.cfg.Host != "" && sqlWorkbenchService.cfg.Port != "" +} + +func (sqlWorkbenchService *SqlWorkbenchService) GetOdcProxyTarget() ([]*middleware.ProxyTarget, error) { + cfg := sqlWorkbenchService.cfg + rawUrl, err := url.Parse(fmt.Sprintf("http://%v:%v", cfg.Host, cfg.Port)) + if err != nil { + return nil, err + } + sqlWorkbenchService.log.Infof("ODC proxy target URL: %s", rawUrl.String()) + return []*middleware.ProxyTarget{ + { + URL: rawUrl, + }, + }, nil +} + +func (sqlWorkbenchService *SqlWorkbenchService) GetRootUri() string { + return SQL_WORKBENCH_URL +} + +func (sqlWorkbenchService *SqlWorkbenchService) Login() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + // 从Cookie中获取DMS token + var dmsToken string + for _, cookie := range c.Cookies() { + if cookie.Name == pkgConst.DMSToken { + dmsToken = cookie.Value + break + } + } + + if dmsToken == "" { + sqlWorkbenchService.log.Errorf("dmsToken is empty") + return fmt.Errorf("dms user token is empty") + } + + dmsUserId, err := jwt.ParseUidFromJwtTokenStr(dmsToken) + if err != nil { + sqlWorkbenchService.log.Errorf("ParseUidFromJwtTokenStr err: %v", err) + return fmt.Errorf("parse dms user uid from token err: %v", err) + } + + // 检查缓存中是否有有效的 ODC 会话 + odcSession := sqlWorkbenchService.getODCSession(dmsUserId, dmsToken) + if odcSession != nil { + // 验证会话是否有效 + if sqlWorkbenchService.validateODCSession(odcSession.jsessionID, odcSession.xsrfToken) { + // 会话有效,设置 cookie 到请求中 + sqlWorkbenchService.setODCCookiesToRequest(c, odcSession.jsessionID, odcSession.xsrfToken) + sqlWorkbenchService.log.Debugf("Using cached ODC session for user: %s", dmsUserId) + return next(c) + } + // 会话无效,清除缓存 + sqlWorkbenchService.log.Debugf("Cached ODC session invalid, clearing cache for user: %s", dmsUserId) + sqlWorkbenchService.clearODCSession(dmsUserId) + } + + // 缓存不存在或会话无效,需要重新登录 + sqlWorkbenchService.log.Debugf("No valid cached ODC session, performing login for user: %s", dmsUserId) + + // 1. 根据dmsUserId从数据库获取用户信息 + user, err := sqlWorkbenchService.userUsecase.GetUser(c.Request().Context(), dmsUserId) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to get user by dmsUserId %s: %v", dmsUserId, err) + return err + } + + // 2. 从数据库表SqlWorkbenchUserCache中判断sqlworkbench中是否存在该用户 + sqlWorkbenchUser, exists, err := sqlWorkbenchService.sqlWorkbenchUserRepo.GetSqlWorkbenchUserByDMSUserID(c.Request().Context(), dmsUserId) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to get sql workbench user cache: %v", err) + return err + } + + // 3. 如果用户不存在,调用sqlworkbench创建用户接口进行创建 + if !exists { + err = sqlWorkbenchService.createSqlWorkbenchUser(c.Request().Context(), user) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to create sql workbench user: %v", err) + return err + } + // 重新获取创建后的用户信息 + sqlWorkbenchUser, _, err = sqlWorkbenchService.sqlWorkbenchUserRepo.GetSqlWorkbenchUserByDMSUserID(c.Request().Context(), dmsUserId) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to get created sql workbench user: %v", err) + return err + } + } + + // 4. 将DMS中的数据源同步给SqlWorkbench + err = sqlWorkbenchService.syncDatasources(c.Request().Context(), user, sqlWorkbenchUser) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to sync datasources: %v", err) + return err + } + + // 5. 调用登录接口进行登录,并且从登录接口的返回值中获取Cookie设置到c echo.Context的上下文中 + jsessionID, xsrfToken, err := sqlWorkbenchService.loginSqlWorkbenchUser(c, user, dmsUserId, dmsToken) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to login sql workbench user: %v", err) + return err + } + + // 将新会话设置到请求中 + sqlWorkbenchService.setODCCookiesToRequest(c, jsessionID, xsrfToken) + + return next(c) + } + } +} + +// createSqlWorkbenchUser 创建SqlWorkbench用户 +func (sqlWorkbenchService *SqlWorkbenchService) createSqlWorkbenchUser(ctx context.Context, dmsUser *biz.User) error { + cookie, _, publicKey, err := sqlWorkbenchService.getUserCookie(sqlWorkbenchService.cfg.AdminUser, sqlWorkbenchService.cfg.AdminPassword) + if err != nil { + return err + } + + // 创建用户请求 + sqlWorkbenchUsername := sqlWorkbenchService.generateSqlWorkbenchUsername(dmsUser.Name) + createUserReq := []client.CreateUserRequest{ + { + AccountName: sqlWorkbenchUsername, + Name: dmsUser.Name, + Password: SQL_WORKBENCH_DEFAULT_PASSWORD, + Enabled: true, + RoleIDs: []int64{INDIVIDUAL_SPACE}, + }, + } + + // 调用创建用户接口 + createUserResp, err := sqlWorkbenchService.client.CreateUsers(createUserReq, publicKey, cookie) + if err != nil { + return fmt.Errorf("failed to create user in sql workbench: %v", err) + } + + if len(createUserResp.Data.Contents) == 0 { + return fmt.Errorf("no user created in sql workbench") + } + + // 激活用户 + activateUserResp, err := sqlWorkbenchService.client.ActivateUser( + sqlWorkbenchService.generateSqlWorkbenchUsername(dmsUser.Name), + SQL_WORKBENCH_DEFAULT_PASSWORD, + SQL_WORKBENCH_REAL_PASSWORD, + publicKey, + cookie, + ) + if err != nil { + return fmt.Errorf("failed to activate user in sql workbench: %v", err) + } + + // 保存用户缓存 + sqlWorkbenchUser := &biz.SqlWorkbenchUser{ + SqlWorkbenchUsername: sqlWorkbenchService.generateSqlWorkbenchUsername(dmsUser.Name), + DMSUserID: dmsUser.UID, + SqlWorkbenchUserId: activateUserResp.Data.ID, + } + + err = sqlWorkbenchService.sqlWorkbenchUserRepo.SaveSqlWorkbenchUserCache(ctx, sqlWorkbenchUser) + if err != nil { + return fmt.Errorf("failed to save sql workbench user cache: %v", err) + } + + sqlWorkbenchService.log.Infof("Successfully created and activated sql workbench user for DMS user %s (ID: %d)", dmsUser.Name, activateUserResp.Data.ID) + return nil +} + +// loginSqlWorkbenchUser 使用SqlWorkbench用户登录并设置Cookie +// 返回 jsessionID 和 xsrfToken,并缓存会话 +func (sqlWorkbenchService *SqlWorkbenchService) loginSqlWorkbenchUser(c echo.Context, dmsUser *biz.User, dmsUserId, dmsToken string) (string, string, error) { + // 获取公钥 + publicKey, err := sqlWorkbenchService.client.GetPublicKey() + if err != nil { + return "", "", fmt.Errorf("failed to get public key: %v", err) + } + + // 使用SqlWorkbench用户登录 + loginResp, err := sqlWorkbenchService.client.Login(sqlWorkbenchService.generateSqlWorkbenchUsername(dmsUser.Name), SQL_WORKBENCH_REAL_PASSWORD, publicKey) + if err != nil { + return "", "", fmt.Errorf("failed to login sql workbench user: %v", err) + } + + // 获取组织信息 + orgResp, err := sqlWorkbenchService.client.GetOrganizations(loginResp.Cookie) + if err != nil { + return "", "", fmt.Errorf("failed to get organizations: %v", err) + } + + // 提取cookie值 + jsessionID := sqlWorkbenchService.client.ExtractCookieValue(loginResp.Cookie, ODCSessionCookieName) + xsrfToken := sqlWorkbenchService.client.ExtractCookieValue(orgResp.XsrfToken, ODCXsrfTokenCookieName) + + // 设置Cookie到echo.Context中 + c.SetCookie(&http.Cookie{ + Name: ODCSessionCookieName, + Value: jsessionID, + Path: "/", + HttpOnly: true, + Secure: false, + }) + + c.SetCookie(&http.Cookie{ + Name: ODCXsrfTokenCookieName, + Value: xsrfToken, + Path: "/", + HttpOnly: false, // XSRF-TOKEN通常需要JavaScript访问 + Secure: false, + }) + + // 缓存会话 + sqlWorkbenchService.setODCSession(dmsUserId, dmsToken, jsessionID, xsrfToken) + + sqlWorkbenchService.log.Infof("Successfully logged in sql workbench user %s", dmsUser.Name) + return jsessionID, xsrfToken, nil +} + +// getODCSession 获取缓存的 ODC 会话 +func (sqlWorkbenchService *SqlWorkbenchService) getODCSession(dmsUserId, dmsToken string) *odcSession { + odcSessionMutex.Lock() + defer odcSessionMutex.Unlock() + + if item, ok := dmsUserIdODCSessionMap[dmsUserId]; ok { + if dmsToken == item.dmsToken { + // 返回副本以避免并发安全问题 + session := item + return &session + } + } + + return nil +} + +// setODCSession 设置 ODC 会话缓存 +func (sqlWorkbenchService *SqlWorkbenchService) setODCSession(dmsUserId, dmsToken, jsessionID, xsrfToken string) { + odcSessionMutex.Lock() + defer odcSessionMutex.Unlock() + + dmsUserIdODCSessionMap[dmsUserId] = odcSession{ + dmsToken: dmsToken, + jsessionID: jsessionID, + xsrfToken: xsrfToken, + } +} + +// clearODCSession 清除 ODC 会话缓存 +func (sqlWorkbenchService *SqlWorkbenchService) clearODCSession(dmsUserId string) { + odcSessionMutex.Lock() + defer odcSessionMutex.Unlock() + + delete(dmsUserIdODCSessionMap, dmsUserId) +} + +// validateODCSession 验证 ODC 会话是否有效 +// 通过调用 GetOrganizations API 来验证会话 +func (sqlWorkbenchService *SqlWorkbenchService) validateODCSession(jsessionID, xsrfToken string) bool { + cookie := fmt.Sprintf("%s=%s; %s=%s", ODCSessionCookieName, jsessionID, ODCXsrfTokenCookieName, xsrfToken) + _, err := sqlWorkbenchService.client.GetOrganizations(cookie) + if err != nil { + sqlWorkbenchService.log.Debugf("ODC session validation failed: %v", err) + return false + } + return true +} + +// setODCCookiesToRequest 将 ODC cookies 设置到请求中 +func (sqlWorkbenchService *SqlWorkbenchService) setODCCookiesToRequest(c echo.Context, jsessionID, xsrfToken string) { + // 更新请求的 Cookie header + // 获取请求中现有的 Cookie header,用于保留客户端已有的 cookies + currentCookies := c.Request().Header.Get("Cookie") + cookieMap := make(map[string]string) + // 解析现有 Cookie 字符串为 map,避免覆盖客户端已有的 cookies + // Cookie 格式为 "key1=value1; key2=value2",使用分号分隔 + if currentCookies != "" { + existingCookies := strings.Split(currentCookies, ";") + for _, cookie := range existingCookies { + cookie = strings.TrimSpace(cookie) + if cookie != "" { + // 使用 SplitN 限制分割次数为 2,防止 cookie 值中包含 "=" 时被错误分割 + parts := strings.SplitN(cookie, "=", 2) + if len(parts) == 2 { + cookieMap[parts[0]] = parts[1] + } + } + } + } + + // 设置 ODC cookies + cookieMap[ODCSessionCookieName] = jsessionID + cookieMap[ODCXsrfTokenCookieName] = xsrfToken + + // 构建新的 Cookie header + var cookieStrings []string + for name, value := range cookieMap { + cookieStrings = append(cookieStrings, fmt.Sprintf("%s=%s", name, value)) + } + + if len(cookieStrings) > 0 { + c.Request().Header.Set("Cookie", strings.Join(cookieStrings, "; ")) + } + + // 更新请求 header 中的 X-XSRF-TOKEN + c.Request().Header.Set("X-XSRF-TOKEN", xsrfToken) +} + +// syncDatasources 同步DMS数据源到SqlWorkbench +func (sqlWorkbenchService *SqlWorkbenchService) syncDatasources(ctx context.Context, dmsUser *biz.User, sqlWorkbenchUser *biz.SqlWorkbenchUser) error { + // 获取用户有权限访问的数据源 + activeDBServices, err := sqlWorkbenchService.getUserAccessibleDBServices(ctx, dmsUser) + if err != nil { + return fmt.Errorf("failed to get user accessible db services: %v", err) + } + + // 获取当前用户Cookie + userCookie, organizationId, _, err := sqlWorkbenchService.getUserCookie(sqlWorkbenchService.generateSqlWorkbenchUsername(dmsUser.Name), SQL_WORKBENCH_REAL_PASSWORD) + if err != nil { + return fmt.Errorf("failed to get user cookie: %v", err) + } + + // 同步数据源 + return sqlWorkbenchService.syncDBServicesToSqlWorkbench(ctx, activeDBServices, sqlWorkbenchUser, userCookie, organizationId) +} + +// getUserAccessibleDBServices 获取用户有权限访问的数据源 +func (sqlWorkbenchService *SqlWorkbenchService) getUserAccessibleDBServices(ctx context.Context, dmsUser *biz.User) ([]*biz.DBService, error) { + // 获取所有活跃的数据源 + activeDBServices, err := sqlWorkbenchService.dbServiceUsecase.GetActiveDBServices(ctx, nil) + if err != nil { + return nil, fmt.Errorf("failed to get active db services: %v", err) + } + + // 检查用户是否有全局权限 + hasGlobalOpPermission, err := sqlWorkbenchService.opPermissionVerifyUsecase.CanOpGlobal(ctx, dmsUser.UID) + if err != nil { + return nil, fmt.Errorf("failed to check global op permission: %v", err) + } + + if hasGlobalOpPermission { + return activeDBServices, nil + } + + // 获取用户的项目和数据源权限 + opPermissions, err := sqlWorkbenchService.opPermissionVerifyUsecase.GetUserOpPermission(ctx, dmsUser.UID) + if err != nil { + return nil, fmt.Errorf("failed to get user op permissions: %v", err) + } + + // 过滤有权限的数据源 + activeDBServices, err = sqlWorkbenchService.filterDBServicesByPermissions(ctx, activeDBServices, opPermissions) + if err != nil { + return nil, fmt.Errorf("failed to filter db services by permissions: %v", err) + } + + // 根据 provision “账号管理” 功能配置的权限进行过滤、修改连接用户 + activeDBServices, err = sqlWorkbenchService.ResetDbServiceByAuth(ctx, activeDBServices, dmsUser.UID) + if err != nil { + return nil, fmt.Errorf("failed to reset db service by auth: %v", err) + } + + return activeDBServices, nil +} + +// filterDBServicesByPermissions 根据权限过滤数据源 +func (sqlWorkbenchService *SqlWorkbenchService) filterDBServicesByPermissions(ctx context.Context, dbServices []*biz.DBService, opPermissions []biz.OpPermissionWithOpRange) ([]*biz.DBService, error) { + projectIdMap := make(map[string]struct{}) + dbServiceIdMap := make(map[string]struct{}) + + for _, opPermission := range opPermissions { + // 项目权限 + if opPermission.OpRangeType == biz.OpRangeTypeProject && opPermission.OpPermissionUID == pkgConst.UIDOfOpPermissionProjectAdmin { + for _, rangeUid := range opPermission.RangeUIDs { + projectIdMap[rangeUid] = struct{}{} + } + } + + // 数据源权限 + if opPermission.OpRangeType == biz.OpRangeTypeDBService && opPermission.OpPermissionUID == pkgConst.UIDOfOpPermissionSQLQuery { + for _, rangeUid := range opPermission.RangeUIDs { + dbServiceIdMap[rangeUid] = struct{}{} + } + } + } + + var filteredDBServices []*biz.DBService + for _, dbService := range dbServices { + // 检查项目权限 + if _, hasProjectPermission := projectIdMap[dbService.ProjectUID]; hasProjectPermission { + filteredDBServices = append(filteredDBServices, dbService) + continue + } + + // 检查数据源权限 + if _, hasDBServicePermission := dbServiceIdMap[dbService.UID]; hasDBServicePermission { + filteredDBServices = append(filteredDBServices, dbService) + } + } + + return filteredDBServices, nil +} + +// getUserCookie 获取当前用户Cookie +func (sqlWorkbenchService *SqlWorkbenchService) getUserCookie(dmsUsername string, dmsUserPassword string) (string, int64, string, error) { + // 获取公钥 + publicKey, err := sqlWorkbenchService.client.GetPublicKey() + if err != nil { + return "", 0, "", fmt.Errorf("failed to get public key: %v", err) + } + + // 使用当前用户账号登录 + loginResp, err := sqlWorkbenchService.client.Login(dmsUsername, dmsUserPassword, publicKey) + if err != nil { + return "", 0, publicKey, fmt.Errorf("failed to login as user: %v", err) + } + + // 获取组织信息 + orgResp, err := sqlWorkbenchService.client.GetOrganizations(loginResp.Cookie) + if err != nil { + return "", 0, publicKey, fmt.Errorf("failed to get organizations: %v", err) + } + + // 检查是否有足够的组织 + if len(orgResp.Data.Contents) < 2 { + return "", 0, publicKey, fmt.Errorf("insufficient organizations, expected at least 2, got %d", len(orgResp.Data.Contents)) + } + + // 合并Cookie + return sqlWorkbenchService.client.MergeCookies(orgResp.XsrfToken, loginResp.Cookie), orgResp.Data.Contents[1].ID, publicKey, nil +} + +// getEnvironmentID 获取环境ID +func (sqlWorkbenchService *SqlWorkbenchService) getEnvironmentID(organizationID int64, cookie string) (int64, error) { + // 调用GetEnvironments接口获取环境信息 + envResp, err := sqlWorkbenchService.client.GetEnvironments(organizationID, cookie) + if err != nil { + return 0, fmt.Errorf("failed to get environments: %v", err) + } + + // 检查是否有环境 + if len(envResp.Data.Contents) == 0 { + return 0, fmt.Errorf("no environments found") + } + + // 优先选择"默认"环境,如果没有则选择第一个 + for _, env := range envResp.Data.Contents { + if env.Name == "默认" { + return env.ID, nil + } + } + + // 如果没有找到"默认"环境,返回第一个环境的ID + return envResp.Data.Contents[0].ID, nil +} + +// syncDBServicesToSqlWorkbench 同步数据源到SqlWorkbench +func (sqlWorkbenchService *SqlWorkbenchService) syncDBServicesToSqlWorkbench(ctx context.Context, dbServices []*biz.DBService, sqlWorkbenchUser *biz.SqlWorkbenchUser, userCookie string, organizationID int64) error { + // 获取公钥 + publicKey, err := sqlWorkbenchService.client.GetPublicKey() + if err != nil { + return fmt.Errorf("failed to get public key: %v", err) + } + + // 获取环境ID + environmentID, err := sqlWorkbenchService.getEnvironmentID(organizationID, userCookie) + if err != nil { + return fmt.Errorf("failed to get environment id: %v", err) + } + + // 获取用户现有的数据源缓存 + existingDatasources, err := sqlWorkbenchService.sqlWorkbenchDatasourceRepo.GetSqlWorkbenchDatasourcesByUserID(ctx, sqlWorkbenchUser.DMSUserID) + if err != nil { + return fmt.Errorf("failed to get existing datasources: %v", err) + } + + // 创建数据源映射 + existingDatasourceMap := make(map[string]*biz.SqlWorkbenchDatasource) + for _, ds := range existingDatasources { + key := sqlWorkbenchService.getDatasourceKey(ds.DMSDBServiceID, ds.Purpose) + existingDatasourceMap[key] = ds + } + + if len(dbServices) == 0 { + sqlWorkbenchService.log.Infof("No accessible db services for user, cleaning up all existing datasources") + return sqlWorkbenchService.cleanupObsoleteDatasources(ctx, dbServices, existingDatasourceMap, userCookie, organizationID) + } + + // 处理每个数据源 + for _, dbService := range dbServices { + key := sqlWorkbenchService.getDatasourceKey(dbService.UID, dbService.AccountPurpose) + + if existingDatasource, exists := existingDatasourceMap[key]; exists { + // 检查是否需要更新 + if sqlWorkbenchService.shouldUpdateDatasource(dbService, existingDatasource) { + err = sqlWorkbenchService.updateDatasourceInSqlWorkbench(ctx, dbService, existingDatasource, publicKey, userCookie, organizationID, environmentID) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to update datasource %s: %v", dbService.Name, err) + } + } + } else { + // 创建新数据源 + err = sqlWorkbenchService.createDatasourceInSqlWorkbench(ctx, dbService, sqlWorkbenchUser, publicKey, userCookie, organizationID, environmentID) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to create datasource %s: %v", dbService.Name, err) + } + } + } + + // 删除不再需要的数据源 + return sqlWorkbenchService.cleanupObsoleteDatasources(ctx, dbServices, existingDatasourceMap, userCookie, organizationID) +} + +// getDatasourceKey 获取数据源唯一键 +func (sqlWorkbenchService *SqlWorkbenchService) getDatasourceKey(dmsDBServiceID, purpose string) string { + return fmt.Sprintf("%s:%s", dmsDBServiceID, purpose) +} + +// shouldUpdateDatasource 判断是否需要更新数据源 +func (sqlWorkbenchService *SqlWorkbenchService) shouldUpdateDatasource(dbService *biz.DBService, existingDatasource *biz.SqlWorkbenchDatasource) bool { + // 比较数据源指纹,如果指纹不同则需要更新 + currentFingerprint := sqlWorkbenchService.dbServiceUsecase.GetDBServiceFingerprint(dbService) + return existingDatasource.DMSDBServiceFingerprint != currentFingerprint +} + +// createDatasourceInSqlWorkbench 在SqlWorkbench中创建数据源 +func (sqlWorkbenchService *SqlWorkbenchService) createDatasourceInSqlWorkbench(ctx context.Context, dbService *biz.DBService, sqlWorkbenchUser *biz.SqlWorkbenchUser, publicKey, userCookie string, organizationID, environmentID int64) error { + // 构建创建数据源请求 + createReq, err := sqlWorkbenchService.buildCreateDatasourceRequest(ctx, dbService, sqlWorkbenchUser, environmentID) + if err != nil { + return fmt.Errorf("failed to build create datasource request: %v", err) + } + + // 调用创建接口 + createResp, err := sqlWorkbenchService.client.CreateDatasources(createReq, publicKey, userCookie, organizationID) + if err != nil { + return fmt.Errorf("failed to create datasource: %v", err) + } + + // 保存缓存 + datasourceCache := &biz.SqlWorkbenchDatasource{ + DMSDBServiceID: dbService.UID, + DMSUserID: sqlWorkbenchUser.DMSUserID, + DMSDBServiceFingerprint: sqlWorkbenchService.dbServiceUsecase.GetDBServiceFingerprint(dbService), + SqlWorkbenchDatasourceID: createResp.Data.ID, + Purpose: dbService.AccountPurpose, + } + + err = sqlWorkbenchService.sqlWorkbenchDatasourceRepo.SaveSqlWorkbenchDatasourceCache(ctx, datasourceCache) + if err != nil { + return fmt.Errorf("failed to save datasource cache: %v", err) + } + + sqlWorkbenchService.log.Infof("Successfully created datasource %s (ID: %d)", dbService.Name, createResp.Data.ID) + return nil +} + +// updateDatasourceInSqlWorkbench 在SqlWorkbench中更新数据源 +func (sqlWorkbenchService *SqlWorkbenchService) updateDatasourceInSqlWorkbench(ctx context.Context, dbService *biz.DBService, existingDatasource *biz.SqlWorkbenchDatasource, publicKey, userCookie string, organizationID, environmentID int64) error { + // 构建更新数据源请求 + updateReq, err := sqlWorkbenchService.buildUpdateDatasourceRequest(ctx, dbService, environmentID) + if err != nil { + return fmt.Errorf("failed to build update datasource request: %v", err) + } + + // 调用更新接口 + _, err = sqlWorkbenchService.client.UpdateDatasource(existingDatasource.SqlWorkbenchDatasourceID, updateReq, publicKey, userCookie, organizationID) + if err != nil { + return fmt.Errorf("failed to update datasource: %v", err) + } + + // 更新缓存中的指纹 + updatedDatasourceCache := &biz.SqlWorkbenchDatasource{ + DMSDBServiceID: dbService.UID, + DMSUserID: existingDatasource.DMSUserID, + DMSDBServiceFingerprint: sqlWorkbenchService.dbServiceUsecase.GetDBServiceFingerprint(dbService), + SqlWorkbenchDatasourceID: existingDatasource.SqlWorkbenchDatasourceID, + Purpose: dbService.AccountPurpose, + } + + err = sqlWorkbenchService.sqlWorkbenchDatasourceRepo.SaveSqlWorkbenchDatasourceCache(ctx, updatedDatasourceCache) + if err != nil { + return fmt.Errorf("failed to update datasource cache: %v", err) + } + + sqlWorkbenchService.log.Infof("Successfully updated datasource %s (ID: %d)", dbService.Name, existingDatasource.SqlWorkbenchDatasourceID) + return nil +} + +// cleanupObsoleteDatasources 清理过时的数据源 +func (sqlWorkbenchService *SqlWorkbenchService) cleanupObsoleteDatasources(ctx context.Context, currentDBServices []*biz.DBService, existingDatasourceMap map[string]*biz.SqlWorkbenchDatasource, userCookie string, organizationID int64) error { + currentKeys := make(map[string]bool) + for _, dbService := range currentDBServices { + key := sqlWorkbenchService.getDatasourceKey(dbService.UID, dbService.AccountPurpose) + currentKeys[key] = true + } + + for key, existingDatasource := range existingDatasourceMap { + if !currentKeys[key] { + // 删除数据源 + _, err := sqlWorkbenchService.client.DeleteDatasource(existingDatasource.SqlWorkbenchDatasourceID, userCookie, organizationID) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to delete datasource %d: %v", existingDatasource.SqlWorkbenchDatasourceID, err) + continue + } + + // 删除缓存 + err = sqlWorkbenchService.sqlWorkbenchDatasourceRepo.DeleteSqlWorkbenchDatasourceCache(ctx, existingDatasource.DMSDBServiceID, existingDatasource.DMSUserID, existingDatasource.Purpose) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to delete datasource cache: %v", err) + } + + sqlWorkbenchService.log.Infof("Successfully deleted obsolete datasource %d", existingDatasource.SqlWorkbenchDatasourceID) + } + } + + return nil +} + +// getProjectName 获取项目名称 +func (sqlWorkbenchService *SqlWorkbenchService) getProjectName(ctx context.Context, projectUID string) (string, error) { + project, err := sqlWorkbenchService.projectUsecase.GetProject(ctx, projectUID) + if err != nil { + return "", fmt.Errorf("failed to get project: %v", err) + } + return project.Name, nil +} + +// buildDatasourceName 构建数据源名称,格式为项目名:数据源名 +func (sqlWorkbenchService *SqlWorkbenchService) buildDatasourceName(ctx context.Context, dbService *biz.DBService) (string, error) { + projectName, err := sqlWorkbenchService.getProjectName(ctx, dbService.ProjectUID) + if err != nil { + return "", fmt.Errorf("failed to get project name: %v", err) + } + return fmt.Sprintf("%s:%s", projectName, dbService.Name), nil +} + +// datasourceBaseInfo 数据源基础信息 +type datasourceBaseInfo struct { + Name string + Type string + Username string + Password string + Host string + Port string + ServiceName *string + EnvironmentID int64 +} + +// buildDatasourceBaseInfo 构建数据源基础信息 +func (sqlWorkbenchService *SqlWorkbenchService) buildDatasourceBaseInfo(ctx context.Context, dbService *biz.DBService, environmentID int64) (*datasourceBaseInfo, error) { + datasourceName, err := sqlWorkbenchService.buildDatasourceName(ctx, dbService) + if err != nil { + return nil, err + } + + baseInfo := &datasourceBaseInfo{ + Name: datasourceName, + Type: sqlWorkbenchService.convertDBType(dbService.DBType), + Username: dbService.User, + Password: dbService.Password, + Host: dbService.Host, + Port: dbService.Port, + EnvironmentID: environmentID, + } + + // Oracle 特殊处理 + if dbService.DBType == "Oracle" { + serviceName := dbService.AdditionalParams.GetParam("service_name").Value + baseInfo.ServiceName = &serviceName + } + + return baseInfo, nil +} + +// buildCreateDatasourceRequest 构建创建数据源请求 +func (sqlWorkbenchService *SqlWorkbenchService) buildCreateDatasourceRequest(ctx context.Context, dbService *biz.DBService, sqlWorkbenchUser *biz.SqlWorkbenchUser, environmentID int64) (client.CreateDatasourceRequest, error) { + baseInfo, err := sqlWorkbenchService.buildDatasourceBaseInfo(ctx, dbService, environmentID) + if err != nil { + return client.CreateDatasourceRequest{}, err + } + + return client.CreateDatasourceRequest{ + CreatorID: sqlWorkbenchUser.SqlWorkbenchUserId, + Type: baseInfo.Type, + Name: baseInfo.Name, + Username: baseInfo.Username, + Password: baseInfo.Password, + Host: baseInfo.Host, + Port: baseInfo.Port, + ServiceName: baseInfo.ServiceName, + SSLConfig: client.SSLConfig{Enabled: false}, + EnvironmentID: baseInfo.EnvironmentID, + }, nil +} + +// buildUpdateDatasourceRequest 构建更新数据源请求 +func (sqlWorkbenchService *SqlWorkbenchService) buildUpdateDatasourceRequest(ctx context.Context, dbService *biz.DBService, environmentID int64) (client.UpdateDatasourceRequest, error) { + baseInfo, err := sqlWorkbenchService.buildDatasourceBaseInfo(ctx, dbService, environmentID) + if err != nil { + return client.UpdateDatasourceRequest{}, err + } + + return client.UpdateDatasourceRequest{ + Type: baseInfo.Type, + Name: &baseInfo.Name, + Username: baseInfo.Username, + Password: &baseInfo.Password, + Host: baseInfo.Host, + Port: baseInfo.Port, + ServiceName: baseInfo.ServiceName, + SSLConfig: client.SSLConfig{Enabled: false}, + EnvironmentID: baseInfo.EnvironmentID, + }, nil +} + +// convertDBType 转换数据库类型 +func (sqlWorkbenchService *SqlWorkbenchService) convertDBType(dmsDBType string) string { + // 这里需要根据实际的数据库类型映射关系进行转换 + // ODC目前支持的数据源有: OB_MYSQL, OB_ORACLE, ORACLE, MYSQL, ODP_SHARDING_OB_MYSQL, DORIS, POSTGRESQL + // 其余调用创建数据源接口会直接失败 + switch dmsDBType { + case "MySQL": + return "MYSQL" + case "PostgreSQL": + return "POSTGRESQL" + case "Oracle": + return "ORACLE" + case "SQL Server": + return "SQL_SERVER" + case "OceanBase For Oracle": + return "OB_ORACLE" + case "OceanBase For MySQL": + return "OB_MYSQL" + default: + return dmsDBType + } +} + +func (sqlWorkbenchService *SqlWorkbenchService) SupportDBType(dbType pkgConst.DBType) bool { + return dbType == pkgConst.DBTypeMySQL || dbType == pkgConst.DBTypeOracle || dbType == pkgConst.DBTypeOceanBaseMySQL +} + +// buildDatabaseUser 当是ob-mysql时需要给账号管理的账号附加租户名集群名等字符: root@oms_mysql#oms_resource_4250 +func buildDatabaseUser(account string, dbServiceUser string, dbType string) string { + if dbType == string(pkgConst.DBTypeOceanBaseMySQL) { + index := strings.Index(dbServiceUser, "@") + if index == -1 { + return account + } + return account + dbServiceUser[index:] + } + return account +} + +func ListAuthDbAccount(ctx context.Context, baseURL, projectUid, userId string) ([]*TempDBAccount, error) { + // Generate token + token, err := generateAuthToken(userId) + if err != nil { + return nil, fmt.Errorf("failed to generate auth token for user %s: %w", userId, err) + } + + // Prepare request headers + header := map[string]string{ + "Authorization": fmt.Sprintf("Bearer %s", token), + } + + // Build request URL + u, err := url.Parse(baseURL) + if err != nil { + return nil, fmt.Errorf("invalid base URL: %w", err) + } + + // Set the path for the endpoint + u.Path = fmt.Sprintf("/provision/v1/auth/projects/%s/db_accounts", projectUid) + + // Add query parameters + query := u.Query() + query.Set("page_size", "999") + query.Set("page_index", "1") + query.Set("filter_by_password_managed", "true") + query.Set("filter_by_status", "unlock") + query.Set("filter_by_users", userId) + u.RawQuery = query.Encode() + requestURL := u.String() + + // Execute request + reply := &ListDBAccountReply{} + if err := makeHttpRequest(ctx, requestURL, header, reply); err != nil { + return nil, err + } + + // Validate response + if reply.Code != 0 { + return nil, fmt.Errorf("unexpected HTTP reply code (%v): %v", reply.Code, reply.Message) + } + + return reply.Data, nil +} + +// Helper function: Generate JWT token +func generateAuthToken(userId string) (string, error) { + token, err := jwt.GenJwtToken(jwt.WithUserId(userId)) + if err != nil { + return "", fmt.Errorf("failed to generate JWT token: %w", err) + } + return token, nil +} + +// Helper function: Make HTTP GET request +func makeHttpRequest(ctx context.Context, url string, headers map[string]string, reply interface{}) error { + err := pkgHttp.Get(ctx, url, headers, nil, reply) + if err != nil { + return fmt.Errorf("HTTP request to %s failed: %w", url, err) + } + return nil +} + +// AuditMiddleware 拦截工作台odc请求进行加工 +func (sqlWorkbenchService *SqlWorkbenchService) AuditMiddleware() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + // 只拦截包含 /streamExecute 的请求 + if !strings.Contains(c.Request().URL.Path, "/streamExecute") { + return next(c) + } + + // 读取请求体 + bodyBytes, err := io.ReadAll(c.Request().Body) + if err != nil { + sqlWorkbenchService.log.Errorf("failed to read request body: %v", err) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditReadReqBodyErr)) + } + // 恢复请求体,供后续处理使用 + c.Request().Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + + // 解析请求体获取 SQL 和 datasource ID + sql, datasourceID, err := sqlWorkbenchService.parseStreamExecuteRequest(bodyBytes) + if err != nil { + sqlWorkbenchService.log.Errorf("failed to parse streamExecute request, skipping audit: %v", err) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditParseReqErr)) + } + + if sql == "" || datasourceID == "" { + sqlWorkbenchService.log.Debugf("SQL or datasource ID is empty, skipping audit") + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditMissingSQLOrDatasourceErr)) + } + + // 获取当前用户 ID + dmsUserId, err := sqlWorkbenchService.getDMSUserIdFromRequest(c) + if err != nil { + sqlWorkbenchService.log.Errorf("failed to get DMS user ID: %v", err) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditGetDMSUserErr)) + } + + // 从缓存表获取 dms_db_service_id + dmsDBServiceID, err := sqlWorkbenchService.getDMSDBServiceIDFromCache(c.Request().Context(), datasourceID, dmsUserId) + if err != nil { + sqlWorkbenchService.log.Errorf("failed to get dms_db_service_id from cache: %v", err) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditGetDBServiceMappingErr)) + } + + if dmsDBServiceID == "" { + sqlWorkbenchService.log.Debugf("dms_db_service_id not found in cache for datasource: %s", datasourceID) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditDBServiceMappingNotFoundErr)) + } + + // 获取 DBService 信息 + dbService, err := sqlWorkbenchService.dbServiceUsecase.GetDBService(c.Request().Context(), dmsDBServiceID) + if err != nil { + sqlWorkbenchService.log.Errorf("failed to get DBService: %v", err) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditGetDBServiceErr)) + } + + // 检查是否启用 SQL 审核 + if !sqlWorkbenchService.isEnableSQLAudit(dbService) { + sqlWorkbenchService.log.Debugf("SQL audit is not enabled for DBService: %s", dmsDBServiceID) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditNotEnabledErr)) + } + + // 调用 SQLE 审核接口 + auditResult, err := sqlWorkbenchService.callSQLEAudit(c.Request().Context(), sql, dbService) + if err != nil { + sqlWorkbenchService.log.Errorf("call SQLE audit failed: %v", err) + return errors.New(locale.Bundle.LocalizeMsgByCtx(c.Request().Context(), locale.SqlWorkbenchAuditCallSQLEErr)) + } + + // 拦截响应并添加审核结果 + return sqlWorkbenchService.interceptAndAddAuditResult(c, next, dmsUserId, auditResult, dbService) + } + } +} + +// parseStreamExecuteRequest 解析 streamExecute 请求体,提取 SQL 和 datasource ID +func (sqlWorkbenchService *SqlWorkbenchService) parseStreamExecuteRequest(bodyBytes []byte) (sql string, datasourceID string, err error) { + var requestBody map[string]interface{} + if err := json.Unmarshal(bodyBytes, &requestBody); err != nil { + return "", "", fmt.Errorf("failed to unmarshal request body: %v", err) + } + + // 从 sql 字段获取 SQL + if sqlVal, ok := requestBody["sql"]; ok { + if sqlStr, ok := sqlVal.(string); ok { + sql = sqlStr + } + } + + // 从 sid 字段解析 datasource ID + // sid 格式: sid:{base64编码的JSON}:d:dms + // base64 JSON 包含: {"dbId":623,"dsId":28,"from":"192.168.21.47","logicalSession":false,"realId":"ee9b8ab276"} + if sidVal, ok := requestBody["sid"]; ok { + if sidStr, ok := sidVal.(string); ok { + dsId, parseErr := sqlWorkbenchService.parseSidToDatasourceID(sidStr) + if parseErr != nil { + sqlWorkbenchService.log.Debugf("Failed to parse sid to datasource ID: %v", parseErr) + } else { + datasourceID = dsId + } + } + } + + return sql, datasourceID, nil +} + +// parseSidToDatasourceID 从 sid 字符串中解析出 datasource ID +// sid 格式: sid:{base64编码的JSON}:d:dms +func (sqlWorkbenchService *SqlWorkbenchService) parseSidToDatasourceID(sid string) (string, error) { + // 检查 sid 格式: sid:...:d:dms + if !strings.HasPrefix(sid, "sid:") { + return "", fmt.Errorf("invalid sid format, missing 'sid:' prefix") + } + + // 移除 "sid:" 前缀 + sid = strings.TrimPrefix(sid, "sid:") + + // 查找最后一个 ":d" 后缀并移除从 ":d" 开始的所有字符 + if idx := strings.LastIndex(sid, ":d"); idx != -1 { + sid = sid[:idx] + } + + // 解码 base64 + decodedBytes, err := base64.StdEncoding.DecodeString(sid) + if err != nil { + return "", fmt.Errorf("failed to decode base64 sid: %v", err) + } + + // 解析 JSON + var sidData struct { + DbId int `json:"dbId"` + DsId int `json:"dsId"` + From string `json:"from"` + LogicalSession bool `json:"logicalSession"` + RealId string `json:"realId"` + } + + if err := json.Unmarshal(decodedBytes, &sidData); err != nil { + return "", fmt.Errorf("failed to unmarshal sid JSON: %v", err) + } + + // 返回 dsId 作为字符串 + return fmt.Sprintf("%d", sidData.DsId), nil +} + +// getDMSUserIdFromRequest 从请求中获取 DMS 用户 ID +func (sqlWorkbenchService *SqlWorkbenchService) getDMSUserIdFromRequest(c echo.Context) (string, error) { + var dmsToken string + for _, cookie := range c.Cookies() { + if cookie.Name == pkgConst.DMSToken { + dmsToken = cookie.Value + break + } + } + + if dmsToken == "" { + return "", fmt.Errorf("dms token is empty") + } + + dmsUserId, err := jwt.ParseUidFromJwtTokenStr(dmsToken) + if err != nil { + return "", fmt.Errorf("failed to parse dms user id from token: %v", err) + } + + return dmsUserId, nil +} + +// getDMSDBServiceIDFromCache 从 sql_workbench_datasource_caches 表获取 dms_db_service_id +func (sqlWorkbenchService *SqlWorkbenchService) getDMSDBServiceIDFromCache(ctx context.Context, datasourceID, dmsUserID string) (string, error) { + // 尝试将 datasourceID 转换为 int64(ODC 的 datasource ID 通常是数字) + var sqlWorkbenchDatasourceID int64 + if _, err := fmt.Sscanf(datasourceID, "%d", &sqlWorkbenchDatasourceID); err != nil { + // 如果转换失败,尝试直接使用字符串作为 datasource ID + sqlWorkbenchService.log.Debugf("Failed to convert datasourceID to int64, trying to find by string: %s", datasourceID) + } + + // 从缓存表中查找,需要根据 sql_workbench_datasource_id 和 dms_user_id 查找 + // 由于缓存表可能没有直接存储 sql_workbench_datasource_id,我们需要通过其他方式查找 + // 这里先尝试通过用户 ID 获取所有数据源,然后匹配 + datasources, err := sqlWorkbenchService.sqlWorkbenchDatasourceRepo.GetSqlWorkbenchDatasourcesByUserID(ctx, dmsUserID) + if err != nil { + return "", fmt.Errorf("failed to get datasources by user id: %v", err) + } + + // 如果 datasourceID 是数字,尝试匹配 SqlWorkbenchDatasourceID + if sqlWorkbenchDatasourceID > 0 { + for _, ds := range datasources { + if ds.SqlWorkbenchDatasourceID == sqlWorkbenchDatasourceID { + return ds.DMSDBServiceID, nil + } + } + } + + // 如果找不到,返回第一个匹配的数据源(临时方案,后续可能需要更精确的匹配逻辑) + if len(datasources) > 0 { + // 这里可以根据实际业务逻辑选择合适的数据源 + // 暂时返回第一个数据源的 dms_db_service_id + return datasources[0].DMSDBServiceID, nil + } + + return "", fmt.Errorf("no datasource found for datasourceID: %s, userID: %s", datasourceID, dmsUserID) +} + +// isEnableSQLAudit 检查是否启用 SQL 审核 +func (sqlWorkbenchService *SqlWorkbenchService) isEnableSQLAudit(dbService *biz.DBService) bool { + if dbService.SQLEConfig == nil || dbService.SQLEConfig.SQLQueryConfig == nil { + return false + } + return dbService.SQLEConfig.AuditEnabled && dbService.SQLEConfig.SQLQueryConfig.AuditEnabled +} + +// callSQLEAudit 调用 SQLE 直接审核接口 +func (sqlWorkbenchService *SqlWorkbenchService) callSQLEAudit(ctx context.Context, sql string, dbService *biz.DBService) (*cloudbeaver.AuditSQLReply, error) { + // 获取 SQLE 服务地址 + target, err := sqlWorkbenchService.proxyTargetRepo.GetProxyTargetByName(ctx, _const.SqleComponentName) + if err != nil { + return nil, fmt.Errorf("failed to get SQLE proxy target: %v", err) + } + + sqleAddr := fmt.Sprintf("%s/v2/sql_audit", target.URL.String()) + + // 构建审核请求 + auditReq := cloudbeaver.AuditSQLReq{ + InstanceType: dbService.DBType, + SQLContent: sql, + SQLType: "sql", + ProjectId: dbService.ProjectUID, + InstanceName: dbService.Name, + RuleTemplateName: dbService.SQLEConfig.SQLQueryConfig.RuleTemplateName, + } + + // 设置请求头 + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + // 调用 SQLE 审核接口 + reply := &cloudbeaver.AuditSQLReply{} + if err := pkgHttp.POST(ctx, sqleAddr, header, auditReq, reply); err != nil { + return nil, fmt.Errorf("failed to call SQLE audit API: %v", err) + } + + if reply.Code != 0 { + return nil, fmt.Errorf("SQLE audit API returned error code %v: %v", reply.Code, reply.Message) + } + + return reply, nil +} + +// interceptAndAddAuditResult 拦截响应并添加审核结果 +func (sqlWorkbenchService *SqlWorkbenchService) interceptAndAddAuditResult(c echo.Context, next echo.HandlerFunc, userId string, auditResult *cloudbeaver.AuditSQLReply, dbService *biz.DBService) error { + // 判断是否需要审批 + allowQueryWhenLessThanAuditLevel := dbService.GetAllowQueryWhenLessThanAuditLevel() + needApproval := sqlWorkbenchService.shouldRequireApproval(auditResult.Data.SQLResults, allowQueryWhenLessThanAuditLevel) + + // 如果需要审批,直接返回审核结果,不请求真实的 streamExecute 接口 + if needApproval { + return sqlWorkbenchService.buildAuditResponseWithoutExecution(c, userId, auditResult, dbService) + } + + // 不需要审批,执行真实请求并添加审核结果 + return sqlWorkbenchService.executeAndAddAuditResult(c, next, auditResult, dbService) +} + +// buildAuditResponseWithoutExecution 构造审核响应,不执行真实的 SQL +func (sqlWorkbenchService *SqlWorkbenchService) buildAuditResponseWithoutExecution(c echo.Context, userId string, auditResult *cloudbeaver.AuditSQLReply, dbService *biz.DBService) error { + // 构造 SQL 条目列表 + sqlItems := make([]StreamExecuteSQLItem, 0, len(auditResult.Data.SQLResults)) + for _, sqlResult := range auditResult.Data.SQLResults { + // 转换审核结果为 violatedRules 格式 + violatedRules := sqlWorkbenchService.convertSQLEAuditToViolatedRules(&sqlResult) + + sqlItem := StreamExecuteSQLItem{ + SQLTuple: StreamExecuteSQLTuple{ + ExecutedSQL: sqlResult.ExecSQL, + Offset: int(sqlResult.Number), + OriginalSQL: sqlResult.ExecSQL, + SQLID: fmt.Sprintf("sqle-audit-%d", sqlResult.Number), + }, + ViolatedRules: violatedRules, + } + sqlItems = append(sqlItems, sqlItem) + } + + // 构造响应数据 + responseData := StreamExecuteData{ + ApprovalRequired: true, // 需要审批 + LogicalSQL: false, + RequestID: nil, + SQLs: sqlItems, + UnauthorizedDBResources: nil, + ViolatedRules: []interface{}{}, + } + + // 构造完整响应 + response := StreamExecuteResponse{ + Data: responseData, + DurationMillis: 0, + HTTPStatus: "OK", + RequestID: fmt.Sprintf("dms-audit-%d", time.Now().UnixNano()), + Server: "DMS", + Successful: true, + Timestamp: float64(time.Now().Unix()), + TraceID: c.Response().Header().Get("X-Trace-ID"), + } + + // 记录审核拦截的操作日志 + if err := sqlWorkbenchService.saveAuditBlockedLog(c, userId, auditResult, dbService); err != nil { + sqlWorkbenchService.log.Errorf("failed to save audit blocked log: %v", err) + // 日志记录失败不影响响应返回 + } + + // 返回 JSON 响应 + return c.JSON(http.StatusOK, response) +} + +// saveAuditBlockedLog 记录审核拦截的操作日志 +func (sqlWorkbenchService *SqlWorkbenchService) saveAuditBlockedLog(c echo.Context, userId string, auditResult *cloudbeaver.AuditSQLReply, dbService *biz.DBService) error { + ctx := context.Background() + + // 提取 session ID + sessionID := extractSessionID(c.Request().URL.Path) + + // 对每个被拦截的 SQL 记录日志 + for _, sqlResult := range auditResult.Data.SQLResults { + // 生成 UID + uid, err := pkgRand.GenStrUid() + if err != nil { + sqlWorkbenchService.log.Errorf("failed to generate UID: %v", err) + continue + } + + // 获取 SQL 内容 + sql := sqlResult.ExecSQL + + // 构建操作详情 + opDetail := i18nPkg.ConvertStr2I18nAsDefaultLang(sql) + + // 转换审核结果 + auditResults := sqlWorkbenchService.convertToAuditResults(&sqlResult) + + // 判断是否审核通过 + isAuditPass := false // 被拦截的 SQL 默认未通过审核 + + // 创建操作日志 - 标记为审核失败(被拦截) + now := time.Now() + cbOperationLog := biz.CbOperationLog{ + UID: uid, + OpPersonUID: userId, + OpTime: &now, + DBServiceUID: dbService.UID, + OpType: biz.CbOperationLogTypeSql, + I18nOpDetail: opDetail, + OpSessionID: &sessionID, + ProjectID: dbService.ProjectUID, + OpHost: c.RealIP(), + AuditResults: auditResults, + IsAuditPass: &isAuditPass, + ExecResult: "", + ExecTotalSec: 0, + ResultSetRowCount: 0, + } + + // 保存操作日志 + if err := sqlWorkbenchService.cbOperationLogUsecase.SaveCbOperationLog(ctx, &cbOperationLog); err != nil { + sqlWorkbenchService.log.Errorf("failed to save operation log: %v", err) + // 继续处理其他 SQL + } + } + + return nil +} + +// convertToAuditResults 将审核结果转换为 model.AuditResults 格式 +func (sqlWorkbenchService *SqlWorkbenchService) convertToAuditResults(sqlResult *cloudbeaver.AuditSQLResV2) dbmodel.AuditResults { + var auditResults dbmodel.AuditResults + for _, result := range sqlResult.AuditResult { + auditResult := dbmodel.AuditResult{ + Level: result.Level, + RuleName: "", // SQLE 返回的审核结果中没有 RuleName,如果需要可以从 Message 中提取 + ExecutionFailed: result.ExecutionFailed, + I18nAuditResultInfo: dbmodel.I18nAuditResultInfo{ + language.Chinese: dbmodel.AuditResultInfo{ + Message: result.Message, + ErrorInfo: "", + }, + }, + } + auditResults = append(auditResults, auditResult) + } + return auditResults +} + +// extractSessionID 从路径中提取 session ID +func extractSessionID(path string) string { + // 匹配类似: /api/v2/datasource/sessions/sid:{sessionId}/sqls/getMoreResults + parts := strings.Split(path, "/") + for i, part := range parts { + if strings.HasPrefix(part, "sid:") { + return part + } + if i < len(parts)-1 && part == "sessions" && strings.HasPrefix(parts[i+1], "sid:") { + return parts[i+1] + } + } + return "" +} + +// executeAndAddAuditResult 执行真实请求并添加审核结果 +func (sqlWorkbenchService *SqlWorkbenchService) executeAndAddAuditResult(c echo.Context, next echo.HandlerFunc, auditResult *cloudbeaver.AuditSQLReply, dbService *biz.DBService) error { + // 创建响应拦截器 + srw := newStreamExecuteResponseWriter(c) + cloudbeaverResBuf := srw.Buffer + c.Response().Writer = srw + + defer func() { + // 在 defer 中处理响应 + if srw.status != 0 { + srw.original.WriteHeader(srw.status) + } + + // 读取响应内容 + responseBytes := cloudbeaverResBuf.Bytes() + if len(responseBytes) == 0 { + return + } + + // 如果是 gzip 压缩响应,先解压 + responseBytes, wasGzip, err := sqlWorkbenchService.decodeResponseBody(cloudbeaverResBuf.Bytes(), srw.Header().Get("Content-Encoding")) + if err != nil { + sqlWorkbenchService.log.Debugf("Failed to decode response body, returning original response: %v", err) + srw.original.Write(cloudbeaverResBuf.Bytes()) + return + } + + // 如果解压过,先移除 Content-Encoding,后续根据需要重新设置 + if wasGzip { + srw.original.Header().Del("Content-Encoding") + } + + // 解析响应 JSON + var responseBody StreamExecuteResponse + if err := json.Unmarshal(responseBytes, &responseBody); err != nil { + sqlWorkbenchService.log.Debugf("Failed to unmarshal response, returning original response: %v", err) + // 如果解析失败,直接返回原始响应 + srw.original.Write(cloudbeaverResBuf.Bytes()) + return + } + + // 添加审核结果到响应的 data 字段中 + if auditResult != nil && auditResult.Data != nil && auditResult.Data.PassRate != 1 { + // 将 SQLE 审核结果整合到每个 SQL 条目中 + sqlWorkbenchService.mergeSQLEAuditResults(&responseBody.Data, auditResult.Data, dbService) + } + + // 重新序列化响应 + modifiedResponse, err := json.Marshal(responseBody) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to marshal modified response: %v", err) + srw.original.Write(cloudbeaverResBuf.Bytes()) + return + } + + finalResponse := modifiedResponse + if wasGzip { + encoded, err := sqlWorkbenchService.encodeResponseBody(modifiedResponse) + if err != nil { + sqlWorkbenchService.log.Errorf("Failed to re-encode gzip response: %v", err) + srw.original.Write(cloudbeaverResBuf.Bytes()) + return + } + finalResponse = encoded + srw.original.Header().Set("Content-Encoding", "gzip") + } + + // 更新 Content-Length + header := srw.original.Header() + header.Set("Content-Length", fmt.Sprintf("%d", len(finalResponse))) + + // 如果拦截过程中未显式写入状态码,默认使用 200 + statusCode := srw.status + if statusCode == 0 { + statusCode = http.StatusOK + } + srw.original.WriteHeader(statusCode) + + // 写入修改后的响应 + if _, err := srw.original.Write(finalResponse); err != nil { + sqlWorkbenchService.log.Errorf("Failed to write modified response: %v", err) + } + }() + + // 执行下一个处理器 + return next(c) +} + +// decodeResponseBody 根据 Content-Encoding 判断是否需要解压 +func (sqlWorkbenchService *SqlWorkbenchService) decodeResponseBody(body []byte, contentEncoding string) ([]byte, bool, error) { + if len(body) == 0 { + return body, false, nil + } + isGzip := utils.IsGzip(body) + if !isGzip { + return body, false, nil + } + gzipBytes, err := utils.DecodeGzipBytes(body) + if err != nil { + return nil, true, fmt.Errorf("Gzip decode error: %v", err) + } + return gzipBytes, true, nil +} + +// encodeResponseBody 将响应体按照 gzip 编码 +func (sqlWorkbenchService *SqlWorkbenchService) encodeResponseBody(body []byte) ([]byte, error) { + var buf bytes.Buffer + gzipWriter := gzip.NewWriter(&buf) + if _, err := gzipWriter.Write(body); err != nil { + gzipWriter.Close() + return nil, fmt.Errorf("failed to gzip response body: %w", err) + } + if err := gzipWriter.Close(); err != nil { + return nil, fmt.Errorf("failed to finalize gzip response body: %w", err) + } + return buf.Bytes(), nil +} + +// mergeSQLEAuditResults 将 SQLE 审核结果整合到 sqls 数组中 +func (sqlWorkbenchService *SqlWorkbenchService) mergeSQLEAuditResults(data *StreamExecuteData, auditData *cloudbeaver.AuditResDataV2, dbService *biz.DBService) { + // 创建 SQL 到审核结果的映射 + sqlAuditMap := make(map[string]*cloudbeaver.AuditSQLResV2) + for i := range auditData.SQLResults { + sqlResult := &auditData.SQLResults[i] + // 使用 exec_sql 作为 key,去除首尾空格和分号 + normalizedSQL := strings.TrimSpace(strings.TrimSuffix(sqlResult.ExecSQL, ";")) + sqlAuditMap[normalizedSQL] = sqlResult + } + + // 设置 ApprovalRequired 为 false,表示已通过审核可以执行 + // 注意:如果需要审批,在 interceptAndAddAuditResult 中已经拦截,不会执行到这里 + data.ApprovalRequired = false + + // 遍历 sqls 数组,为每个 SQL 条目添加 SQLE 审核结果 + for i := range data.SQLs { + sqlItem := &data.SQLs[i] + + // 尝试从 originalSql 或 executedSql 匹配审核结果 + var matchedAuditResult *cloudbeaver.AuditSQLResV2 + normalizedSQL := strings.TrimSpace(strings.TrimSuffix(sqlItem.SQLTuple.OriginalSQL, ";")) + if auditResult, found := sqlAuditMap[normalizedSQL]; found { + matchedAuditResult = auditResult + } + + if matchedAuditResult == nil { + normalizedSQL = strings.TrimSpace(strings.TrimSuffix(sqlItem.SQLTuple.ExecutedSQL, ";")) + if auditResult, found := sqlAuditMap[normalizedSQL]; found { + matchedAuditResult = auditResult + } + } + + // 如果找到匹配的审核结果,将其转换为 violatedRules 格式并添加 + if matchedAuditResult != nil { + sqleViolatedRules := sqlWorkbenchService.convertSQLEAuditToViolatedRules(matchedAuditResult) + if len(sqleViolatedRules) > 0 { + sqlItem.ViolatedRules = sqleViolatedRules + } + } + } +} + +// shouldRequireApproval 根据审核放行等级判断是否需要审批 +func (sqlWorkbenchService *SqlWorkbenchService) shouldRequireApproval(sqlResults []cloudbeaver.AuditSQLResV2, allowQueryWhenLessThanAuditLevel string) bool { + // 如果没有设置审核放行等级,那么直接放行 + if allowQueryWhenLessThanAuditLevel == "" { + return false + } + + // 遍历所有 SQL 审核结果 + for _, sqlResult := range sqlResults { + // 检查是否有执行失败的审核项 + for _, auditItem := range sqlResult.AuditResult { + if auditItem.ExecutionFailed { + return true + } + } + + // 比较审核等级:如果 SQL 的审核等级大于允许的等级,则需要审批 + // 使用 RuleLevel 的 LessOrEqual 方法进行比较 + sqlAuditLevel := dbmodel.RuleLevel(sqlResult.AuditLevel) + allowedLevel := dbmodel.RuleLevel(allowQueryWhenLessThanAuditLevel) + + // 如果 SQL 的审核等级大于允许的等级(即 !LessOrEqual),则需要审批 + if !sqlAuditLevel.LessOrEqual(allowedLevel) { + return true + } + } + + // 所有 SQL 的审核等级都小于等于允许的等级,不需要审批 + return false +} + +// convertSQLEAuditToViolatedRules 将 SQLE 审核结果转换为 violatedRules 格式 +func (sqlWorkbenchService *SqlWorkbenchService) convertSQLEAuditToViolatedRules(auditResult *cloudbeaver.AuditSQLResV2) []StreamExecuteRule { + var violatedRules []StreamExecuteRule + + // 将 SQLE 的 audit_result 转换为 violatedRules 格式 + for _, auditItem := range auditResult.AuditResult { + // 映射 level 字符串到数字 + levelNum := sqlWorkbenchService.mapAuditLevelToNumber(auditItem.Level) + + violatedRule := StreamExecuteRule{ + AppliedDialectTypes: nil, + CreateTime: nil, + Enabled: nil, + ID: nil, + Level: levelNum, + Metadata: nil, + OrganizationID: nil, + Properties: nil, + RulesetID: nil, + UpdateTime: nil, + Violation: StreamExecuteViolation{ + Level: levelNum, + LocalizedMessage: auditItem.Message, + Offset: 0, // SQLE 审核结果可能没有 offset 信息 + Start: 0, + Stop: 0, + Text: auditResult.ExecSQL, + }, + } + violatedRules = append(violatedRules, violatedRule) + } + + return violatedRules +} + +// mapAuditLevelToNumber 将审核级别字符串映射到数字 +// normal=0, notice=3, warn=1, error=2 +func (sqlWorkbenchService *SqlWorkbenchService) mapAuditLevelToNumber(level string) int { + switch strings.ToLower(level) { + case "normal": + return 0 + case "notice": + return 3 + case "warn": + return 1 + case "error": + return 2 + default: + return 0 // 默认为 normal + } +} + +// StreamExecuteResponse streamExecute 接口响应结构 +type StreamExecuteResponse struct { + Data StreamExecuteData `json:"data"` + DurationMillis int64 `json:"durationMillis"` + HTTPStatus string `json:"httpStatus"` + RequestID string `json:"requestId"` + Server string `json:"server"` + Successful bool `json:"successful"` + Timestamp float64 `json:"timestamp"` + TraceID string `json:"traceId"` +} + +// StreamExecuteData streamExecute 响应中的 data 字段 +type StreamExecuteData struct { + ApprovalRequired bool `json:"approvalRequired"` + LogicalSQL bool `json:"logicalSql"` + RequestID *string `json:"requestId"` + SQLs []StreamExecuteSQLItem `json:"sqls"` + UnauthorizedDBResources interface{} `json:"unauthorizedDBResources"` + ViolatedRules []interface{} `json:"violatedRules"` +} + +// StreamExecuteSQLItem SQL 条目 +type StreamExecuteSQLItem struct { + SQLTuple StreamExecuteSQLTuple `json:"sqlTuple"` + ViolatedRules []StreamExecuteRule `json:"violatedRules"` +} + +// StreamExecuteSQLTuple SQL 元组 +type StreamExecuteSQLTuple struct { + ExecutedSQL string `json:"executedSql"` + Offset int `json:"offset"` + OriginalSQL string `json:"originalSql"` + SQLID string `json:"sqlId"` +} + +// StreamExecuteRule 违反的规则 +type StreamExecuteRule struct { + AppliedDialectTypes interface{} `json:"appliedDialectTypes"` + CreateTime interface{} `json:"createTime"` + Enabled interface{} `json:"enabled"` + ID interface{} `json:"id"` + Level int `json:"level"` + Metadata interface{} `json:"metadata"` + OrganizationID interface{} `json:"organizationId"` + Properties interface{} `json:"properties"` + RulesetID interface{} `json:"rulesetId"` + UpdateTime interface{} `json:"updateTime"` + Violation StreamExecuteViolation `json:"violation"` +} + +// StreamExecuteViolation 违反详情 +type StreamExecuteViolation struct { + Level int `json:"level"` + LocalizedMessage string `json:"localizedMessage"` + Offset int `json:"offset"` + Start int `json:"start"` + Stop int `json:"stop"` + Text string `json:"text"` +} + +// SQLEAuditResultSummary SQLE 审核结果汇总 +type SQLEAuditResultSummary struct { + AuditLevel string `json:"audit_level"` + Score int32 `json:"score"` + PassRate float64 `json:"pass_rate"` +} + +// streamExecuteResponseWriter 响应拦截器,用于捕获响应内容 +type streamExecuteResponseWriter struct { + echo.Response + Buffer *bytes.Buffer + original http.ResponseWriter + status int +} + +func newStreamExecuteResponseWriter(c echo.Context) *streamExecuteResponseWriter { + buf := new(bytes.Buffer) + return &streamExecuteResponseWriter{ + Response: *c.Response(), + Buffer: buf, + original: c.Response().Writer, + } +} + +func (w *streamExecuteResponseWriter) Write(b []byte) (int, error) { + // 如果未设置状态码,则补默认值 + if w.status == 0 { + w.WriteHeader(http.StatusOK) + } + // 写入 buffer,不立即写给客户端 + return w.Buffer.Write(b) +} + +func (w *streamExecuteResponseWriter) WriteHeader(code int) { + w.status = code +} + + diff --git a/internal/sql_workbench/service/sql_workbench_service_ce.go b/internal/sql_workbench/service/sql_workbench_service_ce.go new file mode 100644 index 000000000..cc8a7f969 --- /dev/null +++ b/internal/sql_workbench/service/sql_workbench_service_ce.go @@ -0,0 +1,12 @@ +//go:build !enterprise + +package sql_workbench + +import ( + "context" + "github.com/actiontech/dms/internal/dms/biz" +) + +func (sqlWorkbenchService *SqlWorkbenchService) ResetDbServiceByAuth(ctx context.Context, activeDBServices []*biz.DBService, userId string) ([]*biz.DBService, error) { + return activeDBServices, nil +} diff --git a/pkg/dms-common/README.md b/pkg/dms-common/README.md index 8ee0cfa0c..96a20da41 100644 --- a/pkg/dms-common/README.md +++ b/pkg/dms-common/README.md @@ -4,4 +4,5 @@ 2. 反向代理接口:./api/dms/v1/proxy.go 3. 用户查询接口:./api/dms/v1/user.go 4. 用户查询工具:./dmsobject/user.go -5. 校验插件&反向代理注册工具:./register/register.go \ No newline at end of file +5. 校验插件&反向代理注册工具:./register/register.go +6. 事前权限校验涉及的数据结构,背景见 https://github.com/actiontech/dms-ee/issues/125:./sql_op \ No newline at end of file diff --git a/pkg/dms-common/api/accesstoken/access_token.go b/pkg/dms-common/api/accesstoken/access_token.go new file mode 100644 index 000000000..a9940e5f2 --- /dev/null +++ b/pkg/dms-common/api/accesstoken/access_token.go @@ -0,0 +1,52 @@ +package accesstoken + +import ( + "context" + "fmt" + "net/http" + + jwtPkg "github.com/actiontech/dms/pkg/dms-common/api/jwt" + "github.com/actiontech/dms/pkg/dms-common/dmsobject" + "github.com/labstack/echo/v4" +) + +const AccessTokenLogin = "access_token_login" + +func CheckLatestAccessToken(dmsAddress string, getTokenDetail func(c jwtPkg.EchoContextGetter) (*jwtPkg.TokenDetail, error)) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + tokenDetail, err := getTokenDetail(c) + + if err != nil { + echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("get token detail failed, err:%v", err)) + return err + } + + if tokenDetail.TokenStr == "" { + return next(c) + } + + // LoginType为空,不需要校验access token + if tokenDetail.LoginType == "" { + return next(c) + } + + if tokenDetail.LoginType != AccessTokenLogin { + return echo.NewHTTPError(http.StatusUnauthorized, "access token login type is error") + } + + userInfo, err := dmsobject.GetUser(context.TODO(), tokenDetail.UID, dmsAddress) + if err != nil { + return err + } + if userInfo == nil { + return echo.NewHTTPError(http.StatusNotFound, "access token: cannot get user info") + } + + if userInfo.AccessTokenInfo.AccessToken != tokenDetail.TokenStr { + return echo.NewHTTPError(http.StatusUnauthorized, "access token is not latest") + } + return next(c) + } + } +} diff --git a/pkg/dms-common/api/base/v1/base.go b/pkg/dms-common/api/base/v1/base.go index dc1fbd33e..5ac09000f 100644 --- a/pkg/dms-common/api/base/v1/base.go +++ b/pkg/dms-common/api/base/v1/base.go @@ -6,7 +6,7 @@ type GenericResp struct { // code Code int `json:"code"` // message - Msg string `json:"msg"` + Message string `json:"message"` } func (r *GenericResp) SetCode(code int) { @@ -14,7 +14,7 @@ func (r *GenericResp) SetCode(code int) { } func (r *GenericResp) SetMsg(msg string) { - r.Msg = msg + r.Message = msg } type GenericResper interface { diff --git a/pkg/dms-common/api/dms/v1/db_service.go b/pkg/dms-common/api/dms/v1/db_service.go new file mode 100644 index 000000000..e928b60e0 --- /dev/null +++ b/pkg/dms-common/api/dms/v1/db_service.go @@ -0,0 +1,225 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + "github.com/go-openapi/strfmt" +) + +type CheckDbConnectable struct { + // DB Service type + // Required: true + // example: MySQL + DBType string `json:"db_type" example:"mysql" validate:"required"` + // DB Service admin user + // Required: true + // example: root + User string `json:"user" example:"root" valid:"required"` + // DB Service host + // Required: true + // example: 127.0.0.1 + Host string `json:"host" example:"10.10.10.10" valid:"required,ip_addr|uri|hostname|hostname_rfc1123"` + // DB Service port + // Required: true + // example: 3306 + Port string `json:"port" example:"3306" valid:"required,port"` + // DB Service admin password + // Required: true + // example: 123456 + Password string `json:"password" example:"123456"` + // DB Service Custom connection parameters + // Required: false + AdditionalParams []*AdditionalParam `json:"additional_params" from:"additional_params"` +} + +type AdditionalParam struct { + Name string `json:"name"` + Value string `json:"value"` + Description string `json:"description" example:"参数项中文名" form:"description"` + Type string `json:"type" example:"int" form:"type"` +} + +// swagger:parameters ListDBServices +type ListDBServiceReq struct { + // the maximum count of db service to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of users to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy DBServiceOrderByField `query:"order_by" json:"order_by"` + // the db service business name + // in:query + FilterByBusiness string `query:"filter_by_business" json:"filter_by_business"` + // the db service connection + // enum: ["connect_success","connect_failed"] + // in:query + FilterLastConnectionTestStatus *string `query:"filter_last_connection_test_status" json:"filter_last_connection_test_status" validate:"omitempty,oneof=connect_success connect_failed"` + // the db service host + // in:query + FilterByHost string `query:"filter_by_host" json:"filter_by_host"` + // the db service uid + // in:query + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` + // the db service name + // in:query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // the db service port + // in:query + FilterByPort string `query:"filter_by_port" json:"filter_by_port"` + // the db service db type + // in:query + FilterByDBType string `query:"filter_by_db_type" json:"filter_by_db_type"` + // project id + // in:path + ProjectUid string `param:"project_uid" json:"project_uid"` + // filter db services by db service id list using in condition + // in:query + FilterByDBServiceIds []string `query:"filter_by_db_service_ids" json:"filter_by_db_service_ids"` + // the db service fuzzy keyword,include host/port + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` + // is masking + // in:query + IsEnableMasking *bool `query:"is_enable_masking" json:"is_enable_masking"` +} + +// swagger:enum DBServiceOrderByField +type DBServiceOrderByField string + +const ( + DBServiceOrderByName DBServiceOrderByField = "name" +) + +type MaintenanceTime struct { + MaintenanceStartTime *Time `json:"maintenance_start_time"` + MaintenanceStopTime *Time `json:"maintenance_stop_time"` +} + +type Time struct { + Hour int `json:"hour"` + Minute int `json:"minute"` +} + +type AuditPlanTypes struct { + AuditPlanId uint `json:"audit_plan_id"` + AuditPlanType string `json:"type"` + AuditPlanTypeDesc string `json:"desc"` +} + +// swagger:enum LastConnectionTestStatus +type LastConnectionTestStatus string + +const ( + LastConnectionTestStatusSuccess LastConnectionTestStatus = "connect_success" + LastConnectionTestStatusFailed LastConnectionTestStatus = "connect_failed" +) + +// A dms db Service +type ListDBService struct { + // db service uid + DBServiceUid string `json:"uid"` + // db service name + Name string `json:"name"` + // db service DB type + DBType string `json:"db_type"` + // db service host + Host string `json:"host"` + // db service port + Port string `json:"port"` + // db service admin user + User string `json:"user"` + // db service admin encrypted password + Password string `json:"password"` + // TODO This parameter is deprecated and will be removed soon. + // the db service business name + Business string `json:"business"` + // DB Service maintenance time + MaintenanceTimes []*MaintenanceTime `json:"maintenance_times"` + // DB desc + Desc string `json:"desc"` + // DB source + Source string `json:"source"` + // DB project uid + ProjectUID string `json:"project_uid"` + // sqle config + SQLEConfig *SQLEConfig `json:"sqle_config"` + // DB Service Custom connection parameters + AdditionalParams []*AdditionalParam `json:"additional_params"` + // is enable masking + IsEnableMasking bool `json:"is_enable_masking"` + // backup switch + EnableBackup bool `json:"enable_backup"` + // backup max rows + BackupMaxRows uint64 `json:"backup_max_rows"` + // audit plan types + AuditPlanTypes []*AuditPlanTypes `json:"audit_plan_types"` + // instance audit plan id + InstanceAuditPlanID uint `json:"instance_audit_plan_id,omitempty"` + // DB connection test time + LastConnectionTestTime strfmt.DateTime `json:"last_connection_test_time"` + // DB connect test status + LastConnectionTestStatus LastConnectionTestStatus `json:"last_connection_test_status"` + // DB connect test error message + LastConnectionTestErrorMessage string `json:"last_connection_test_error_message,omitempty"` +} + +// swagger:model +type EnvironmentTag struct { + UID string `json:"uid,omitempty"` + // 环境属性标签最多50个字符 + Name string `json:"name" validate:"max=50"` +} + +type SQLEConfig struct { + // DB Service audit enabled + AuditEnabled bool `json:"audit_enabled" example:"false"` + // DB Service rule template name + RuleTemplateName string `json:"rule_template_name"` + // DB Service rule template id + RuleTemplateID string `json:"rule_template_id"` + // DB Service data export rule template name + DataExportRuleTemplateName string `json:"data_export_rule_template_name"` + // DB Service data export rule template id + DataExportRuleTemplateID string `json:"data_export_rule_template_id"` + // DB Service SQL query config + SQLQueryConfig *SQLQueryConfig `json:"sql_query_config"` +} + +// swagger:enum SQLAllowQueryAuditLevel +type SQLAllowQueryAuditLevel string + +const ( + AuditLevelNormal SQLAllowQueryAuditLevel = "normal" + AuditLevelNotice SQLAllowQueryAuditLevel = "notice" + AuditLevelWarn SQLAllowQueryAuditLevel = "warn" + AuditLevelError SQLAllowQueryAuditLevel = "error" +) + +type SQLQueryConfig struct { + MaxPreQueryRows int `json:"max_pre_query_rows" example:"100"` + QueryTimeoutSecond int `json:"query_timeout_second" example:"10"` + AuditEnabled bool `json:"audit_enabled" example:"false"` + WorkflowExecEnabled bool `json:"workflow_exec_enabled" example:"false"` + AllowQueryWhenLessThanAuditLevel SQLAllowQueryAuditLevel `json:"allow_query_when_less_than_audit_level" enums:"normal,notice,warn,error" valid:"omitempty,oneof=normal notice warn error " example:"error"` + RuleTemplateName string `json:"rule_template_name"` + RuleTemplateID string `json:"rule_template_id"` + MaintenanceTimes []*MaintenanceTime `json:"maintenance_times"` // 允许执行非 DQL 的运维时间窗口,与数据源 maintenance_times 结构一致 +} + +// swagger:model ListDBServiceReply +type ListDBServiceReply struct { + // List db service reply + Data []*ListDBService `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +type DBServiceUidWithNameInfo struct { + DBServiceUid string + DBServiceName string +} diff --git a/pkg/dms-common/api/dms/v1/member.go b/pkg/dms-common/api/dms/v1/member.go index 19368d537..17173776a 100644 --- a/pkg/dms-common/api/dms/v1/member.go +++ b/pkg/dms-common/api/dms/v1/member.go @@ -11,9 +11,10 @@ type ListMembersForInternalReq struct { // the offset of members to be returned, default is 0 // in:query PageIndex uint32 `query:"page_index" json:"page_index"` - // the member namespace uid - // in:query - NamespaceUid string `query:"namespace_uid" json:"namespace_uid" validate:"required"` + // project id + // Required: true + // in:path + ProjectUid string `param:"project_uid" json:"project_uid" validate:"required"` } // swagger:enum MemberForInternalOrderByField @@ -25,11 +26,9 @@ const ( // A dms member for internal type ListMembersForInternalItem struct { - // member uid - MemberUid string `json:"uid"` // member user User UidWithName `json:"user"` - // is member namespace admin, admin has all permissions + // is member project admin, admin has all permissions IsAdmin bool `json:"is_admin"` // member op permissions MemberOpPermissionList []OpPermissionItem `json:"member_op_permission_list"` @@ -38,11 +37,39 @@ type ListMembersForInternalItem struct { // swagger:model ListMembersForInternalReply type ListMembersForInternalReply struct { // List member reply - Payload struct { - Members []*ListMembersForInternalItem `json:"members"` - Total int64 `json:"total"` - } `json:"payload"` + Data []*ListMembersForInternalItem `json:"data"` + Total int64 `json:"total_nums"` // Generic reply base.GenericResp } + +// swagger:model GetMemberGroupReply +type GetMemberGroupReply struct { + // List member reply + Data *GetMemberGroup `json:"data"` + + // Generic reply + base.GenericResp +} + +type GetMemberGroup struct { + Name string `json:"name"` + // member group uid + Uid string `json:"uid"` + // member user + Users []UidWithName `json:"users"` + // Whether the member has project admin permission + IsProjectAdmin bool `json:"is_project_admin"` + // member op permission + RoleWithOpRanges []ListMemberRoleWithOpRange `json:"role_with_op_ranges"` +} + +type ListMemberRoleWithOpRange struct { + // role uid + RoleUID UidWithName `json:"role_uid" validate:"required"` + // op permission range type, only support db service now + OpRangeType OpRangeType `json:"op_range_type" validate:"required"` + // op range uids + RangeUIDs []UidWithName `json:"range_uids" validate:"required"` +} diff --git a/pkg/dms-common/api/dms/v1/namespace.go b/pkg/dms-common/api/dms/v1/namespace.go deleted file mode 100644 index 0bf0bfb7a..000000000 --- a/pkg/dms-common/api/dms/v1/namespace.go +++ /dev/null @@ -1,60 +0,0 @@ -package v1 - -import ( - base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" - - "github.com/go-openapi/strfmt" -) - -// swagger:parameters ListNamespaces -type ListNamespaceReq struct { - // the maximum count of namespace to be returned - // in:query - // Required: true - PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` - // the offset of namespaces to be returned, default is 0 - // in:query - PageIndex uint32 `query:"page_index" json:"page_index"` - // Multiple of ["name"], default is ["name"] - // in:query - OrderBy NamespaceOrderByField `query:"order_by" json:"order_by"` - // filter the namespace name - FilterByName string `query:"filter_by_name" json:"filter_by_name"` - // filter the namespace UID - FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` -} - -// swagger:enum NamespaceOrderByField -type NamespaceOrderByField string - -const ( - NamespaceOrderByName NamespaceOrderByField = "name" -) - -// A dms namespace -type ListNamespace struct { - // namespace uid - NamespaceUid string `json:"uid"` - // namespace name - Name string `json:"name"` - // namespace is archived - Archived bool `json:"archived"` - // namespace desc - Desc string `json:"desc"` - // create user - CreateUser UidWithName `json:"create_user"` - // create time - CreateTime strfmt.DateTime `json:"create_time"` -} - -// swagger:model ListNamespaceReply -type ListNamespaceReply struct { - // List namespace reply - Payload struct { - Namespaces []*ListNamespace `json:"namespaces"` - Total int64 `json:"total"` - } `json:"payload"` - - // Generic reply - base.GenericResp -} diff --git a/pkg/dms-common/api/dms/v1/notify.go b/pkg/dms-common/api/dms/v1/notify.go index 3b3e6cd98..179084b5b 100644 --- a/pkg/dms-common/api/dms/v1/notify.go +++ b/pkg/dms-common/api/dms/v1/notify.go @@ -1,6 +1,9 @@ package v1 -import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + "github.com/actiontech/dms/pkg/dms-common/i18nPkg" +) // swagger:parameters Notification type NotificationReq struct { @@ -10,9 +13,9 @@ type NotificationReq struct { } type Notification struct { - NotificationSubject string `json:"notification_subject"` - NotificationBody string `json:"notification_body"` - UserUids []string `json:"user_uids"` + NotificationSubject i18nPkg.I18nStr `json:"notification_subject"` + NotificationBody i18nPkg.I18nStr `json:"notification_body"` + UserUids []string `json:"user_uids"` } // swagger:model NotificationReply diff --git a/pkg/dms-common/api/dms/v1/plugin.go b/pkg/dms-common/api/dms/v1/plugin.go index 7693e0b4c..2888a4673 100644 --- a/pkg/dms-common/api/dms/v1/plugin.go +++ b/pkg/dms-common/api/dms/v1/plugin.go @@ -4,58 +4,45 @@ import ( "fmt" base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + "github.com/actiontech/dms/pkg/params" ) -// swagger:enum IPluginDBType -type IPluginDBType string - -const ( - IPluginDBTypeDBTypeMySQL IPluginDBType = "MySQL" - IPluginDBTypeDBTypeOceanBaseMySQL IPluginDBType = "OceanBaseMySQL" -) - -func ParseIPluginDBType(s string) (IPluginDBType, error) { - switch s { - case string(IPluginDBTypeDBTypeMySQL): - return IPluginDBTypeDBTypeMySQL, nil - case string(IPluginDBTypeDBTypeOceanBaseMySQL): - return IPluginDBTypeDBTypeOceanBaseMySQL, nil - default: - return "", fmt.Errorf("invalid db type: %s", s) - } -} - type IPluginDBService struct { - Name string - DBType IPluginDBType - Host string - Port string - User string - Business string + Name string + DBType string + Host string + Port string + User string + // Business string + EnvironmentTag *EnvironmentTag SQLERuleTemplateName string SQLERuleTemplateId string - // TODO: more + AdditionalParams params.Params `json:"additional_params" from:"additional_params"` +} + +type IPluginProject struct { + // Project name + Name string `json:"name"` + // Project is archived + Archived bool `json:"archived"` + // Project desc + Desc string `json:"desc"` } type Plugin struct { // 插件名称 Name string `json:"name" validate:"required"` - // 添加数据源预检查接口地址, 如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/services/precheck/add - AddDBServicePreCheckUrl string `json:"add_db_service_pre_check_url"` - // 删除数据源预检查接口地址, 如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/services/precheck/del - DelDBServicePreCheckUrl string `json:"del_db_service_pre_check_url"` - // 删除用户预检查接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/users/precheck/del - DelUserPreCheckUrl string `json:"del_user_pre_check_url"` - // 删除用户组预检查接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/usergroups/precheck/del - DelUserGroupPreCheckUrl string `json:"del_user_group_pre_check_url"` // 操作资源处理接口地址,如果为空表示没有检查, eg: http://127.0.0.1:7602/v1/auth/data_resource_operate/handle + // 该地址目的是统一调用其他服务 数据资源变更前后校验/更新数据的 接口 + // eg: 删除数据源前: + // 需要sqle服务中实现接口逻辑,判断该数据源上已经没有进行中的工单 OperateDataResourceHandleUrl string `json:"operate_data_resource_handle_url"` + GetDatabaseDriverOptionsUrl string `json:"get_database_driver_options_url"` + GetDatabaseDriverLogosUrl string `json:"get_database_driver_logos_url"` } -// swagger:parameters RegisterDMSPlugin +// swagger:model type RegisterDMSPluginReq struct { - // Register dms plugin - // in:body Plugin *Plugin `json:"plugin" validate:"required"` } @@ -72,94 +59,16 @@ type RegisterDMSPluginReply struct { base.GenericResp } -// swagger:parameters AddDBServicePreCheck -type AddDBServicePreCheckReq struct { - // Check if dms can add db service - // in:body - DBService *IPluginDBService `json:"db_service" validate:"required"` -} - -func (u *AddDBServicePreCheckReq) String() string { - if u == nil { - return "AddDBServicePreCheckReq{nil}" - } - return fmt.Sprintf("AddDBServicePreCheckReq{Name:%s,DBType:%s Host:%s}", u.DBService.Name, u.DBService.DBType, u.DBService.Host) -} - -// swagger:model AddDBServicePreCheckReply -type AddDBServicePreCheckReply struct { - // Generic reply - base.GenericResp -} - -// swagger:parameters DelDBServicePreCheck -type DelDBServicePreCheckReq struct { - // Check if dms can del db service - // in:body - DBServiceUid string `json:"db_service_uid" validate:"required"` -} - -func (u *DelDBServicePreCheckReq) String() string { - if u == nil { - return "DelDBServicePreCheckReq{nil}" - } - return fmt.Sprintf("DelDBServicePreCheckReq{Uid:%s}", u.DBServiceUid) -} - -// swagger:model DelDBServicePreCheckReply -type DelDBServicePreCheckReply struct { - // Generic reply - base.GenericResp -} - -// swagger:parameters DelUserPreCheck -type DelUserPreCheckReq struct { - // Check if dms can del db service - // in:body - UserUid string `json:"user_uid" validate:"required"` -} - -func (u *DelUserPreCheckReq) String() string { - if u == nil { - return "DelUserPreCheckReq{nil}" - } - return fmt.Sprintf("DelUserPreCheckReq{Uid:%s}", u.UserUid) -} - -// swagger:model DelUserPreCheckReply -type DelUserPreCheckReply struct { - // Generic reply - base.GenericResp -} - -// swagger:parameters DelUserGroupPreCheck -type DelUserGroupPreCheckReq struct { - // Check if dms can del db service - // in:body - UserGroupUid string `json:"user_group_uid" validate:"required"` -} - -func (u *DelUserGroupPreCheckReq) String() string { - if u == nil { - return "DelUserGroupPreCheckReq{nil}" - } - return fmt.Sprintf("DelUserGroupPreCheckReq{Uid:%s}", u.UserGroupUid) -} - -// swagger:model DelUserGroupPreCheckReply -type DelUserGroupPreCheckReply struct { - // Generic reply - base.GenericResp -} - // swagger:enum DataResourceType type DataResourceType string const ( - DataResourceTypeDBService DataResourceType = "db_service" - DataResourceTypeNamespace DataResourceType = "namespace" - DataResourceTypeUser DataResourceType = "user" - DataResourceTypeUserGroup DataResourceType = "user_group" + DataResourceTypeDBService DataResourceType = "db_service" + DataResourceTypeProject DataResourceType = "project" + DataResourceTypeUser DataResourceType = "user" + DataResourceTypeUserGroup DataResourceType = "user_group" + DataResourceTypeMember DataResourceType = "member" + DataResourceTypeMemberGroup DataResourceType = "member_group" ) // swagger:enum OperationType @@ -176,7 +85,7 @@ type OperationTimingType string const ( OperationTimingTypeBefore OperationTimingType = "before" - OperationTimingAfter OperationTimingType = "after" + OperationTimingTypeAfter OperationTimingType = "after" ) // swagger:parameters OperateDataResourceHandle @@ -185,7 +94,7 @@ type OperateDataResourceHandleReq struct { DataResourceType DataResourceType `json:"data_resource_type"` OperationType OperationType `json:"operation_type"` OperationTiming OperationTimingType `json:"operation_timing"` - // TODO ExtraParams need extra params for pre check? + ExtraParams string `json:"extra_params"` } // swagger:model OperateDataResourceHandleReply diff --git a/pkg/dms-common/api/dms/v1/project.go b/pkg/dms-common/api/dms/v1/project.go new file mode 100644 index 000000000..1e4112037 --- /dev/null +++ b/pkg/dms-common/api/dms/v1/project.go @@ -0,0 +1,120 @@ +package v1 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + + "github.com/go-openapi/strfmt" +) + +// swagger:parameters ListProjects +type ListProjectReq struct { + // the maximum count of Project to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of Projects to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy ProjectOrderByField `query:"order_by" json:"order_by"` + // filter the Project name + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // filter the Project UID + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` + // filter project by project id list, using in condition + // in:query + FilterByProjectUids []string `query:"filter_by_project_uids" json:"filter_by_project_uids"` + // filter project by project priority + // in:query + FilterByProjectPriority ProjectPriority `query:"filter_by_project_priority" json:"filter_by_project_priority"` + // filter the Project By Project description + FilterByDesc string `query:"filter_by_desc" json:"filter_by_desc"` +} + +// swagger:enum ProjectOrderByField +type ProjectOrderByField string + +const ( + ProjectOrderByName ProjectOrderByField = "name" +) + +// swagger:enum ProjectPriority +type ProjectPriority string + +const ( + ProjectPriorityHigh ProjectPriority = "high" + ProjectPriorityMedium ProjectPriority = "medium" + ProjectPriorityLow ProjectPriority = "low" + ProjectPriorityUnknown ProjectPriority = "unknown" // 当数据库中数据存在问题时,返回该状态 +) + +func ToPriorityNum(priority ProjectPriority) uint8 { + switch priority { + case ProjectPriorityHigh: + return 30 + case ProjectPriorityMedium: + return 20 + case ProjectPriorityLow: + return 10 + default: + return 20 // 默认优先级为中 + } +} + +func ToPriority(priority uint8) ProjectPriority { + switch priority { + case 10: + return ProjectPriorityLow + case 20: + return ProjectPriorityMedium + case 30: + return ProjectPriorityHigh + default: + return ProjectPriorityUnknown + } +} + +// swagger:model ListProjectV1 +type ListProject struct { + // Project uid + ProjectUid string `json:"uid"` + // Project name + Name string `json:"name"` + // Project is archived + Archived bool `json:"archived"` + // Project desc + Desc string `json:"desc"` + // is fixed business + IsFixedBusiness bool `json:"is_fixed_business"` + // Project business + Business []Business `json:"business"` + // create user + CreateUser UidWithName `json:"create_user"` + // create time + CreateTime strfmt.DateTime `json:"create_time"` + // project priority + ProjectPriority ProjectPriority `json:"project_priority" enums:"high,medium,low"` +} + +type Business struct { + Id string `json:"id"` + Name string `json:"name"` + IsUsed bool `json:"is_used"` +} + +// swagger:model ListProjectReply +type ListProjectReply struct { + // List project reply + Data []*ListProject `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +type ProjectInfo struct { + ProjectUid string `json:"project_uid"` + ProjectName string `json:"project_name"` + ProjectPriority ProjectPriority `json:"project_priority"` +} diff --git a/pkg/dms-common/api/dms/v1/proxy.go b/pkg/dms-common/api/dms/v1/proxy.go index 0c72e8624..80c2fbf45 100644 --- a/pkg/dms-common/api/dms/v1/proxy.go +++ b/pkg/dms-common/api/dms/v1/proxy.go @@ -1,11 +1,13 @@ package v1 -import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +import ( + "fmt" -// swagger:parameters RegisterDMSProxyTarget + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +// swagger:model type RegisterDMSProxyTargetReq struct { - // register dms proxy - // in:body DMSProxyTarget *DMSProxyTarget `json:"dms_proxy_target" validate:"required"` } @@ -17,11 +19,28 @@ type DMSProxyTarget struct { // target addr, eg: http://10.1.2.1:5432 // Required: true Addr string `json:"addr" validate:"required,url"` + // version number + // Required: true + Version string `json:"version" validate:"required"` // url prefix that need to be proxy, eg: /v1/user // Required: true ProxyUrlPrefixs []string `json:"proxy_url_prefixs" validate:"required"` + // the scenario is used to differentiate scenarios + Scenario ProxyScenario `json:"scenario"` +} + +func (s *DMSProxyTarget) String() string { + return fmt.Sprintf("{name: %v, addr: %v, version: %v, Scenario %v}", s.Name, s.Addr, s.Version, s.Scenario) } +// swagger:enum ProxyScenario +type ProxyScenario string + +const ( + ProxyScenarioInternalService ProxyScenario = "internal_service" + ProxyScenarioThirdPartyIntegrate ProxyScenario = "thrid_party_integrate" +) + // swagger:model RegisterDMSProxyTargetReply type RegisterDMSProxyTargetReply struct { // Generic reply diff --git a/pkg/dms-common/api/dms/v1/router.go b/pkg/dms-common/api/dms/v1/router.go index 70822c46b..8d9989d00 100644 --- a/pkg/dms-common/api/dms/v1/router.go +++ b/pkg/dms-common/api/dms/v1/router.go @@ -7,21 +7,25 @@ import ( // login config var ( - JwtSigningKey = []byte("actiontech dms secret") + JwtSigningKey = []byte("secret") ) // router var ( SessionRouterGroup = "/dms/sessions" UserRouterGroup = "/dms/users" - DBServiceRouterGroup = "/dms/db_services" + DBServiceRouterGroup = "/dms/projects/:project_uid/db_services" + DBEnvironmentTagGroup = "/dms/projects/:project_uid/environment_tags" ProxyRouterGroup = "/dms/proxys" PluginRouterGroup = "/dms/plugins" - MemberRouterGroup = "/dms/members" - NamespaceRouterGroup = "/dms/namespaces" + MemberRouterGroup = "/dms/projects/:project_uid/members" + MemberGroupRouterGroup = "/dms/projects/:project_uid/member_groups" + ProjectRouterGroup = "/dms/projects" NotificationRouterGroup = "/dms/notifications" WebHookRouterGroup = "/dms/webhooks" MemberForInternalRouterSuffix = "/internal" + InternalDBServiceRouterGroup = "/internal/db_services" + LicenseRouterGroup = "/dms/license" ) // api group @@ -30,6 +34,12 @@ var ( CurrentGroupVersion = GroupV1 ) +func ResetJWTSigningKey(val string) { + if val != "" { + JwtSigningKey = []byte(val) + } +} + func GetUserOpPermissionRouter(userUid string) string { return fmt.Sprintf("%s%s/%s/op_permission", CurrentGroupVersion, UserRouterGroup, userUid) } @@ -39,20 +49,24 @@ func GetUserOpPermissionRouterWithoutPrefix(userUid string) string { return strings.TrimPrefix(strings.TrimPrefix(router, CurrentGroupVersion), UserRouterGroup) } -func GetDBServiceRouter() string { - return fmt.Sprintf("%s%s", CurrentGroupVersion, DBServiceRouterGroup) +func GetDBServiceRouter(projectUid string) string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, strings.Replace(DBServiceRouterGroup, ":project_uid", projectUid, 1)) } func GetUserRouter(userUid string) string { return fmt.Sprintf("%s%s/%s", CurrentGroupVersion, UserRouterGroup, userUid) } +func GetMemberGroupRouter(memberGroupUid, projectUid string) string { + return fmt.Sprintf("%s%s/%s", CurrentGroupVersion, strings.Replace(MemberGroupRouterGroup, ":project_uid", projectUid, 1), memberGroupUid) +} + func GetUsersRouter() string { return fmt.Sprintf("%s%s", CurrentGroupVersion, UserRouterGroup) } -func GetListMembersForInternalRouter() string { - return fmt.Sprintf("%s%s%s", CurrentGroupVersion, MemberRouterGroup, MemberForInternalRouterSuffix) +func GetListMembersForInternalRouter(projectUid string) string { + return fmt.Sprintf("%s%s%s", CurrentGroupVersion, strings.Replace(MemberRouterGroup, ":project_uid", projectUid, 1), MemberForInternalRouterSuffix) } func GetProxyRouter() string { @@ -63,8 +77,8 @@ func GetPluginRouter() string { return fmt.Sprintf("%s%s", CurrentGroupVersion, PluginRouterGroup) } -func GetNamespacesRouter() string { - return fmt.Sprintf("%s%s", CurrentGroupVersion, NamespaceRouterGroup) +func GetProjectsRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, ProjectRouterGroup) } func GetNotificationRouter() string { @@ -74,3 +88,11 @@ func GetNotificationRouter() string { func GetWebHooksRouter() string { return fmt.Sprintf("%s%s", CurrentGroupVersion, WebHookRouterGroup) } + +func GetDBConnectionAbleRouter() string { + return fmt.Sprintf("%s%s/connection", CurrentGroupVersion, InternalDBServiceRouterGroup) +} + +func GetGlobalDataExportWorkflowsRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, "/dms/dashboard/data_export_workflows") +} diff --git a/pkg/dms-common/api/dms/v1/system_variable.go b/pkg/dms-common/api/dms/v1/system_variable.go new file mode 100644 index 000000000..a385555bb --- /dev/null +++ b/pkg/dms-common/api/dms/v1/system_variable.go @@ -0,0 +1,29 @@ +package v1 + +import base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + +// swagger:model UpdateSystemVariablesReqV1 +type UpdateSystemVariablesReqV1 struct { + Url *string `json:"url" form:"url" example:"http://10.186.61.32:8080" validate:"omitempty,url"` + OperationRecordExpiredHours *int `json:"operation_record_expired_hours" form:"operation_record_expired_hours" example:"2160"` + CbOperationLogsExpiredHours *int `json:"cb_operation_logs_expired_hours" form:"cb_operation_logs_expired_hours" example:"2160"` + SystemVariableSSHPrimaryKey *string `json:"system_variable_ssh_primary_key"` + SystemVariableWorkflowExpiredHours *int `json:"system_variable_workflow_expired_hours"` + SystemVariableSqlManageRawExpiredHours *int `json:"system_variable_sql_manage_raw_expired_hours"` +} + +// swagger:model GetSystemVariablesReply +type GetSystemVariablesReply struct { + // Generic reply + base.GenericResp + Data SystemVariablesResV1 `json:"data"` +} + +type SystemVariablesResV1 struct { + Url string `json:"url"` + OperationRecordExpiredHours int `json:"operation_record_expired_hours"` + CbOperationLogsExpiredHours int `json:"cb_operation_logs_expired_hours"` + SystemVariableSSHPrimaryKey string `json:"system_variable_ssh_primary_key"` + SystemVariableWorkflowExpiredHours int `json:"system_variable_workflow_expired_hours"` + SystemVariableSqlManageRawExpiredHours int `json:"system_variable_sql_manage_raw_expired_hours"` +} diff --git a/pkg/dms-common/api/dms/v1/user.go b/pkg/dms-common/api/dms/v1/user.go index 5289c037d..d043f5160 100644 --- a/pkg/dms-common/api/dms/v1/user.go +++ b/pkg/dms-common/api/dms/v1/user.go @@ -25,8 +25,12 @@ type GetUser struct { Phone string `json:"phone"` // user wxid WxID string `json:"wxid"` + // user language + Language string `json:"language"` // user stat Stat Stat `json:"stat"` + // user two factor enabled + TwoFactorEnabled bool `json:"two_factor_enabled"` // user authentication type AuthenticationType UserAuthenticationType `json:"authentication_type"` // user groups @@ -36,22 +40,36 @@ type GetUser struct { // is admin IsAdmin bool `json:"is_admin"` // user bind name space - UserBindNamespaces []UserBindNamespace `json:"user_bind_namespaces"` + UserBindProjects []UserBindProject `json:"user_bind_projects"` + ThirdPartyUserInfo string `json:"third_party_user_info"` + // access token + AccessTokenInfo AccessTokenInfo `json:"access_token_info"` + // user system + System UserSystem `json:"system"` } -type UserBindNamespace struct { - NamespaceID string `json:"namespace_id"` - NamespaceName string `json:"namespace_name"` - IsManager bool `json:"is_manager"` +type AccessTokenInfo struct { + AccessToken string `json:"access_token"` + ExpiredTime string `json:"token_expired_timestamp" example:"RFC3339"` + IsExpired bool `json:"is_expired"` +} + +type UserBindProject struct { + ProjectID string `json:"project_id"` + ProjectName string `json:"project_name"` + IsManager bool `json:"is_manager"` } // swagger:enum Stat type Stat string const ( - StatOK Stat = "正常" - StatDisable Stat = "被禁用" - StatUnknown Stat = "未知" + StatOK Stat = "正常" + StatDisable Stat = "被禁用" + StatUnknown Stat = "未知" + StatOKEn Stat = "Normal" + StatDisableEn Stat = "Disabled" + StatUnknownEn Stat = "Unknown" ) type UidWithName struct { @@ -69,12 +87,26 @@ const ( UserAuthenticationTypeUnknown UserAuthenticationType = "unknown" ) +// swagger:enum UserSystem +type UserSystem string + +const ( + UserSystemWorkbench UserSystem = "WORKBENCH" + UserSystemManagement UserSystem = "MANAGEMENT" +) + +// swagger:enum UserStatFilter +type UserStatFilter string + +const ( + UserStatFilterNormal UserStatFilter = "Normal" // normal + UserStatFilterDisabled UserStatFilter = "Disabled" // disabled +) + // swagger:model GetUserReply type GetUserReply struct { // Get user reply - Payload struct { - User *GetUser `json:"user"` - } `json:"payload"` + Data *GetUser `json:"data"` // Generic reply base.GenericResp @@ -85,26 +117,29 @@ type GetUserOpPermissionReq struct { // user uid // in:path UserUid string `param:"user_uid" json:"user_uid" validate:"required"` + + // in:query + // uesr project uid + ProjectUid string `json:"project_uid" query:"project_uid"` // user op permission info // in:body - UserOpPermission *UserOpPermission `json:"user_op_permission" validate:"required"` + UserOpPermission *UserOpPermission `json:"user_op_permission" ` } type UserOpPermission struct { - // uesr namespace uid - NamespaceUid string `json:"namespace_uid" validate:"required"` + // uesr project uid + ProjectUid string `json:"project_uid"` } // swagger:model GetUserOpPermissionReply type GetUserOpPermissionReply struct { // user op permission reply - Payload struct { - // is user admin, admin has all permissions + // is user admin, admin has all permissions + Data struct { IsAdmin bool `json:"is_admin"` // user op permissions OpPermissionList []OpPermissionItem `json:"op_permission_list"` - } `json:"payload"` - + } `json:"data"` // Generic reply base.GenericResp } @@ -125,9 +160,9 @@ const ( OpRangeTypeUnknown OpRangeType = "unknown" // 全局权限: 该权限只能被用户使用 OpRangeTypeGlobal OpRangeType = "global" - // 空间权限: 该权限只能被成员使用 - OpRangeTypeNamespace OpRangeType = "namespace" - // 空间内的数据源权限: 该权限只能被成员使用 + // 项目权限: 该权限只能被成员使用 + OpRangeTypeProject OpRangeType = "project" + // 项目内的数据源权限: 该权限只能被成员使用 OpRangeTypeDBService OpRangeType = "db_service" ) @@ -135,8 +170,8 @@ func ParseOpRangeType(typ string) (OpRangeType, error) { switch typ { case string(OpRangeTypeDBService): return OpRangeTypeDBService, nil - case string(OpRangeTypeNamespace): - return OpRangeTypeNamespace, nil + case string(OpRangeTypeProject): + return OpRangeTypeProject, nil case string(OpRangeTypeGlobal): return OpRangeTypeGlobal, nil default: @@ -149,15 +184,19 @@ type OpPermissionType string const ( OpPermissionTypeUnknown OpPermissionType = "unknown" - // 创建空间;创建空间的用户自动拥有该空间管理权限 - OpPermissionTypeCreateNamespace OpPermissionType = "create_namespace" - // 空间管理;拥有该权限的用户可以管理空间下的所有资源 - OpPermissionTypeNamespaceAdmin OpPermissionType = "namespace_admin" + // 创建项目;创建项目的用户自动拥有该项目管理权限 + OpPermissionTypeCreateProject OpPermissionType = "create_project" + // 项目管理;拥有该权限的用户可以管理项目下的所有资源 + OpPermissionTypeGlobalView OpPermissionType = "global_view" + // 全局浏览;拥有该权限的用户可以浏览全局的资源 + OpPermissionTypeGlobalManagement OpPermissionType = "global_management" + // 全局管理;拥有该权限的用户可以浏览和管理全局的资源 + OpPermissionTypeProjectAdmin OpPermissionType = "project_admin" // 创建/编辑工单;拥有该权限的用户可以创建/编辑工单 OpPermissionTypeCreateWorkflow OpPermissionType = "create_workflow" // 审核/驳回工单;拥有该权限的用户可以审核/驳回工单 OpPermissionTypeAuditWorkflow OpPermissionType = "audit_workflow" - // 授权数据源数据权限;拥有该权限的用户可以授权数据源数据权限 + // 账号管理;拥有该权限的用户可以授权数据源数据权限 OpPermissionTypeAuthDBServiceData OpPermissionType = "auth_db_service_data" // 查看其他工单权限 OpPermissionTypeViewOthersWorkflow OpPermissionType = "view_others_workflow" @@ -165,18 +204,72 @@ const ( OpPermissionTypeExecuteWorkflow OpPermissionType = "execute_workflow" // 查看其他扫描任务权限 OpPermissionTypeViewOtherAuditPlan OpPermissionType = "view_other_audit_plan" + // 查看SQL洞察权限 + OpPermissionTypeViewSQLInsight OpPermissionType = "view_sql_insight" // 创建扫描任务权限;拥有该权限的用户可以创建/更新扫描任务 OpPermissionTypeSaveAuditPlan OpPermissionType = "save_audit_plan" //SQL查询;SQL查询权限 OpPermissionTypeSQLQuery OpPermissionType = "sql_query" + // 创建数据导出任务;拥有该权限的用户可以创建数据导出任务或者工单 + OpPermissionTypeExportCreate OpPermissionType = "create_export_task" + // 审核/驳回数据导出工单;拥有该权限的用户可以审核/驳回数据导出工单 + OpPermissionTypeAuditExportWorkflow OpPermissionType = "audit_export_workflow" + // 创建智能调优;拥有该权限的用户可以创建智能调优 + OpPermissionTypeCreateOptimization OpPermissionType = "create_optimization" + // 查看他人创建的智能调优 + OpPermissionTypeViewOthersOptimization OpPermissionType = "view_others_optimization" + // 配置流水线 + OpPermissionTypeCreatePipeline OpPermissionType = "create_pipeline" + // SQL工作台;查看所有操作记录 + OpPermissionViewOperationRecord OpPermissionType = "view_operation_record" + // 数据导出;查看所有导出任务 + OpPermissionViewExportTask OpPermissionType = "view_export_task" + // 快捷审核;查看所有快捷审核记录 + OpPermissionViewQuickAuditRecord OpPermissionType = "view_quick_audit_record" + // IDE审核;查看所有IDE审核记录 + OpPermissionViewIDEAuditRecord OpPermissionType = "view_ide_audit_record" + // SQL优化;查看所有优化记录 + OpPermissionViewOptimizationRecord OpPermissionType = "view_optimization_record" + // 版本管理;查看他人创建的版本记录 + OpPermissionViewVersionManage OpPermissionType = "view_version_manage" + // 版本管理;配置版本 + OpPermissionVersionManage OpPermissionType = "version_manage" + // CI/CD集成;查看所有流水线 + OpPermissionViewPipeline OpPermissionType = "view_pipeline" + // 数据源管理;管理项目数据源管理 + OpPermissionManageProjectDataSource OpPermissionType = "manage_project_data_source" + // 审核规则模版;管理审核规则模版 + OpPermissionManageAuditRuleTemplate OpPermissionType = "manage_audit_rule_template" + // 审批流程模版;管理审批流程模版 + OpPermissionManageApprovalTemplate OpPermissionType = "manage_approval_template" + // 成员与权限;管理成员与权限 + OpPermissionManageMember OpPermissionType = "manage_member" + // 推送规则;管理推送规则 + OpPermissionPushRule OpPermissionType = "manage_push_rule" + // 审核SQL例外;管理审核SQL例外 + OpPermissionMangeAuditSQLWhiteList OpPermissionType = "manage_audit_sql_white_list" + // 管控SQL例外;管理管控SQL例外 + OpPermissionManageSQLMangeWhiteList OpPermissionType = "manage_sql_mange_white_list" + // 角色管理;角色管理权限 + OpPermissionManageRoleMange OpPermissionType = "manage_role_mange" + // 脱敏规则;脱敏规则配置权限 + OpPermissionDesensitization OpPermissionType = "desensitization" + // 脱敏审核;拥有该权限的用户可以查看和处理脱敏审批请求 + OpPermissionMaskingAudit OpPermissionType = "masking_audit" + // 无任何权限 + OpPermissionTypeNone OpPermissionType = "none" ) func ParseOpPermissionType(typ string) (OpPermissionType, error) { switch typ { - case string(OpPermissionTypeCreateNamespace): - return OpPermissionTypeCreateNamespace, nil - case string(OpPermissionTypeNamespaceAdmin): - return OpPermissionTypeNamespaceAdmin, nil + case string(OpPermissionTypeGlobalView): + return OpPermissionTypeGlobalView, nil + case string(OpPermissionTypeGlobalManagement): + return OpPermissionTypeGlobalManagement, nil + case string(OpPermissionTypeCreateProject): + return OpPermissionTypeCreateProject, nil + case string(OpPermissionTypeProjectAdmin): + return OpPermissionTypeProjectAdmin, nil case string(OpPermissionTypeCreateWorkflow): return OpPermissionTypeCreateWorkflow, nil case string(OpPermissionTypeAuditWorkflow): @@ -189,10 +282,60 @@ func ParseOpPermissionType(typ string) (OpPermissionType, error) { return OpPermissionTypeExecuteWorkflow, nil case string(OpPermissionTypeViewOtherAuditPlan): return OpPermissionTypeViewOtherAuditPlan, nil + case string(OpPermissionTypeViewSQLInsight): + return OpPermissionTypeViewSQLInsight, nil case string(OpPermissionTypeSaveAuditPlan): return OpPermissionTypeSaveAuditPlan, nil case string(OpPermissionTypeSQLQuery): return OpPermissionTypeSQLQuery, nil + case string(OpPermissionTypeExportCreate): + return OpPermissionTypeExportCreate, nil + case string(OpPermissionTypeAuditExportWorkflow): + return OpPermissionTypeAuditExportWorkflow, nil + case string(OpPermissionTypeCreateOptimization): + return OpPermissionTypeCreateOptimization, nil + case string(OpPermissionTypeViewOthersOptimization): + return OpPermissionTypeViewOthersOptimization, nil + case string(OpPermissionTypeCreatePipeline): + return OpPermissionTypeCreatePipeline, nil + case string(OpPermissionViewOperationRecord): + return OpPermissionViewOperationRecord, nil + case string(OpPermissionViewExportTask): + return OpPermissionViewExportTask, nil + case string(OpPermissionViewQuickAuditRecord): + return OpPermissionViewQuickAuditRecord, nil + case string(OpPermissionViewIDEAuditRecord): + return OpPermissionViewIDEAuditRecord, nil + case string(OpPermissionViewOptimizationRecord): + return OpPermissionViewOptimizationRecord, nil + case string(OpPermissionViewVersionManage): + return OpPermissionViewVersionManage, nil + case string(OpPermissionVersionManage): + return OpPermissionVersionManage, nil + case string(OpPermissionViewPipeline): + return OpPermissionViewPipeline, nil + case string(OpPermissionManageProjectDataSource): + return OpPermissionManageProjectDataSource, nil + case string(OpPermissionManageAuditRuleTemplate): + return OpPermissionManageAuditRuleTemplate, nil + case string(OpPermissionManageApprovalTemplate): + return OpPermissionManageApprovalTemplate, nil + case string(OpPermissionManageMember): + return OpPermissionManageMember, nil + case string(OpPermissionPushRule): + return OpPermissionPushRule, nil + case string(OpPermissionMangeAuditSQLWhiteList): + return OpPermissionMangeAuditSQLWhiteList, nil + case string(OpPermissionManageSQLMangeWhiteList): + return OpPermissionManageSQLMangeWhiteList, nil + case string(OpPermissionManageRoleMange): + return OpPermissionManageRoleMange, nil + case string(OpPermissionDesensitization): + return OpPermissionDesensitization, nil + case string(OpPermissionMaskingAudit): + return OpPermissionMaskingAudit, nil + case string(OpPermissionTypeNone): + return OpPermissionTypeNone, nil default: return "", fmt.Errorf("invalid op permission type: %s", typ) } @@ -202,10 +345,10 @@ func GetOperationTypeDesc(opType OpPermissionType) string { switch opType { case OpPermissionTypeUnknown: return "未知操作类型" - case OpPermissionTypeCreateNamespace: - return "创建空间" - case OpPermissionTypeNamespaceAdmin: - return "空间管理" + case OpPermissionTypeCreateProject: + return "创建项目" + case OpPermissionTypeProjectAdmin: + return "项目管理" case OpPermissionTypeCreateWorkflow: return "创建/编辑工单" case OpPermissionTypeAuditWorkflow: @@ -218,12 +361,22 @@ func GetOperationTypeDesc(opType OpPermissionType) string { return "上线工单" case OpPermissionTypeViewOtherAuditPlan: return "查看其他扫描任务权限" + case OpPermissionTypeViewSQLInsight: + return "查看SQL洞察权限" case OpPermissionTypeSaveAuditPlan: return "创建扫描任务权限" case OpPermissionTypeSQLQuery: - return "SQL查询" + return "SQL工作台查询" + case OpPermissionTypeCreateOptimization: + return "创建智能调优" + case OpPermissionTypeViewOthersOptimization: + return "查看他人创建的智能调优" + case OpPermissionTypeCreatePipeline: + return "配置流水线" + case OpPermissionMaskingAudit: + return "脱敏审核" default: - return "不支持的操作类型" + return "未知操作类型" } } @@ -248,6 +401,26 @@ type ListUserReq struct { // filter deleted user to be return ,default is false // in:query FilterDeletedUser bool `query:"filter_del_user" json:"filter_del_user"` + // fuzzy keyword + // in:query + // fuzzy keyword, search in name, uid, email, phone fields (OR relationship) + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` + // filter the user email + // in:query + FilterByEmail string `query:"filter_by_email" json:"filter_by_email"` + // filter the user phone + // in:query + FilterByPhone string `query:"filter_by_phone" json:"filter_by_phone"` + // filter the user stat (0: normal, 1: disabled) + // in:query + FilterByStat UserStatFilter `query:"filter_by_stat" json:"filter_by_stat"` + // filter the user authentication type (ldap, dms, oauth2) + // in:query + FilterByAuthenticationType UserAuthenticationType `query:"filter_by_authentication_type" json:"filter_by_authentication_type"` + // filter the user system (WORKBENCH, MANAGEMENT) + // in:query + FilterBySystem UserSystem `query:"filter_by_system" json:"filter_by_system"` } // swagger:enum UserOrderByField @@ -277,17 +450,35 @@ type ListUser struct { UserGroups []UidWithName `json:"user_groups"` // user operation permissions OpPermissions []UidWithName `json:"op_permissions"` + // projects + Projects []string `json:"projects"` // user is deleted IsDeleted bool `json:"is_deleted"` + // third party user info + ThirdPartyUserInfo string `json:"third_party_user_info"` + // user system + System UserSystem `json:"system"` } // swagger:model ListUserReply type ListUserReply struct { // List user reply - Payload struct { - Users []*ListUser `json:"users"` - Total int64 `json:"total"` - } `json:"payload"` + Data []*ListUser `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +// swagger:model +type GenAccessToken struct { + ExpirationDays string `param:"expiration_days" json:"expiration_days" validate:"required"` +} + +// swagger:model GenAccessTokenReply +type GenAccessTokenReply struct { + // Get user reply + Data *AccessTokenInfo `json:"data"` // Generic reply base.GenericResp diff --git a/pkg/dms-common/api/dms/v1/webhooks.go b/pkg/dms-common/api/dms/v1/webhooks.go index ae8ccc2d5..9da77bd99 100644 --- a/pkg/dms-common/api/dms/v1/webhooks.go +++ b/pkg/dms-common/api/dms/v1/webhooks.go @@ -6,12 +6,11 @@ type TriggerEventType string const ( TriggerEventTypeWorkflow TriggerEventType = "workflow" + TriggerEventAuditPlan TriggerEventType = "auditplan" ) -// swagger:parameters WebHookSendMessage +// swagger:model type WebHookSendMessageReq struct { - // webhooks - // in:body WebHookMessage *WebHooksMessage `json:"webhook_message" validate:"required"` } diff --git a/pkg/dms-common/api/dms/v1/workflow.go b/pkg/dms-common/api/dms/v1/workflow.go new file mode 100644 index 000000000..22c6505a4 --- /dev/null +++ b/pkg/dms-common/api/dms/v1/workflow.go @@ -0,0 +1,52 @@ +package v1 + +import ( + "time" + + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" +) + +type FilterGlobalDataExportWorkflowReq struct { + FilterStatusList []DataExportWorkflowStatus `json:"filter_status_list" query:"filter_status_list"` + FilterDBServiceUid string `json:"filter_db_service_uid" query:"filter_db_service_uid"` + FilterProjectUids []string `json:"filter_project_uids" query:"filter_project_uids"` + FilterCurrentStepAssigneeUserId string `json:"filter_current_step_assignee_user_id" query:"filter_current_step_assignee_user_id"` + FilterProjectUid string `json:"filter_project_uid" query:"filter_project_uid"` + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + PageIndex uint32 `query:"page_index" json:"page_index"` + FilterByStatus DataExportWorkflowStatus `query:"filter_by_status" json:"filter_by_status"` + FilterByCreateUserUid string `json:"filter_by_create_user_uid" query:"filter_by_create_user_uid"` + FilterCurrentStepAssigneeUserUid string `json:"filter_current_step_assignee_user_uid" query:"filter_current_step_assignee_user_uid"` + FilterByDBServiceUid string `json:"filter_by_db_service_uid" query:"filter_by_db_service_uid"` + FuzzyKeyword string `json:"fuzzy_keyword" query:"fuzzy_keyword"` +} + +type DataExportWorkflowStatus string + +const ( + DataExportWorkflowStatusWaitForApprove DataExportWorkflowStatus = "wait_for_approve" + DataExportWorkflowStatusWaitForExport DataExportWorkflowStatus = "wait_for_export" + DataExportWorkflowStatusWaitForExporting DataExportWorkflowStatus = "exporting" + DataExportWorkflowStatusRejected DataExportWorkflowStatus = "rejected" + DataExportWorkflowStatusCancel DataExportWorkflowStatus = "cancel" + DataExportWorkflowStatusFailed DataExportWorkflowStatus = "failed" + DataExportWorkflowStatusFinish DataExportWorkflowStatus = "finish" +) + +type ListDataExportWorkflow struct { + WorkflowID string `json:"workflow_uid"` // 数据导出工单ID + WorkflowName string `json:"workflow_name"` // 数据导出工单的名称 + Description string `json:"desc"` // 数据导出工单的描述 + Creater UidWithName `json:"creater"` // 数据导出工单的创建人 + CreatedAt time.Time `json:"created_at"` // 数据导出工单的创建时间 + Status DataExportWorkflowStatus `json:"status"` // 数据导出工单的状态 + CurrentStepAssigneeUsers []UidWithName `json:"current_step_assignee_user_list"` // 工单待操作人 + DBServiceInfos []*DBServiceUidWithNameInfo `json:"db_service_info,omitempty"` // 所属数据源信息 + ProjectInfo *ProjectInfo `json:"project_info,omitempty"` // 所属项目信息 +} + +type ListDataExportWorkflowsReply struct { + Data []*ListDataExportWorkflow `json:"data"` + Total int64 `json:"total_nums"` + base.GenericResp +} diff --git a/pkg/dms-common/api/dms/v2/db_service.go b/pkg/dms-common/api/dms/v2/db_service.go new file mode 100644 index 000000000..c0445372d --- /dev/null +++ b/pkg/dms-common/api/dms/v2/db_service.go @@ -0,0 +1,113 @@ +package v2 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/go-openapi/strfmt" +) + +// swagger:parameters ListDBServicesV2 +type ListDBServiceReq struct { + // the maximum count of db service to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of users to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy v1.DBServiceOrderByField `query:"order_by" json:"order_by"` + // the db service connection + // enum: ["connect_success","connect_failed"] + // in:query + FilterLastConnectionTestStatus *string `query:"filter_last_connection_test_status" json:"filter_last_connection_test_status" validate:"omitempty,oneof=connect_success connect_failed"` + // the db service host + // in:query + FilterByHost string `query:"filter_by_host" json:"filter_by_host"` + // the db service uid + // in:query + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` + // the db service name + // in:query + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // the db service port + // in:query + FilterByPort string `query:"filter_by_port" json:"filter_by_port"` + // the db service db type + // in:query + FilterByDBType string `query:"filter_by_db_type" json:"filter_by_db_type"` + // project id + // in:path + ProjectUid string `param:"project_uid" json:"project_uid"` + // filter db services by db service id list using in condition + // in:query + FilterByDBServiceIds []string `query:"filter_by_db_service_ids" json:"filter_by_db_service_ids"` + // filter db services by environment tag + // in:query + FilterByEnvironmentTagUID string `query:"filter_by_environment_tag_uid" json:"filter_by_environment_tag_uid"` + // the db service fuzzy keyword,include host/port + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` + // is masking + // in:query + IsEnableMasking *bool `query:"is_enable_masking" json:"is_enable_masking"` +} + +// swagger:model ListDBServiceReplyV2 +type ListDBServiceReply struct { + // List db service reply + Data []*ListDBService `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} + +// swagger:model ListDBServiceV2 +type ListDBService struct { + // db service uid + DBServiceUid string `json:"uid"` + // db service name + Name string `json:"name"` + // db service DB type + DBType string `json:"db_type"` + // db service host + Host string `json:"host"` + // db service port + Port string `json:"port"` + // db service admin user + User string `json:"user"` + // db service admin encrypted password + Password string `json:"password"` + // DB Service environment tag + EnvironmentTag *v1.EnvironmentTag `json:"environment_tag"` + // DB Service maintenance time + MaintenanceTimes []*v1.MaintenanceTime `json:"maintenance_times"` + // DB desc + Desc string `json:"desc"` + // DB source + Source string `json:"source"` + // DB project uid + ProjectUID string `json:"project_uid"` + // sqle config + SQLEConfig *v1.SQLEConfig `json:"sqle_config"` + // DB Service Custom connection parameters + AdditionalParams []*v1.AdditionalParam `json:"additional_params"` + // is enable masking + IsEnableMasking bool `json:"is_enable_masking"` + // backup switch + EnableBackup bool `json:"enable_backup"` + // backup max rows + BackupMaxRows uint64 `json:"backup_max_rows"` + // audit plan types + AuditPlanTypes []*v1.AuditPlanTypes `json:"audit_plan_types"` + // instance audit plan id + InstanceAuditPlanID uint `json:"instance_audit_plan_id,omitempty"` + // DB connection test time + LastConnectionTestTime strfmt.DateTime `json:"last_connection_test_time"` + // DB connect test status + LastConnectionTestStatus v1.LastConnectionTestStatus `json:"last_connection_test_status"` + // DB connect test error message + LastConnectionTestErrorMessage string `json:"last_connection_test_error_message,omitempty"` +} diff --git a/pkg/dms-common/api/dms/v2/project.go b/pkg/dms-common/api/dms/v2/project.go new file mode 100644 index 000000000..58d6396e3 --- /dev/null +++ b/pkg/dms-common/api/dms/v2/project.go @@ -0,0 +1,78 @@ +package v2 + +import ( + base "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + + "github.com/go-openapi/strfmt" + + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" +) + +// swagger:parameters ListProjectsV2 +type ListProjectReq struct { + // the maximum count of Project to be returned + // in:query + // Required: true + PageSize uint32 `query:"page_size" json:"page_size" validate:"required"` + // the offset of Projects to be returned, default is 0 + // in:query + PageIndex uint32 `query:"page_index" json:"page_index"` + // Multiple of ["name"], default is ["name"] + // in:query + OrderBy v1.ProjectOrderByField `query:"order_by" json:"order_by"` + // filter the Project name + FilterByName string `query:"filter_by_name" json:"filter_by_name"` + // filter the Project UID + FilterByUID string `query:"filter_by_uid" json:"filter_by_uid"` + // filter project by project id list, using in condition + // in:query + FilterByProjectUids []string `query:"filter_by_project_uids" json:"filter_by_project_uids"` + // filter project by project priority + // in:query + FilterByProjectPriority v1.ProjectPriority `query:"filter_by_project_priority" json:"filter_by_project_priority"` + // filter project by business tag + // in:query + FilterByBusinessTag string `query:"filter_by_business_tag" json:"filter_by_business_tag"` + // filter the Project By Project description + FilterByDesc string `query:"filter_by_desc" json:"filter_by_desc"` + // fuzzy keyword + // in:query + FuzzyKeyword string `query:"fuzzy_keyword" json:"fuzzy_keyword"` +} + +// swagger:model ListProjectV2 +type ListProject struct { + // Project uid + ProjectUid string `json:"uid"` + // Project name + Name string `json:"name"` + // Project is archived + Archived bool `json:"archived"` + // Project desc + Desc string `json:"desc"` + // project business tag + BusinessTag *BusinessTag `json:"business_tag"` + // create user + CreateUser v1.UidWithName `json:"create_user"` + // create time + CreateTime strfmt.DateTime `json:"create_time"` + // project priority + ProjectPriority v1.ProjectPriority `json:"project_priority" enums:"high,medium,low"` +} + +// swagger:model BusinessTagCommon +type BusinessTag struct { + UID string `json:"uid,omitempty"` + // 业务标签最多50个字符 + Name string `json:"name" validate:"max=50"` +} + +// swagger:model ListProjectReplyV2 +type ListProjectReply struct { + // List project reply + Data []*ListProject `json:"data"` + Total int64 `json:"total_nums"` + + // Generic reply + base.GenericResp +} diff --git a/pkg/dms-common/api/dms/v2/router.go b/pkg/dms-common/api/dms/v2/router.go new file mode 100644 index 000000000..fa476c3c7 --- /dev/null +++ b/pkg/dms-common/api/dms/v2/router.go @@ -0,0 +1,27 @@ +package v2 + +import ( + "fmt" + "strings" +) + +// router +var ( + DBServiceRouterGroup = "/dms/projects/:project_uid/db_services" + ProjectRouterGroup = "/dms/projects" + MemberRouterGroup = "/dms/projects/:project_uid/members" +) + +// api group +var ( + GroupV2 = "/v2" + CurrentGroupVersion = GroupV2 +) + +func GetDBServiceRouter(projectUid string) string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, strings.Replace(DBServiceRouterGroup, ":project_uid", projectUid, 1)) +} + +func GetProjectsRouter() string { + return fmt.Sprintf("%s%s", CurrentGroupVersion, ProjectRouterGroup) +} diff --git a/pkg/dms-common/api/jwt/jwt.go b/pkg/dms-common/api/jwt/jwt.go index 73e0aaffc..e72e39aeb 100644 --- a/pkg/dms-common/api/jwt/jwt.go +++ b/pkg/dms-common/api/jwt/jwt.go @@ -1,12 +1,14 @@ package jwt import ( + "errors" "fmt" "strconv" "time" dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/internal/dms/pkg/constant" jwtOld "github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt/v4" ) @@ -16,23 +18,85 @@ type EchoContextGetter interface { Get(key string) interface{} } -type myClaims struct { - Uid string `json:"uid"` - jwt.RegisteredClaims +type CustomClaimFunc func(claims jwt.MapClaims) + +const ( + JWTUserId = "uid" + JWTUsername = "name" + JWTExpiredTime = "exp" + JWTAuditPlanName = "apn" + JWTLoginType = "loginType" + JWTType = "typ" + + DefaultDmsTokenExpHours = 2 + DefaultDmsRefreshTokenExpHours = 24 +) + +func GenJwtToken(customClaims ...CustomClaimFunc) (tokenStr string, err error) { + mapClaims := jwt.MapClaims{ + "iss": "actiontech dms", + JWTExpiredTime: jwt.NewNumericDate(time.Now().Add(DefaultDmsTokenExpHours * time.Hour)), + JWTType: constant.DMSToken, + } + + return genJwtToken(mapClaims, customClaims...) } -func GenJwtToken(userUid string) (tokenStr string, err error) { +func GenJwtTokenWithExpirationTime(expiredTime *jwt.NumericDate, customClaims ...CustomClaimFunc) (tokenStr string, err error) { + mapClaims := jwt.MapClaims{ + "iss": "actiontech dms", + JWTExpiredTime: expiredTime, + } + + return genJwtToken(mapClaims, customClaims...) +} - claims := myClaims{ - Uid: userUid, - RegisteredClaims: jwt.RegisteredClaims{ - Issuer: "actiontech dms", - ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), - }, +func GenRefreshToken(customClaims ...CustomClaimFunc) (tokenStr string, err error) { + mapClaims := jwt.MapClaims{ + "iss": "actiontech dms", + JWTExpiredTime: jwt.NewNumericDate(time.Now().Add(DefaultDmsRefreshTokenExpHours * time.Hour)), + JWTType: constant.DMSRefreshToken, } + return genJwtToken(mapClaims, customClaims...) +} + +func ParseRefreshToken(tokenStr string) (userUid, sub, sid string, expired bool, err error) { + token, err := parseJwtTokenStr(tokenStr) + if err != nil { + var validationErr *jwt.ValidationError + if errors.As(err, &validationErr) && validationErr.Errors&jwt.ValidationErrorExpired != 0 { + expired = true + } else { + return "", "", "", false, err + } + } + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return "", "", "", expired, fmt.Errorf("failed to convert token claims to jwt") + } + + if fmt.Sprint(claims[JWTType]) != constant.DMSRefreshToken { + return "", "", "", expired, fmt.Errorf("invalid jwt type") + } + + userUid, _ = claims[JWTUserId].(string) + if userUid == "" { + return "", "", "", expired, fmt.Errorf("failed to parse user id: empty userUid") + } + sub, _ = claims["sub"].(string) + sid, _ = claims["sid"].(string) + + return userUid, sub, sid, expired, nil +} + +func genJwtToken(mapClaims jwt.MapClaims, customClaims ...CustomClaimFunc) (tokenStr string, err error) { + for _, claimFunc := range customClaims { + claimFunc(mapClaims) + } + mapClaims["iat"] = jwt.NewNumericDate(time.Now()) // Create token with claims - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + token := jwt.NewWithClaims(jwt.SigningMethodHS256, mapClaims) // Generate encoded token and send it as response. tokenStr, err = token.SignedString(dmsCommonV1.JwtSigningKey) @@ -42,27 +106,134 @@ func GenJwtToken(userUid string) (tokenStr string, err error) { return tokenStr, nil } +func WithUserId(userId string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTUserId] = userId + } +} + +func WithJTWType(typ string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTType] = typ + } +} + +func WithUserName(name string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTUsername] = name + } +} + +func WithAuditPlanName(name string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTAuditPlanName] = name + } +} + +func WithExpiredTime(duration time.Duration) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTExpiredTime] = jwt.NewNumericDate(time.Now().Add(duration)) + } +} + +func WithAccessTokenMark(loginType string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims[JWTLoginType] = loginType + } +} + +func WithSub(sub string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims["sub"] = sub + } +} + +func WithSid(sid string) CustomClaimFunc { + return func(claims jwt.MapClaims) { + claims["sid"] = sid + } +} + func ParseUidFromJwtTokenStr(tokenStr string) (uid string, err error) { + token, err := parseJwtTokenStr(tokenStr) + if err != nil { + return "", err + } + + userId, err := ParseUserUidStrFromToken(token) + if err != nil { + return "", fmt.Errorf("get user id from token failed, err: %v", err) + } + + return userId, nil +} + +func parseJwtTokenStr(tokenStr string) (*jwt.Token, error) { token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) { if signMethod256, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + return nil, jwt.ErrSignatureInvalid } else if signMethod256 != jwt.SigningMethodHS256 { - return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + return nil, jwt.ErrSignatureInvalid } return dmsCommonV1.JwtSigningKey, nil }) - if err != nil { - return "", fmt.Errorf("parse token failed: %v", err) + return token, fmt.Errorf("parse token failed: %w", err) } - userId, err := ParseUserUidStrFromToken(token) + return token, nil +} + +// ParseAuditPlanName used by echo middleware which only verify api request to audit plan related. +func ParseAuditPlanName(tokenStr string) (string, error) { + token, err := parseJwtTokenStr(tokenStr) if err != nil { - return "", fmt.Errorf("get user id from token failed, err: %v", err) + return "", err } - return userId, nil + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return "", fmt.Errorf("failed to convert token claims to jwt") + } + + auditPlanName, ok := claims[JWTAuditPlanName] + if !ok { + return "", jwt.NewValidationError("unknown token", jwt.ValidationErrorClaimsInvalid) + } + + return fmt.Sprintf("%v", auditPlanName), nil +} + +// 获取token的过期时间 +func ParseExpiredTimeFromJwtTokenStr(tokenStr string) (expiredTime int64, err error) { + // 使用自定义解析器,跳过过期验证 + parser := jwt.NewParser(jwt.WithoutClaimsValidation()) + token, err := parser.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) { + if signMethod256, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, jwt.ErrSignatureInvalid + } else if signMethod256 != jwt.SigningMethodHS256 { + return nil, jwt.ErrSignatureInvalid + } + + return dmsCommonV1.JwtSigningKey, nil + }) + if err != nil { + return 0, fmt.Errorf("parse token failed: %w", err) + } + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return 0, fmt.Errorf("failed to convert token claims to jwt") + } + expiredTimeStr, ok := claims[JWTExpiredTime] + if !ok { + return 0, jwt.NewValidationError("unknown token", jwt.ValidationErrorClaimsInvalid) + } + expiredTimeInt, ok := expiredTimeStr.(float64) + if !ok { + return 0, jwt.NewValidationError("unknown token", jwt.ValidationErrorClaimsInvalid) + } + return int64(expiredTimeInt), nil } func GetUserFromContext(c EchoContextGetter) (uid int64, err error) { @@ -122,7 +293,8 @@ func ParseUserUidStrFromToken(token *jwt.Token) (uid string, err error) { if !ok { return "", fmt.Errorf("failed to convert token claims to jwt") } - uidStr := fmt.Sprintf("%v", claims["uid"]) + + uidStr := fmt.Sprintf("%v", claims[JWTUserId]) if uidStr == "" { return "", fmt.Errorf("failed to parse user id: empty uid") } @@ -134,9 +306,85 @@ func ParseUserUidStrFromTokenWithOldJwt(token *jwtOld.Token) (uid string, err er if !ok { return "", fmt.Errorf("failed to convert token claims to jwt") } - uidStr := fmt.Sprintf("%v", claims["uid"]) + uidStr := fmt.Sprintf("%v", claims[JWTUserId]) if uidStr == "" { return "", fmt.Errorf("failed to parse user id: empty uid") } return uidStr, nil } + +type TokenDetail struct { + TokenStr string + UID string + LoginType string +} + +// 由于sqle使用的github.com/golang-jwt/jwt,本方法为sqle兼容 +func GetTokenDetailFromContextWithOldJwt(c EchoContextGetter) (tokenDetail *TokenDetail, err error) { + tokenDetail = &TokenDetail{} + + if c.Get("user") == nil { + return tokenDetail, nil + } + + // Gets user token from the context. + u, ok := c.Get("user").(*jwtOld.Token) + if !ok { + return nil, fmt.Errorf("failed to convert user from jwt token") + } + tokenDetail.TokenStr = u.Raw + + // get uid from token + uid, err := ParseUserUidStrFromTokenWithOldJwt(u) + if err != nil { + return nil, err + } + tokenDetail.UID = uid + + // get login type from token + claims, ok := u.Claims.(jwtOld.MapClaims) + if !ok { + return nil, fmt.Errorf("failed to convert token claims to jwt") + } + loginType, ok := claims[JWTLoginType] + if !ok { + return tokenDetail, nil + } + + tokenDetail.LoginType = fmt.Sprint(loginType) + return tokenDetail, nil +} + +func GetTokenDetailFromContext(c EchoContextGetter) (tokenDetail *TokenDetail, err error) { + tokenDetail = &TokenDetail{} + if c.Get("user") == nil { + return tokenDetail, nil + } + + // Gets user token from the context. + u, ok := c.Get("user").(*jwt.Token) + if !ok { + return nil, fmt.Errorf("failed to convert user from jwt token") + } + tokenDetail.TokenStr = u.Raw + + // get uid from token + uid, err := ParseUserUidStrFromToken(u) + if err != nil { + return nil, err + } + tokenDetail.UID = uid + + // get login type from token + claims, ok := u.Claims.(jwt.MapClaims) + if !ok { + return nil, fmt.Errorf("failed to convert token claims to jwt") + } + loginType, ok := claims[JWTLoginType] + if !ok { + return tokenDetail, nil + } + + tokenDetail.LoginType = fmt.Sprint(loginType) + return tokenDetail, nil +} diff --git a/pkg/dms-common/api/jwt/jwt_test.go b/pkg/dms-common/api/jwt/jwt_test.go index a0ed7679b..a45c8919b 100644 --- a/pkg/dms-common/api/jwt/jwt_test.go +++ b/pkg/dms-common/api/jwt/jwt_test.go @@ -9,7 +9,7 @@ import ( ) func TestGenJwtToken(t *testing.T) { - token, err := GenJwtToken("999999") + token, err := GenJwtToken(WithUserId("999999")) if err != nil { t.Errorf("failed to sign the token: %v", err) } diff --git a/pkg/dms-common/conf/options.go b/pkg/dms-common/conf/options.go new file mode 100644 index 000000000..c11b88974 --- /dev/null +++ b/pkg/dms-common/conf/options.go @@ -0,0 +1,28 @@ +package conf + +import "fmt" + +type BaseOptions struct { + ID int64 `yaml:"id" validate:"required"` + APIServiceOpts *APIServerOpts `yaml:"api"` + SecretKey string `yaml:"secret_key"` + ServerId string `yaml:"server_id"` + ReportHost string `yaml:"report_host"` //the host name or IP address of the cluster node + EnableClusterMode bool `yaml:"enable_cluster_mode"` +} + +type APIServerOpts struct { + Addr string `yaml:"addr" validate:"required"` + Port int `yaml:"port" validate:"required"` + EnableHttps bool `yaml:"enable_https"` + CertFilePath string `yaml:"cert_file_path"` + KeyFilePath string `yaml:"key_file_path"` +} + +func (o *BaseOptions) GetAPIServer() *APIServerOpts { + return o.APIServiceOpts +} + +func (api *APIServerOpts) GetHTTPAddr() string { + return fmt.Sprintf("%v:%v", api.Addr, api.Port) +} diff --git a/pkg/dms-common/dmsobject/data_export_workflow.go b/pkg/dms-common/dmsobject/data_export_workflow.go new file mode 100644 index 000000000..9f95d1d1a --- /dev/null +++ b/pkg/dms-common/dmsobject/data_export_workflow.go @@ -0,0 +1,74 @@ +package dmsobject + +import ( + "context" + "fmt" + "net/url" + + dmsCommonV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func GetGlobalDataExportWorkflowsList(ctx context.Context, dmsAddr string, req dmsCommonV1.FilterGlobalDataExportWorkflowReq) ([]*dmsCommonV1.ListDataExportWorkflow, int64, error) { + + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + // 构建基础 URL + baseURL, err := url.Parse(fmt.Sprintf("%s%s", dmsAddr, dmsCommonV1.GetGlobalDataExportWorkflowsRouter())) + if err != nil { + return nil, 0, fmt.Errorf("failed to parse base URL: %v", err) + } + + // 构建查询参数 + query := url.Values{} + query.Set("page_size", fmt.Sprintf("%d", req.PageSize)) + query.Set("page_index", fmt.Sprintf("%d", req.PageIndex)) + + if req.FilterByCreateUserUid != "" { + query.Set("filter_by_create_user_uid", req.FilterByCreateUserUid) + } + + if len(req.FilterStatusList) > 0 { + for _, v := range req.FilterStatusList { + if v != "" { + query.Add("filter_status_list", string(v)) + } + } + } + + if len(req.FilterProjectUids) > 0 { + for _, v := range req.FilterProjectUids { + if v != "" { + query.Add("filter_project_uids", v) + } + } + } + + if req.FilterProjectUid != "" { + query.Set("filter_project_uid", req.FilterProjectUid) + } + + if req.FilterDBServiceUid != "" { + query.Set("filter_db_service_uid", req.FilterDBServiceUid) + } + + if req.FilterCurrentStepAssigneeUserId != "" { + query.Set("filter_current_step_assignee_user_id", req.FilterCurrentStepAssigneeUserId) + } + + // 将查询参数附加到 URL + baseURL.RawQuery = query.Encode() + + // 调用 HTTP GET 请求 + reply := &dmsCommonV1.ListDataExportWorkflowsReply{} + if err := pkgHttp.Get(ctx, baseURL.String(), header, nil, reply); err != nil { + return nil, 0, err + } + if reply.Code != 0 { + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, reply.Total, nil +} diff --git a/pkg/dms-common/dmsobject/db_service.go b/pkg/dms-common/dmsobject/db_service.go new file mode 100644 index 000000000..29f503384 --- /dev/null +++ b/pkg/dms-common/dmsobject/db_service.go @@ -0,0 +1,73 @@ +package dmsobject + +import ( + "context" + "fmt" + "net/url" + + dmsCommonV2 "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func ListDbServices(ctx context.Context, dmsAddr string, req dmsCommonV2.ListDBServiceReq) ([]*dmsCommonV2.ListDBService, int64, error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + // 构建基础 URL + baseURL, err := url.Parse(fmt.Sprintf("%s%s", dmsAddr, dmsCommonV2.GetDBServiceRouter(req.ProjectUid))) + if err != nil { + return nil, 0, fmt.Errorf("failed to parse base URL: %v", err) + } + + // 构建查询参数 + query := url.Values{} + query.Set("page_size", fmt.Sprintf("%d", req.PageSize)) + query.Set("page_index", fmt.Sprintf("%d", req.PageIndex)) + + if req.OrderBy != "" { + query.Set("order_by", fmt.Sprintf("%v", req.OrderBy)) + } + if req.FilterByEnvironmentTagUID != "" { + query.Set("filter_by_environment_tag_uid", req.FilterByEnvironmentTagUID) + } + if req.FilterByHost != "" { + query.Set("filter_by_host", req.FilterByHost) + } + if req.FilterByUID != "" { + query.Set("filter_by_uid", req.FilterByUID) + } + if req.FilterByName != "" { + query.Set("filter_by_name", req.FilterByName) + } + if req.FilterByPort != "" { + query.Set("filter_by_port", req.FilterByPort) + } + if req.FilterByDBType != "" { + query.Set("filter_by_db_type", req.FilterByDBType) + } + if req.FuzzyKeyword != "" { + query.Set("fuzzy_keyword", req.FuzzyKeyword) + } + if req.IsEnableMasking != nil { + query.Set("is_enable_masking", fmt.Sprintf("%t", *req.IsEnableMasking)) + } + + for _, id := range req.FilterByDBServiceIds { + query.Add("filter_by_db_service_ids", id) + } + + // 将查询参数附加到 URL + baseURL.RawQuery = query.Encode() + + // 调用 HTTP GET 请求 + reply := &dmsCommonV2.ListDBServiceReply{} + if err := pkgHttp.Get(ctx, baseURL.String(), header, nil, reply); err != nil { + return nil, 0, err + } + if reply.Code != 0 { + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, reply.Total, nil +} diff --git a/pkg/dms-common/dmsobject/namespace.go b/pkg/dms-common/dmsobject/namespace.go deleted file mode 100644 index 2d23bc24f..000000000 --- a/pkg/dms-common/dmsobject/namespace.go +++ /dev/null @@ -1,28 +0,0 @@ -package dmsobject - -import ( - "context" - "fmt" - - dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" - pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" -) - -func ListNamespaces(ctx context.Context, dmsAddr string, req dmsV1.ListNamespaceReq) (ret []*dmsV1.ListNamespace, total int64, err error) { - header := map[string]string{ - "Authorization": pkgHttp.DefaultDMSToken, - } - - reply := &dmsV1.ListNamespaceReply{} - - url := fmt.Sprintf("%v%v?page_size=%v&page_index=%v&filter_by_name=%v&filter_by_uid=%v", dmsAddr, dmsV1.GetNamespacesRouter(), req.PageSize, req.PageIndex, req.FilterByName, req.FilterByUID) - - if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { - return nil, 0, fmt.Errorf("failed to list namespace from %v: %v", url, err) - } - if reply.Code != 0 { - return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) - } - - return reply.Payload.Namespaces, reply.Payload.Total, nil -} diff --git a/pkg/dms-common/dmsobject/notify.go b/pkg/dms-common/dmsobject/notify.go index 51137bd26..9dbe2e9b3 100644 --- a/pkg/dms-common/dmsobject/notify.go +++ b/pkg/dms-common/dmsobject/notify.go @@ -20,7 +20,7 @@ func Notify(ctx context.Context, dmsAddr string, req dmsV1.NotificationReq) (err return fmt.Errorf("failed to notify by %v: %v", url, err) } if reply.Code != 0 { - return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } return nil diff --git a/pkg/dms-common/dmsobject/plugin.go b/pkg/dms-common/dmsobject/plugin.go new file mode 100644 index 000000000..446a854ca --- /dev/null +++ b/pkg/dms-common/dmsobject/plugin.go @@ -0,0 +1,39 @@ +package dmsobject + +import ( + "context" + "reflect" + + "github.com/iancoleman/strcase" +) + +var operateHandlers map[string]OperationHandler = make(map[string]OperationHandler) + +// OperationHandler NOTE: +// The implemented structure must be named[CamelCase] by the combination of DataResourceType, OperationType, and OperationTimingType +type OperationHandler interface { + Handle(ctx context.Context, currentUserId string, objId string, extraParams string) error +} + +type DefaultOperateHandle struct { +} + +func (f DefaultOperateHandle) Handle(ctx context.Context, currentUserId string, objId string, extraParams string) error { + return nil +} + +func InitOperateHandlers(operationHandlers []OperationHandler) { + for _, v := range operationHandlers { + structName := strcase.ToSnake(reflect.TypeOf(v).Name()) + operateHandlers[structName] = v + } +} + +func GetOperateHandle(name string) OperationHandler { + handle, ok := operateHandlers[name] + if ok { + return handle + } + + return DefaultOperateHandle{} +} diff --git a/pkg/dms-common/dmsobject/project.go b/pkg/dms-common/dmsobject/project.go new file mode 100644 index 000000000..21f6aab6b --- /dev/null +++ b/pkg/dms-common/dmsobject/project.go @@ -0,0 +1,52 @@ +package dmsobject + +import ( + "context" + "fmt" + "net/url" + + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + dmsV2 "github.com/actiontech/dms/pkg/dms-common/api/dms/v2" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +func ListProjects(ctx context.Context, dmsAddr string, req dmsV1.ListProjectReq) (ret []*dmsV1.ListProject, total int64, err error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.ListProjectReply{} + + baseURL, err := url.Parse(fmt.Sprintf("%v%v", dmsAddr, dmsV2.GetProjectsRouter())) + if err != nil { + return nil, 0, fmt.Errorf("failed to parse base URL: %v", err) + } + // 构建查询参数 + query := url.Values{} + query.Set("page_size", fmt.Sprintf("%v", req.PageSize)) + query.Set("page_index", fmt.Sprintf("%v", req.PageIndex)) + + if req.FilterByName != "" { + query.Set("filter_by_name", req.FilterByName) + } + if req.FilterByUID != "" { + query.Set("filter_by_uid", req.FilterByUID) + } + if req.FilterByProjectPriority != "" { + query.Set("filter_by_project_priority", string(req.FilterByProjectPriority)) + } + for _, projectUid := range req.FilterByProjectUids { + query.Add("filter_by_project_uids", projectUid) + } + + baseURL.RawQuery = query.Encode() + + if err := pkgHttp.Get(ctx, baseURL.String(), header, nil, reply); err != nil { + return nil, 0, fmt.Errorf("failed to list project from %v: %v", baseURL.String(), err) + } + if reply.Code != 0 { + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, reply.Total, nil +} diff --git a/pkg/dms-common/dmsobject/system_variable.go b/pkg/dms-common/dmsobject/system_variable.go new file mode 100644 index 000000000..176e101c1 --- /dev/null +++ b/pkg/dms-common/dmsobject/system_variable.go @@ -0,0 +1,64 @@ +package dmsobject + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + + baseV1 "github.com/actiontech/dms/pkg/dms-common/api/base/v1" + dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" +) + +// GetSystemVariables 获取系统变量配置 +func GetSystemVariables(ctx context.Context, dmsAddr string) (*dmsV1.GetSystemVariablesReply, error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + // 构建基础 URL + baseURL, err := url.Parse(fmt.Sprintf("%s/v1/dms/configurations/system_variables", dmsAddr)) + if err != nil { + return nil, fmt.Errorf("failed to parse base URL: %v", err) + } + + // 调用 HTTP GET 请求 + reply := &dmsV1.GetSystemVariablesReply{} + if err := pkgHttp.Get(ctx, baseURL.String(), header, nil, reply); err != nil { + return nil, err + } + if reply.Code != 0 { + return nil, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply, nil +} + +// UpdateSystemVariables 更新系统变量配置 +func UpdateSystemVariables(ctx context.Context, dmsAddr string, req *dmsV1.UpdateSystemVariablesReqV1) error { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + // 构建基础 URL + baseURL, err := url.Parse(fmt.Sprintf("%s/v1/dms/configurations/system_variables", dmsAddr)) + if err != nil { + return fmt.Errorf("failed to parse base URL: %v", err) + } + + // 调用 HTTP PATCH 请求 + reqBody, err := json.Marshal(req) + if err != nil { + return fmt.Errorf("marshal error: %v", err) + } + reply := &baseV1.GenericResp{} + if err := pkgHttp.Call(ctx, "PATCH", baseURL.String(), header, "application/json", reqBody, reply); err != nil { + return err + } + if reply.Code != 0 { + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return nil +} diff --git a/pkg/dms-common/dmsobject/user.go b/pkg/dms-common/dmsobject/user.go index d0d09847e..015a14a03 100644 --- a/pkg/dms-common/dmsobject/user.go +++ b/pkg/dms-common/dmsobject/user.go @@ -3,6 +3,8 @@ package dmsobject import ( "context" "fmt" + "net/url" + "strconv" dmsV1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" pkgHttp "github.com/actiontech/dms/pkg/dms-common/pkg/http" @@ -21,13 +23,32 @@ func GetUser(ctx context.Context, userUid string, dmsAddr string) (*dmsV1.GetUse return nil, fmt.Errorf("failed to get user from %v: %v", url, err) } if reply.Code != 0 { - return nil, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return nil, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } - return reply.Payload.User, nil + return reply.Data, nil } -func GetUserOpPermission(ctx context.Context, namespaceUid, userUid, dmsAddr string) (ret []dmsV1.OpPermissionItem, isAdmin bool, err error) { +func GetMemberGroup(ctx context.Context, memberGroupUid, projectUid string, dmsAddr string) (*dmsV1.GetMemberGroup, error) { + header := map[string]string{ + "Authorization": pkgHttp.DefaultDMSToken, + } + + reply := &dmsV1.GetMemberGroupReply{} + + url := fmt.Sprintf("%v%v", dmsAddr, dmsV1.GetMemberGroupRouter(memberGroupUid, projectUid)) + + if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { + return nil, fmt.Errorf("failed to get member group from %v: %v", url, err) + } + if reply.Code != 0 { + return nil, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) + } + + return reply.Data, nil +} + +func GetUserOpPermission(ctx context.Context, projectUid, userUid, dmsAddr string) (ret []dmsV1.OpPermissionItem, isAdmin bool, err error) { header := map[string]string{ "Authorization": pkgHttp.DefaultDMSToken, } @@ -35,7 +56,7 @@ func GetUserOpPermission(ctx context.Context, namespaceUid, userUid, dmsAddr str reqBody := struct { UserOpPermission *dmsV1.UserOpPermission `json:"user_op_permission"` }{ - UserOpPermission: &dmsV1.UserOpPermission{NamespaceUid: namespaceUid}, + UserOpPermission: &dmsV1.UserOpPermission{ProjectUid: projectUid}, } reply := &dmsV1.GetUserOpPermissionReply{} @@ -46,31 +67,30 @@ func GetUserOpPermission(ctx context.Context, namespaceUid, userUid, dmsAddr str return nil, false, fmt.Errorf("failed to get user op permission from %v: %v", url, err) } if reply.Code != 0 { - return nil, false, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return nil, false, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } - return reply.Payload.OpPermissionList, reply.Payload.IsAdmin, nil + return reply.Data.OpPermissionList, reply.Data.IsAdmin, nil } -func ListMembersInNamespace(ctx context.Context, dmsAddr string, req dmsV1.ListMembersForInternalReq) ([]*dmsV1.ListMembersForInternalItem, int64, error) { +func ListMembersInProject(ctx context.Context, dmsAddr string, req dmsV1.ListMembersForInternalReq) ([]*dmsV1.ListMembersForInternalItem, int64, error) { header := map[string]string{ "Authorization": pkgHttp.DefaultDMSToken, } reply := &dmsV1.ListMembersForInternalReply{} - url := fmt.Sprintf("%v%v?page_size=%v&page_index=%v&namespace_uid=%v", - dmsAddr, dmsV1.GetListMembersForInternalRouter(), req.PageSize, req.PageIndex, req.NamespaceUid) + url := fmt.Sprintf("%v%v?page_size=%v&page_index=%v", dmsAddr, dmsV1.GetListMembersForInternalRouter(req.ProjectUid), req.PageSize, req.PageIndex) if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { return nil, 0, fmt.Errorf("failed to get member from %v: %v", url, err) } if reply.Code != 0 { - return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } - return reply.Payload.Members, reply.Payload.Total, nil + return reply.Data, reply.Total, nil } func ListUsers(ctx context.Context, dmsAddr string, req dmsV1.ListUserReq) (ret []*dmsV1.ListUser, total int64, err error) { @@ -80,15 +100,52 @@ func ListUsers(ctx context.Context, dmsAddr string, req dmsV1.ListUserReq) (ret reply := &dmsV1.ListUserReply{} - url := fmt.Sprintf("%v%v?page_size=%v&page_index=%v&filter_del_user=%v&filter_by_uids=%v", dmsAddr, dmsV1.GetUsersRouter(), req.PageSize, req.PageIndex, req.FilterDeletedUser, req.FilterByUids) + // 构建查询参数 + params := url.Values{} + params.Set("page_size", strconv.FormatUint(uint64(req.PageSize), 10)) + if req.PageIndex > 0 { + params.Set("page_index", strconv.FormatUint(uint64(req.PageIndex), 10)) + } + if req.OrderBy != "" { + params.Set("order_by", string(req.OrderBy)) + } + if req.FilterByName != "" { + params.Set("filter_by_name", req.FilterByName) + } + if req.FilterByUids != "" { + params.Set("filter_by_uids", req.FilterByUids) + } + if req.FilterDeletedUser { + params.Set("filter_del_user", "true") + } + if req.FuzzyKeyword != "" { + params.Set("fuzzy_keyword", req.FuzzyKeyword) + } + if req.FilterByEmail != "" { + params.Set("filter_by_email", req.FilterByEmail) + } + if req.FilterByPhone != "" { + params.Set("filter_by_phone", req.FilterByPhone) + } + if req.FilterByStat != "" { + params.Set("filter_by_stat", string(req.FilterByStat)) + } + if req.FilterByAuthenticationType != "" { + params.Set("filter_by_authentication_type", string(req.FilterByAuthenticationType)) + } + if req.FilterBySystem != "" { + params.Set("filter_by_system", string(req.FilterBySystem)) + } - if err := pkgHttp.Get(ctx, url, header, nil, reply); err != nil { - return nil, 0, fmt.Errorf("failed to list users from %v: %v", url, err) + requestURL := fmt.Sprintf("%v%v?%v", dmsAddr, dmsV1.GetUsersRouter(), params.Encode()) + + if err := pkgHttp.Get(ctx, requestURL, header, nil, reply); err != nil { + return nil, 0, fmt.Errorf("failed to list users from %v: %v", requestURL, err) } if reply.Code != 0 { - return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return nil, 0, fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } - return reply.Payload.Users, reply.Payload.Total, nil + return reply.Data, reply.Total, nil } diff --git a/pkg/dms-common/dmsobject/webhooks.go b/pkg/dms-common/dmsobject/webhooks.go index d1db781a1..e8631b2bb 100644 --- a/pkg/dms-common/dmsobject/webhooks.go +++ b/pkg/dms-common/dmsobject/webhooks.go @@ -20,7 +20,7 @@ func WebHookSendMessage(ctx context.Context, dmsAddr string, req *dmsV1.WebHookS return fmt.Errorf("failed to notify by %v: %v", url, err) } if reply.Code != 0 { - return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } return nil diff --git a/pkg/dms-common/i18nPkg/bundle.go b/pkg/dms-common/i18nPkg/bundle.go new file mode 100644 index 000000000..96c0de9ab --- /dev/null +++ b/pkg/dms-common/i18nPkg/bundle.go @@ -0,0 +1,193 @@ +package i18nPkg + +import ( + "context" + "fmt" + "io/fs" + "runtime/debug" + "strings" + + "github.com/BurntSushi/toml" + "github.com/labstack/echo/v4" + "github.com/nicksnyder/go-i18n/v2/i18n" + "golang.org/x/text/language" +) + +const ( + LocalizerCtxKey = "localizer" + AcceptLanguageKey = "Accept-Language" +) + +var DefaultLang = language.Chinese + +func NewBundleFromTomlDir(fsys fs.FS, log Log) (*Bundle, error) { + if log == nil { + log = &StdLogger{} + } + b := &Bundle{ + Bundle: i18n.NewBundle(DefaultLang), + localizers: nil, + logger: log, + } + b.Bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) + + err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || !strings.HasSuffix(d.Name(), "toml") { + return nil + } + _, err = b.Bundle.LoadMessageFileFS(fsys, path) + return err + }) + if err != nil { + return nil, err + } + + b.localizers = make(map[language.Tag]*i18n.Localizer, len(b.Bundle.LanguageTags())) + for _, tag := range b.Bundle.LanguageTags() { + b.localizers[tag] = i18n.NewLocalizer(b.Bundle, tag.String()) + } + + return b, nil +} + +type Bundle struct { + *i18n.Bundle + localizers map[language.Tag]*i18n.Localizer + logger Log +} + +func (b *Bundle) DefaultLocalizer() *i18n.Localizer { + return b.localizers[DefaultLang] +} + +func (b *Bundle) GetLocalizer(tag language.Tag) *i18n.Localizer { + if localizer, ok := b.localizers[tag]; ok { + return localizer + } + return b.DefaultLocalizer() +} + +func (b *Bundle) localizeMsg(localizer *i18n.Localizer, msg *i18n.Message) string { + if msg == nil { + stack := debug.Stack() + b.logger.Errorf("i18nPkg localize nil msg, %s", stack) + return "" + } + m, err := localizer.LocalizeMessage(msg) + if err != nil { + b.logger.Errorf("i18nPkg LocalizeMessage %v failed: %v", msg.ID, err) + } + return m +} + +func (b *Bundle) LocalizeMsgByCtx(ctx context.Context, msg *i18n.Message) string { + l, ok := ctx.Value(LocalizerCtxKey).(*i18n.Localizer) + if !ok { + l = b.DefaultLocalizer() + b.logger.Errorf("i18nPkg No localizer in context when localize msg: %v, use default", msg) + } + + return b.localizeMsg(l, msg) +} + +func (b *Bundle) LocalizeMsgByLang(lang language.Tag, msg *i18n.Message) string { + l := b.GetLocalizer(lang) + return b.localizeMsg(l, msg) +} + +func (b *Bundle) LocalizeAll(msg *i18n.Message) I18nStr { + result := make(I18nStr, len(b.localizers)) + for langTag, localizer := range b.localizers { + result[langTag] = b.localizeMsg(localizer, msg) + } + return result +} + +// LocalizeAllWithArgs if there is any i18n.Message or I18nStr in args, it will be Localized in the corresponding language too +func (b *Bundle) LocalizeAllWithArgs(fmtMsg *i18n.Message, args ...any) I18nStr { + result := make(I18nStr, len(b.localizers)) + msgs := map[int]*i18n.Message{} + i18nStrs := map[int]*I18nStr{} + for k, v := range args { + switch arg := v.(type) { + case i18n.Message: + msgs[k] = &arg + case *i18n.Message: + msgs[k] = arg + case I18nStr: + i18nStrs[k] = &arg + case *I18nStr: + i18nStrs[k] = arg + default: + } + } + for langTag, localizer := range b.localizers { + for k := range msgs { + args[k] = b.localizeMsg(localizer, msgs[k]) + } + for k := range i18nStrs { + args[k] = i18nStrs[k].GetStrInLang(langTag) + } + result[langTag] = fmt.Sprintf(b.localizeMsg(localizer, fmtMsg), args...) + } + return result +} + +func GetLangByAcceptLanguage(c echo.Context) string { + return c.Request().Header.Get(AcceptLanguageKey) +} + +func (b *Bundle) EchoMiddlewareByCustomFunc(getLang ...func(c echo.Context) string) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + var acceptLang string + for _, f := range getLang { + if lang := f(c); lang != "" { + acceptLang = lang + break + } + } + langTag := b.MatchLangTag(acceptLang) + ctx := context.WithValue(c.Request().Context(), LocalizerCtxKey, b.localizers[langTag]) + ctx = context.WithValue(ctx, AcceptLanguageKey, langTag) + c.SetRequest(c.Request().WithContext(ctx)) + return next(c) + } + } +} + +func (b *Bundle) MatchLangTag(s string) language.Tag { + langTag := DefaultLang + for _, lang := range b.Bundle.LanguageTags() { + if strings.HasPrefix(s, lang.String()) { + langTag = lang + break + } + } + return langTag +} + +func (b *Bundle) JoinI18nStr(elems []I18nStr, sep string) I18nStr { + var result = make(I18nStr, len(b.LanguageTags())) + for _, langTag := range b.LanguageTags() { + var langStr []string + for _, v := range elems { + langStr = append(langStr, v.GetStrInLang(langTag)) + } + result.SetStrInLang(langTag, strings.Join(langStr, sep)) + } + return result +} + +func (b *Bundle) GetLangTagFromCtx(ctx context.Context) language.Tag { + al, ok := ctx.Value(AcceptLanguageKey).(language.Tag) + if ok { + if _, ok = b.localizers[al]; ok { + return al + } + } + return DefaultLang +} diff --git a/pkg/dms-common/i18nPkg/i18nStr.go b/pkg/dms-common/i18nPkg/i18nStr.go new file mode 100644 index 000000000..82b80deca --- /dev/null +++ b/pkg/dms-common/i18nPkg/i18nStr.go @@ -0,0 +1,96 @@ +package i18nPkg + +import ( + "database/sql/driver" + "encoding/json" + "fmt" + + "golang.org/x/text/language" +) + +func ConvertStr2I18nAsDefaultLang(s string) I18nStr { + if s == "" { + return nil + } + return map[language.Tag]string{DefaultLang: s} +} + +func ConvertStrMap2I18nStr(s map[string]string) (I18nStr, error) { + if len(s) == 0 { + return nil, nil + } + if _, exist := s[DefaultLang.String()]; !exist { + return nil, fmt.Errorf("must contains DefaultLang:%s", DefaultLang.String()) + } + i := make(I18nStr, len(s)) + for lang, v := range s { + langTag, err := language.Parse(lang) + if err != nil { + return nil, fmt.Errorf("parse key:%s err:%v", lang, err) + } + i[langTag] = v + } + return i, nil +} + +type I18nStr map[language.Tag]string + +// GetStrInLang if the lang not exists, return DefaultLang +func (s *I18nStr) GetStrInLang(lang language.Tag) string { + if s == nil || *s == nil { + return "" + } + if str, exist := (*s)[lang]; exist { + return str + } + return (*s)[DefaultLang] +} + +func (s *I18nStr) SetStrInLang(lang language.Tag, str string) { + if *s == nil { + *s = map[language.Tag]string{lang: str} + } else { + (*s)[lang] = str + } + return +} + +func (s *I18nStr) StrMap() map[string]string { + if s == nil || *s == nil { + return map[string]string{} + } + m := make(map[string]string, len(*s)) + for langTag, v := range *s { + m[langTag.String()] = v + } + return m +} + +func (s *I18nStr) Copy() I18nStr { + if s == nil || *s == nil { + return nil + } + i := make(I18nStr, len(*s)) + for k, v := range *s { + i[k] = v + } + return i +} + +// Value impl sql. driver.Valuer interface +func (s I18nStr) Value() (driver.Value, error) { + b, err := json.Marshal(s) + return string(b), err +} + +// Scan impl sql.Scanner interface +func (s *I18nStr) Scan(input interface{}) error { + if input == nil { + return nil + } + if data, ok := input.([]byte); !ok { + return fmt.Errorf("I18nStr Scan input is not bytes") + } else { + return json.Unmarshal(data, s) + } +} diff --git a/pkg/dms-common/i18nPkg/log.go b/pkg/dms-common/i18nPkg/log.go new file mode 100644 index 000000000..e088692dd --- /dev/null +++ b/pkg/dms-common/i18nPkg/log.go @@ -0,0 +1,16 @@ +package i18nPkg + +import ( + "fmt" + "os" +) + +type Log interface { + Errorf(string, ...any) +} + +type StdLogger struct{} + +func (l *StdLogger) Errorf(s string, args ...any) { + fmt.Fprintf(os.Stdout, "[Error] "+s, args...) +} diff --git a/pkg/dms-common/pkg/aes/aes.go b/pkg/dms-common/pkg/aes/aes.go index ebc1c0750..34ad7e36e 100644 --- a/pkg/dms-common/pkg/aes/aes.go +++ b/pkg/dms-common/pkg/aes/aes.go @@ -31,10 +31,15 @@ func NewEncryptor(key []byte) *encryptor { } } -func (e *encryptor) SetAesSecretKey(key []byte) (err error) { - e.mutex.Lock() - defer e.mutex.Unlock() +func ResetAesSecretKey(secret string) error { + if secret == "" { + return nil + } + return std.SetAesSecretKey([]byte(secret)) +} + +func (e *encryptor) SetAesSecretKey(key []byte) (err error) { origKey := e.SecretKey e.SecretKey = key origData := "test" diff --git a/pkg/dms-common/pkg/config/AUTHORS b/pkg/dms-common/pkg/config/AUTHORS deleted file mode 100644 index f4b30a5c8..000000000 --- a/pkg/dms-common/pkg/config/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -Stephen Weinberg diff --git a/pkg/dms-common/pkg/config/COPYRIGHT b/pkg/dms-common/pkg/config/COPYRIGHT deleted file mode 100644 index f8b9c808b..000000000 --- a/pkg/dms-common/pkg/config/COPYRIGHT +++ /dev/null @@ -1,10 +0,0 @@ -Copyright (c) 2010-2012, Stephen Weinberg -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of goconf nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pkg/dms-common/pkg/config/conf.go b/pkg/dms-common/pkg/config/conf.go deleted file mode 100644 index 370a2dfd7..000000000 --- a/pkg/dms-common/pkg/config/conf.go +++ /dev/null @@ -1,234 +0,0 @@ -// This package implements a parser for configuration files. -// This allows easy reading and writing of structured configuration files. -// -// Given the configuration file: -// -// [default] -// host = example.com -// port = 443 -// php = on -// -// [service-1] -// host = s1.example.com -// allow-writing = false -// -// To read this configuration file, do: -// -// c, err := config.ReadConfigFile("server.conf") -// c.GetString("default", "host") // returns example.com -// c.GetInt("", "port") // returns 443 (assumes "default") -// c.GetBool("", "php") // returns true -// c.GetString("service-1", "host") // returns s1.example.com -// c.GetBool("service-1","allow-writing") // returns false -// c.GetInt("service-1", "port") // returns 0 and a GetError -// -// Note that all section and option names are case insensitive. All values are case -// sensitive. -// -// Goconfig's string substitution syntax has not been removed. However, it may be -// taken out or modified in the future. -package config - -import ( - "fmt" - "strings" -) - -// ConfigFile is the representation of configuration settings. -// The public interface is entirely through methods. -type ConfigFile struct { - data map[string][]*KVData // Maps sections to options to values. - sectionOrder []string // comments and option order -} - -type KVData struct { - key string - value string -} - -const ( - // Get Errors - SectionNotFound = iota - OptionNotFound - MaxDepthReached - - // Read Errors - BlankSection - - // Get and Read Errors - CouldNotParse -) - -const ( - //line category - emptyLine = "emptyline" - commentLine = "commentline" -) -const virtualSection = "virtualsection" //to save comments before first real section eg: comments - -var ( - DefaultSection = "default" // Default section name (must be lower-case). - DepthValues = 200 // Maximum allowed depth when recursively substituing variable names. - - // Strings accepted as bool. - BoolStrings = map[string]bool{ - "t": true, - "true": true, - "y": true, - "yes": true, - "on": true, - "1": true, - "f": false, - "false": false, - "n": false, - "no": false, - "off": false, - "0": false, - "": true, //Only one key is considered as true - } -) - -// AddSection adds a new section to the configuration. -// It returns true if the new section was inserted, and false if the section already existed. -func (c *ConfigFile) AddSection(section string) bool { - section = strings.ToLower(section) - - if _, ok := c.data[section]; ok { - return false - } - - c.data[section] = []*KVData{} - c.sectionOrder = append(c.sectionOrder, section) - return true -} - -// RemoveSection removes a section from the configuration. -// It returns true if the section was removed, and false if section did not exist. -func (c *ConfigFile) RemoveSection(section string) bool { - section = strings.ToLower(section) - - switch _, ok := c.data[section]; { - case !ok: - return false - case section == DefaultSection: - return false // default section cannot be removed - default: - delete(c.data, section) - } - - return true -} - -// AddOption adds a new option and value to the configuration, replace value if key exists by default. -// It returns true if the option and value were inserted, and false if the value was overwritten. -// If the section does not exist in advance, it is created. -// If the section has duplicated options, all options would be overwritten -func (c *ConfigFile) AddOption(section string, option string, value string, replaceArg ...bool) bool { - c.AddSection(section) // make sure section exists - - section = strings.ToLower(section) - option = strings.ToLower(option) - replace := true - if len(replaceArg) != 0 { - replace = replaceArg[0] - } - - if replace { - isOptionExisted := false - for i, kvData := range c.data[section] { - if kvData.key == option && option != emptyLine && - option != commentLine { - isOptionExisted = true - c.data[section][i] = &KVData{ - key: option, - value: value, - } - } - } - - if !isOptionExisted { - c.data[section] = append(c.data[section], &KVData{ - key: option, - value: value, - }) - } - return !isOptionExisted - } - c.data[section] = append(c.data[section], &KVData{ - key: option, - value: value, - }) - return true -} - -// RemoveOption removes a option and value from the configuration. -// It returns true if the option and value were removed, and false otherwise, -// including if the section did not exist. -func (c *ConfigFile) RemoveOption(section string, option string) bool { - section = strings.ToLower(section) - option = strings.ToLower(option) - - if _, ok := c.data[section]; !ok { - return false - } - - kvDatas := c.data[section] - for i := 0; i < len(kvDatas); i++ { - if kvDatas[i].key == option { - kvDatas = append(kvDatas[:i], kvDatas[i+1:]...) - i-- - } - } - c.data[section] = kvDatas - - return true -} - -// NewConfigFile creates an empty configuration representation. -// This representation can be filled with AddSection and AddOption and then -// saved to a file using WriteConfigFile. -func NewConfigFile() *ConfigFile { - c := new(ConfigFile) - c.data = make(map[string][]*KVData) - c.AddSection(DefaultSection) // default section always exists - return c -} - -type GetError struct { - Reason int - ValueType string - Value string - Section string - Option string -} - -func (err GetError) Error() string { - switch err.Reason { - case SectionNotFound: - return fmt.Sprintf("section '%s' not found", err.Section) - case OptionNotFound: - return fmt.Sprintf("option '%s' not found in section '%s'", err.Option, err.Section) - case CouldNotParse: - return fmt.Sprintf("could not parse %s value '%s'", err.ValueType, err.Value) - case MaxDepthReached: - return fmt.Sprintf("possible cycle while unfolding variables: max depth of %d reached", DepthValues) - } - - return "invalid get error" -} - -type ReadError struct { - Reason int - Line string -} - -func (err ReadError) Error() string { - switch err.Reason { - case BlankSection: - return "empty section name not allowed" - case CouldNotParse: - return fmt.Sprintf("could not parse line: %s", err.Line) - } - - return "invalid read error" -} diff --git a/pkg/dms-common/pkg/config/conf_test.go b/pkg/dms-common/pkg/config/conf_test.go deleted file mode 100644 index 15ac7dc10..000000000 --- a/pkg/dms-common/pkg/config/conf_test.go +++ /dev/null @@ -1,190 +0,0 @@ -package config - -import ( - "strconv" - "testing" -) - -const confFile = ` -[default] -host = example.com -port = 43 -compression = on -active = false - -[service-1] -port = 443 -` - -//url = http://%(host)s/something - -type stringtest struct { - section string - option string - answer string -} - -type inttest struct { - section string - option string - answer int -} - -type booltest struct { - section string - option string - answer bool -} - -var testSet = []interface{}{ - stringtest{"", "host", "example.com"}, - inttest{"default", "port", 43}, - booltest{"default", "compression", true}, - booltest{"default", "active", false}, - inttest{"service-1", "port", 443}, - //stringtest{"service-1", "url", "http://example.com/something"}, -} - -func TestBuild(t *testing.T) { - c, err := ReadConfigBytes([]byte(confFile)) - if err != nil { - t.Error(err) - } - - for _, element := range testSet { - switch e := element.(type) { - case stringtest: - ans, err := c.GetString(e.section, e.option) - if err != nil { - t.Error("c.GetString(\"" + e.section + "\",\"" + e.option + "\") returned error: " + err.Error()) - } else if ans != e.answer { - t.Error("c.GetString(\"" + e.section + "\",\"" + e.option + "\") returned incorrect answer: " + ans) - } - case inttest: - ans, err := c.GetInt(e.section, e.option) - if err != nil { - t.Error("c.GetInt(\"" + e.section + "\",\"" + e.option + "\") returned error: " + err.Error()) - } else if ans != e.answer { - t.Error("c.GetInt(\"" + e.section + "\",\"" + e.option + "\") returned incorrect answer: " + strconv.Itoa(ans)) - } - case booltest: - ans, err := c.GetBool(e.section, e.option) - if err != nil { - t.Error("c.GetBool(\"" + e.section + "\",\"" + e.option + "\") returned error: " + err.Error()) - } else if ans != e.answer { - t.Error("c.GetBool(\"" + e.section + "\",\"" + e.option + "\") returned incorrect answer") - } - } - } -} - -var ( - byteConfigForTest = `[default1] -host = something.com -port = 443 -active = true -compression = off - -[service-2] -port = 444 -skip_lock -fake_key = value1 -host = something.com -fake_key = value - -[service-1]#comment1 -compression = on -` -) - -func TestRemoveOption(t *testing.T) { - t.Logf("conf is like before :\n%v\n", byteConfigForTest) - conf, err := ReadConfigBytes([]byte(byteConfigForTest)) - assertNoError(t, err) - success := conf.RemoveOption("service-2", "fake_key") - if !success { - t.Fatalf("failed to remove fake_key") - } - options, err := conf.GetOptions("service-2") - assertNoError(t, err) - if 3 != len(options) { - t.Fatalf("expect 3 but get: %v", len(options)) - } - for _, option := range options { - if option == "fake_key" { - t.Fatalf("option: fake_key should be removed") - } - } -} - -func TestAddOption(t *testing.T) { - t.Logf("conf is like before :\n%v\n", byteConfigForTest) - conf, err := ReadConfigBytes([]byte(byteConfigForTest)) - assertNoError(t, err) - isNotOverwritten := conf.AddOption("service-2", "fake_key", "fakeValue") - if isNotOverwritten { - t.Fatalf("add existed should be overwritten") - } - t.Logf("conf is like after :\n%v\n", conf.String()) - options, err := conf.GetOptions("service-2") - assertNoError(t, err) - if 5 != len(options) { - t.Fatalf("expect 5 but get: %v", len(options)) - } - - kvDataMapList, isExisted := conf.GetKVDatas("service-2") - if !isExisted { - t.Fatalf("should get section service-2") - } - for _, kvDataMap := range kvDataMapList { - _, isExisted := kvDataMap["fake_key"] - if isExisted && kvDataMap["fake_key"] != "fakeValue" { - t.Fatalf("expect: fakeValue but get: %v", kvDataMap["fake_key"]) - } - } - - isNotOverwritten = conf.AddOption("service-2", "fake_key1", "fakeValue1") - if !isNotOverwritten { - t.Fatalf("add existed should not be overwritten") - } - - value, err := conf.GetString("service-2", "fake_key1") - if err != nil { - t.Fatalf("failed to get key fake_key1") - } - if value != "fakeValue1" { - t.Fatalf("expect: fakeValue1 but get: %v", value) - } -} - -var ( - byteConfigGetStringTest = `[default1] -host = something.com -host1 = "something.com" -host2 = 'something.com" -host3 = 'something.com' -host4 = "'something.com" -` -) - -func TestGetString(t *testing.T) { - t.Logf("conf is like before :\n%v\n", byteConfigGetStringTest) - conf, err := ReadConfigBytes([]byte(byteConfigGetStringTest)) - assertNoError(t, err) - options, err := conf.GetOptions("default1") - assertNoError(t, err) - for _, option := range options { - value, err := conf.GetString("default1", option) - assertNoError(t, err) - if option == "host4" { - if value != "'something.com" { - t.Fatalf("expect: something.com but get: %v", value) - } - continue - } - - if value != "something.com" { - t.Fatalf("expect: something.com but get: %v", value) - } - } -} diff --git a/pkg/dms-common/pkg/config/get.go b/pkg/dms-common/pkg/config/get.go deleted file mode 100644 index d0081be39..000000000 --- a/pkg/dms-common/pkg/config/get.go +++ /dev/null @@ -1,220 +0,0 @@ -package config - -import ( - "strconv" - "strings" -) - -const ( - SectionDefault = "default" -) - -// GetSections returns the list of sections in the configuration. -// (The default section always exists.) -func (c *ConfigFile) GetSections() (sections []string) { - sections = make([]string, 0, len(c.data)) - for s := range c.data { - sections = append(sections, s) - } - return sections -} - -// HasSection checks if the configuration has the given section. -// (The default section always exists.) -func (c *ConfigFile) HasSection(section string) bool { - if section == "" { - section = SectionDefault - } - _, ok := c.data[strings.ToLower(section)] - - return ok -} - -// GetOptions returns the list of options available in the given section. -// It returns an error if the section does not exist and an empty list if the section is empty. -// Options within the default section are also included. -func (c *ConfigFile) GetOptions(section string) (options []string, err error) { - if section == "" { - section = SectionDefault - } - section = strings.ToLower(section) - - if _, ok := c.data[section]; !ok { - return nil, GetError{SectionNotFound, "", "", section, ""} - } - - options = make([]string, 0, len(c.data[DefaultSection])+len(c.data[section])) - for _, kvData := range c.data[DefaultSection] { //NO_DUPL_CHECK - if kvData.key != emptyLine && kvData.key != commentLine { - options = append(options, kvData.key) - } - } - if section == SectionDefault { - return options, nil - } - for _, kvData := range c.data[section] { - if kvData.key != emptyLine && kvData.key != commentLine { - options = append(options, kvData.key) - } - } - - return options, nil -} - -// GetOptionsWithoutDefaultSection returns the list of options available in the given section. -// It returns an error if the section does not exist and an empty list if the section id empty. -// Options within the default section are not included. -func (c *ConfigFile) GetOptionsWithoutDefaultSection(section string) (options []string, err error) { - section = strings.ToLower(section) - - if _, ok := c.data[section]; !ok { - return nil, GetError{SectionNotFound, "", "", section, ""} - } - - for _, kvData := range c.data[section] { - options = append(options, kvData.key) - } - - return options, nil -} - -// HasOption checks if the configuration has the given option in the section. -// It returns false if either the option or section do not exist. -func (c *ConfigFile) HasOption(section string, option string) bool { - if section == "" { - section = SectionDefault - } - section = strings.ToLower(section) - option = strings.ToLower(option) - - if _, ok := c.data[section]; !ok { - return false - } - - var okd, oknd bool - for _, kvData := range c.data[DefaultSection] { - if kvData.key == option { - okd = true - } - } - for _, kvData := range c.data[section] { - if kvData.key == option { - oknd = true - } - } - - return okd || oknd -} - -// GetRawString gets the (raw) string value for the given option in the section. -// The raw string value is not subjected to unfolding, which was illustrated in the beginning of this documentation. -// It returns an error if either the section or the option do not exist. -// if has duplicated key, return the first one -func (c *ConfigFile) GetRawString(section string, option string) (value string, err error) { - if section == "" { - section = SectionDefault - } - - section = strings.ToLower(section) - option = strings.ToLower(option) - if _, ok := c.data[section]; ok { - - for _, kvData := range c.data[section] { - if kvData.key == option { - return kvData.value, nil - } - } - return "", GetError{OptionNotFound, "", "", section, option} - } - return "", GetError{SectionNotFound, "", "", section, option} -} - -// GetString gets the string value for the given option in the section. -// If the value needs to be unfolded (see e.g. %(host)s example in the beginning of this documentation), -// then GetString does this unfolding automatically, up to DepthValues number of iterations. -// It returns an error if either the section or the option do not exist, or the unfolding cycled. -func (c *ConfigFile) GetString(section string, option string) (value string, err error) { - value, err = c.GetRawString(section, option) - if err != nil { - return "", err - } - - //trim ", ' left - if strings.HasPrefix(value, "\"") { - value = strings.TrimPrefix(value, "\"") - } else { - value = strings.TrimPrefix(value, "'") - } - - //trim ", ' right - value = strings.TrimSuffix(value, "\"") - value = strings.TrimSuffix(value, "'") - if strings.HasSuffix(value, "\"") { - value = strings.TrimSuffix(value, "\"") - } else { - value = strings.TrimSuffix(value, "'") - } - - return value, nil -} - -// GetInt has the same behaviour as GetString but converts the response to int. -func (c *ConfigFile) GetInt(section string, option string) (value int, err error) { - sv, err := c.GetString(section, option) - if err == nil { - value, err = strconv.Atoi(sv) - if err != nil { - err = GetError{CouldNotParse, "int", sv, section, option} - } - } - - return value, err -} - -// GetFloat has the same behaviour as GetString but converts the response to float. -func (c *ConfigFile) GetFloat64(section string, option string) (value float64, err error) { - sv, err := c.GetString(section, option) - if err == nil { - value, err = strconv.ParseFloat(sv, 64) - if err != nil { - err = GetError{CouldNotParse, "float64", sv, section, option} - } - } - - return value, err -} - -// GetBool has the same behaviour as GetString but converts the response to bool. -// See constant BoolStrings for string values converted to bool. -func (c *ConfigFile) GetBool(section string, option string) (value bool, err error) { - sv, err := c.GetString(section, option) - if err != nil { - return false, err - } - - value, ok := BoolStrings[strings.ToLower(sv)] - if !ok { - return false, GetError{CouldNotParse, "bool", sv, section, option} - } - - return value, nil -} - -// get all key value data, if no existed section return false -func (c *ConfigFile) GetKVDatas(section string) ([]map[string]string, bool) { - _, ok := c.data[section] - if !ok { - return nil, false - } - kvDatasMapList := make([]map[string]string, 0, len(c.data[section])) - for _, kvdata := range c.data[section] { - if kvdata.key == emptyLine || kvdata.key == commentLine { - continue - } - kvDatasMapList = append( - kvDatasMapList, - map[string]string{kvdata.key: kvdata.value}, - ) - } - return kvDatasMapList, true -} diff --git a/pkg/dms-common/pkg/config/read.go b/pkg/dms-common/pkg/config/read.go deleted file mode 100644 index e9456521f..000000000 --- a/pkg/dms-common/pkg/config/read.go +++ /dev/null @@ -1,133 +0,0 @@ -package config - -import ( - "bufio" - "bytes" - "io" - "os" - "strings" -) - -const BLANK_SECTION = "BLANK_SECTION" - -// ReadConfigFile reads a file and returns a new configuration representation. -// This representation can be queried with GetString, etc. -// Not support multi-line value -func ReadConfigFile(fname string) (c *ConfigFile, err error) { - var file *os.File - - if file, err = os.Open(fname); err != nil { - return nil, err - } - - c = NewConfigFile() - if err = c.Read(file); err != nil { - return nil, err - } - - if err = file.Close(); err != nil { - return nil, err - } - - return c, nil -} - -func ReadConfigBytes(conf []byte) (c *ConfigFile, err error) { - buf := bytes.NewBuffer(conf) - - c = NewConfigFile() - if err = c.Read(buf); err != nil { - return nil, err - } - - return c, err -} - -// Read reads an io.Reader and returns a configuration representation. This -// representation can be queried with GetString, etc. -// Not support multi-line value -func (c *ConfigFile) Read(reader io.Reader) (err error) { - buf := bufio.NewReader(reader) - - var ( - section, option string - getFirstRealSection bool - ) - - for { - l, buferr := buf.ReadString('\n') // parse line-by-line - l = strings.TrimSpace(l) - - if buferr != nil { - if buferr != io.EOF { - return err - } - - if len(l) == 0 { - break - } - } - - // switch written for readability (not performance) - switch { - case len(l) == 0: // empty line - if getFirstRealSection { - c.AddOption(section, emptyLine, "") - } - continue - case l[0] == '#', - l[0] == ';', - len(l) >= 3 && strings.ToLower(l[0:3]) == "rem": // comment - if getFirstRealSection { - c.AddOption(section, commentLine, l, false) - } else { - c.AddOption(virtualSection, commentLine, l, false) //comments before first section - } - continue - case l[0] == '[' && strings.Index(l, "]") > 0: // new section - option = "" //nolint:ineffassign // 这段代码在for循环中将option变为空字符串,看起来是有意义的赋值,linter误报 - sectionEnd := strings.Index(l, "]") - section = strings.TrimSpace(l[1:sectionEnd]) - if !getFirstRealSection { - getFirstRealSection = true - } - c.AddSection(section) - case section == "": // not new section and no section defined so far - section = BLANK_SECTION - - default: // other alternatives - i := strings.IndexAny(l, "=:") - switch { - case i > 0: // option and value - i := strings.IndexAny(l, "=:") - option = strings.TrimSpace(l[0:i]) - value := "" - if i > 0 { - value = strings.TrimSpace(StripComments(l[i+1:])) - } - c.AddOption(section, option, value, false) - case i == -1: - option = strings.TrimSpace(l) - c.AddOption(section, option, "", false) - default: - return ReadError{CouldNotParse, l} - } - } - - // Reached end of file - if buferr == io.EOF { - break - } - } - return nil -} - -func StripComments(l string) string { - // comments are preceded by space or TAB - for _, c := range []string{" ;", "\t;", " #", "\t#"} { - if i := strings.Index(l, c); i != -1 { - l = l[0:i] - } - } - return l -} diff --git a/pkg/dms-common/pkg/config/read_test.go b/pkg/dms-common/pkg/config/read_test.go deleted file mode 100644 index 1368bf180..000000000 --- a/pkg/dms-common/pkg/config/read_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package config - -import ( - "fmt" - "testing" -) - -var ( - byteConfig = `[default1] -host = something.com -port = 443 -active = true -compression = off - -[service-2] -port = 444 -skip_lock -host = something.com - -[service-1]#comment1 -compression = on -` -) - -func TestReadConfigBytes_Normal(t *testing.T) { - t.Logf("conf is like before :\n%v\n", byteConfig) - conf, err := ReadConfigBytes([]byte(byteConfig)) - assertNoError(t, err) - options, err := conf.GetOptions("default1") - assertNoError(t, err) - if len(options) != 4 { - for i, opt := range options { - fmt.Printf("%v : %v,len=%v\n", i, opt, len(opt)) - } - t.Fatalf("read conf uncorrect , expect num of default1.option is 4, result is %v", len(options)) - } - - host, err := conf.GetString("default1", "host") - assertNoError(t, err) - if "something.com" != host { - t.Fatalf("expect default1.host=something.com, result default1.host=%v", host) - } - - port, err := conf.GetInt("default1", "port") - assertNoError(t, err) - if 443 != port { - t.Fatalf("expect default1.port=, result default1.port=%v", port) - } - - active, err := conf.GetBool("default1", "active") - assertNoError(t, err) - if !active { - t.Fatalf("expect default1.active=true, result default1.active=%v", active) - } - - compression, err := conf.GetBool("default1", "compression") - assertNoError(t, err) - if compression { - t.Fatalf("expect default1.compression=false, result default1.compression=%v", compression) - } -} - -// could have comments at section line -// eg: [setion1] #comments -func TestReadConfigBytes_SectionWithComment(t *testing.T) { - t.Logf("conf is like before :\n%v\n", byteConfig) - conf, err := ReadConfigBytes([]byte(byteConfig)) - assertNoError(t, err) - if !conf.HasSection("service-1") { - t.Fatalf("read conf error, section(service-1) with comment be ignored") - } -} - -func assertNoError(t *testing.T, err error) { - if nil != err { - t.Fatalf(err.Error()) - } -} - -// if option don't have value,should give this option defautl value(true) -func TestReadConfigBytes_OptionWithoutValue(t *testing.T) { - t.Logf("conf is like before :\n%v\n", byteConfig) - conf, err := ReadConfigBytes([]byte(byteConfig)) - assertNoError(t, err) - - opt, err := conf.GetBool("service-2", "skip_lock") - assertNoError(t, err) - if !opt { - t.Fatalf("expect service-2.skip_lock=true, result is %v", opt) - } - formalOpt, err := conf.GetInt("service-2", "port") - assertNoError(t, err) - if 444 != formalOpt { - t.Fatalf("expect service-2.port=444, result is %v", formalOpt) - } -} diff --git a/pkg/dms-common/pkg/config/set.go b/pkg/dms-common/pkg/config/set.go deleted file mode 100644 index 6892a1b69..000000000 --- a/pkg/dms-common/pkg/config/set.go +++ /dev/null @@ -1,19 +0,0 @@ -package config - -func (c *ConfigFile) SetString(section, option, value string) error { - if section == "" { - section = "default" - } - - if _, ok := c.data[section]; ok { - for _, kvData := range c.data[section] { - if kvData.key == option { - kvData.value = value - return nil - } - } - - return GetError{OptionNotFound, "", "", section, option} - } - return GetError{SectionNotFound, "", "", section, option} -} diff --git a/pkg/dms-common/pkg/config/validator.go b/pkg/dms-common/pkg/config/validator.go index 203f79744..6cc367b0a 100644 --- a/pkg/dms-common/pkg/config/validator.go +++ b/pkg/dms-common/pkg/config/validator.go @@ -1,12 +1,23 @@ package config -import validator "github.com/go-playground/validator/v10" +import ( + "regexp" + + "github.com/go-playground/validator/v10" +) // use a single instance of Validate, it caches struct info var validate *validator.Validate +var DbNameFormatPattern = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_-]*$") + +func validateDbNameFormat(field validator.FieldLevel) bool { + return DbNameFormatPattern.MatchString(field.Field().String()) +} + func init() { validate = validator.New() + _ = validate.RegisterValidation("dbNameFormat", validateDbNameFormat) } func Validate(i interface{}) error { diff --git a/pkg/dms-common/pkg/config/write.go b/pkg/dms-common/pkg/config/write.go deleted file mode 100644 index 531fccd35..000000000 --- a/pkg/dms-common/pkg/config/write.go +++ /dev/null @@ -1,125 +0,0 @@ -package config - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// WriteConfigFile saves the configuration representation to a file. -// The desired file permissions must be passed as in os.Open. -// The header is a string that is saved as a comment in the first line of the file. -func (c *ConfigFile) WriteConfigFile(fname string, perm uint32, header string, firstSections []string) (err error) { - - var file *os.File - if file, err = os.Create(fname); err != nil { - return err - } - defer file.Close() - - if err = c.Write(file, header, firstSections); err != nil { - return err - } - file.Sync() //nolint:errcheck //we're OK if sync returns non-zero code - return nil -} - -// WriteConfigBytes returns the configuration file. -func (c *ConfigFile) WriteConfigBytes(header string) (config []byte) { - buf := bytes.NewBuffer(nil) - - err := c.Write(buf, header, []string{}) - if err != nil && err != io.EOF { - fmt.Println("WriteConfigBytes error: " + err.Error()) - } - - return buf.Bytes() -} - -// Writes the configuration file to the io.Writer. -func (c *ConfigFile) Write(writer io.Writer, header string, firstSections []string) (err error) { - buf := bytes.NewBuffer(nil) - - if header != "" { - if _, err = buf.WriteString("# " + header + "\n"); err != nil { - return err - } - } - - for _, section := range c.sectionOrder { - sectionDataList, exist := c.data[section] - if !exist { - continue - } - if section == DefaultSection && len(sectionDataList) == 0 { - continue // skip default section if empty - } - - if section != virtualSection { - if _, err = buf.WriteString("[" + section + "]\n"); err != nil { - return err - } - } - - for _, kvData := range c.data[section] { - switch kvData.key { - case commentLine: - if _, err := buf.WriteString(kvData.value + "\n"); err != nil { - return err - } - case emptyLine: - if _, err := buf.WriteString("\n"); err != nil { - return err - } - default: - if kvData.value == "" { - if _, err := buf.WriteString(kvData.key + " = " + "\n"); err != nil { - return err - } - } else { - if _, err := buf.WriteString(kvData.key + " = " + kvData.value + "\n"); err != nil { - return err - } - } - } - } - } - - _, err = buf.WriteTo(writer) - - return err -} - -// String return configuration as string. -func (c *ConfigFile) String() string { - buf := bytes.NewBuffer(nil) - for _, section := range c.sectionOrder { - sectionmap, exist := c.data[section] - if !exist { - continue - } - if section == DefaultSection && len(sectionmap) == 0 { - continue // skip default section if empty - } - if section != virtualSection { - buf.WriteString("[" + section + "]\n") - } - - for _, kvData := range c.data[section] { - switch kvData.key { - case commentLine: - buf.WriteString(kvData.value + "\n") - case emptyLine: - buf.WriteString("\n") - default: - if kvData.value == "" { - buf.WriteString(kvData.key + " = " + "\n") - } else { - buf.WriteString(kvData.key + " = " + kvData.value + "\n") - } - } - } - } - return buf.String() -} diff --git a/pkg/dms-common/pkg/const/const.go b/pkg/dms-common/pkg/const/const.go new file mode 100644 index 000000000..e930eb479 --- /dev/null +++ b/pkg/dms-common/pkg/const/const.go @@ -0,0 +1,6 @@ +package _const + +const ( + SqleComponentName = "sqle" + DmsComponentName = "dms" +) diff --git a/pkg/dms-common/pkg/http/http.go b/pkg/dms-common/pkg/http/http.go index c85ab5f3a..e19e274b7 100644 --- a/pkg/dms-common/pkg/http/http.go +++ b/pkg/dms-common/pkg/http/http.go @@ -8,27 +8,72 @@ import ( "io" "net/http" "time" + + v1 "github.com/actiontech/dms/pkg/dms-common/api/dms/v1" + "github.com/actiontech/dms/pkg/dms-common/api/jwt" ) // sys用户长有效期token,有限期至2073年 -var DefaultDMSToken = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI3MDAyMDEiLCJleHAiOjMyNTkxMzU3ODIsImlzcyI6ImFjdGlvbnRlY2ggZG1zIn0.pdCLmGM-lZwcBsOnwfxM2m5xbUzGpEqAiRurkCj-8YY" + +var defaultDMSToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjMyNzI0MjEzNTMsImlzcyI6ImFjdGlvbnRlY2ggZG1zIiwidWlkIjoiNzAwMjAxIn0.45o27vHjHWslarkbovAim6oir3QlrvSDDuzfpGTn6Dk" +var DefaultDMSToken = fmt.Sprintf("Bearer %s", defaultDMSToken) + +func ResetJWTSigningKeyAndDefaultToken(val string) error { + if val == "" { + return nil + } + + uid, err := jwt.ParseUidFromJwtTokenStr(defaultDMSToken) + if err != nil { + return err + } + + // reset jwt singing key + v1.ResetJWTSigningKey(val) + + // expire time: 50 years later + token, err := jwt.GenJwtToken(jwt.WithUserId(uid), jwt.WithExpiredTime(time.Hour*24*365*50)) + if err != nil { + return err + } + + // reset default dms token + resetDefaultDMSToken(token) + + return nil +} + +func resetDefaultDMSToken(token string) { + if token != "" { + DefaultDMSToken = fmt.Sprintf("Bearer %s", token) + } +} func Get(ctx context.Context, url string, headers map[string]string, body, out interface{}) error { - return Call(ctx, http.MethodGet, url, headers, body, out) + bodyJson, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("marshal error: %v", err) + } + return Call(ctx, http.MethodGet, url, headers, "application/json", bodyJson, out) } func POST(ctx context.Context, url string, headers map[string]string, body, out interface{}) error { - return Call(ctx, http.MethodPost, url, headers, body, out) + bodyJson, err := json.Marshal(body) + if err != nil { + return fmt.Errorf("marshal error: %v", err) + } + return Call(ctx, http.MethodPost, url, headers, "application/json", bodyJson, out) } -func Call(ctx context.Context, method, url string, headers map[string]string, body, out interface{}) error { +func Call(ctx context.Context, method, url string, headers map[string]string, contentType string, body []byte, out interface{}) error { + // 获取上下文中的超时值,并将其断言为 int64 类型 + timeout, ok := ctx.Value(timeoutKey).(int64) + if !ok { + timeout = 30 * 60 // 默认超时时间 + } var bodyReader io.Reader if body != nil { - bodyJson, err := json.Marshal(body) - if err != nil { - return fmt.Errorf("marshal error: %v", err) - } - bodyReader = bytes.NewReader(bodyJson) + bodyReader = bytes.NewReader(body) } req, err := http.NewRequestWithContext(ctx, method, url, bodyReader) @@ -38,10 +83,12 @@ func Call(ctx context.Context, method, url string, headers map[string]string, bo for k, v := range headers { req.Header.Add(k, v) } - req.Header.Set("Content-Type", "application/json") + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } client := http.Client{ - Timeout: time.Second * 15, + Timeout: time.Second * time.Duration(timeout), } resp, err := client.Do(req) if err != nil { @@ -64,3 +111,11 @@ func Call(ctx context.Context, method, url string, headers map[string]string, bo } return nil } + +type contextKey string + +const timeoutKey contextKey = "timeoutKey" + +func SetTimeoutValueContext(ctx context.Context, timeout int64) context.Context { + return context.WithValue(ctx, timeoutKey, timeout) +} diff --git a/internal/pkg/log/log_options.go b/pkg/dms-common/pkg/log/log_options.go similarity index 100% rename from internal/pkg/log/log_options.go rename to pkg/dms-common/pkg/log/log_options.go diff --git a/internal/pkg/log/log_wrapper.go b/pkg/dms-common/pkg/log/log_wrapper.go similarity index 84% rename from internal/pkg/log/log_wrapper.go rename to pkg/dms-common/pkg/log/log_wrapper.go index d69c757ba..01a23bca5 100644 --- a/internal/pkg/log/log_wrapper.go +++ b/pkg/dms-common/pkg/log/log_wrapper.go @@ -5,8 +5,6 @@ import ( "fmt" "time" - utilLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" - "github.com/go-kratos/kratos/v2/log" gormLog "gorm.io/gorm/logger" ) @@ -111,7 +109,7 @@ func formatId(id string) string { return fmt.Sprintf("[%s] ", id) } -func NewUtilLogWrapper(logger log.Logger) utilLog.Logger { +func NewUtilLogWrapper(logger log.Logger) Logger { return &UtilLogWrapper{logger: logger} } @@ -119,20 +117,20 @@ type UtilLogWrapper struct { logger log.Logger } -func (l *UtilLogWrapper) Log(level utilLog.Level, keyvals ...interface{}) error { +func (l *UtilLogWrapper) Log(level Level, keyvals ...interface{}) error { var myLevel log.Level switch level { - case utilLog.LevelDebug: + case LevelDebug: myLevel = log.LevelDebug - case utilLog.LevelInfo: + case LevelInfo: myLevel = log.LevelInfo - case utilLog.LevelWarn: + case LevelWarn: myLevel = log.LevelWarn - case utilLog.LevelError: + case LevelError: myLevel = log.LevelError - case utilLog.LevelFatal: + case LevelFatal: myLevel = log.LevelFatal - case utilLog.LevelInfoDilute: + case LevelInfoDilute: myLevel = log.LevelDebug default: myLevel = log.LevelDebug @@ -161,12 +159,12 @@ func (h *gormLogWrapper) LogMode(level gormLog.LogLevel) gormLog.Interface { } func (h *gormLogWrapper) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) { - if h.logLevel <= gormLog.Silent { - return + // 只有在 Info 级别或更高时才输出 SQL trace 日志 + if h.logLevel >= gormLog.Info { + elapsed := time.Since(begin) + sql, rowsAffected := fc() + _ = h.logger.Log(log.LevelDebug, h.msgKey, fmt.Sprintf("trace: begin:%v; elapsed:%v; sql: %v; rowsAffected: %v; err: %v", begin.Format(LogTimeLayout), elapsed, sql, rowsAffected, err)) } - elapsed := time.Since(begin) - sql, rowsAffected := fc() - _ = h.logger.Log(log.LevelDebug, h.msgKey, fmt.Sprintf("trace: begin:%v; elapsed:%v; sql: %v; rowsAffected: %v; err: %v", begin.Format(LogTimeLayout), elapsed, sql, rowsAffected, err)) } func (h *gormLogWrapper) Error(ctx context.Context, format string, a ...interface{}) { @@ -188,30 +186,30 @@ func (h *gormLogWrapper) Info(ctx context.Context, format string, a ...interface } type kWrapper struct { - logger utilLog.Logger + logger Logger } -func NewKLogWrapper(logger utilLog.Logger) *kWrapper { +func NewKLogWrapper(logger Logger) *kWrapper { return &kWrapper{ logger: logger, } } func (k *kWrapper) Log(level log.Level, keyvals ...interface{}) error { - var l utilLog.Level + var l Level switch level { case log.LevelDebug: - l = utilLog.LevelDebug + l = LevelDebug case log.LevelInfo: - l = utilLog.LevelInfo + l = LevelInfo case log.LevelWarn: - l = utilLog.LevelWarn + l = LevelWarn case log.LevelError: - l = utilLog.LevelError + l = LevelError case log.LevelFatal: - l = utilLog.LevelFatal + l = LevelFatal default: - l = utilLog.LevelDebug + l = LevelDebug } return k.logger.Log(l, keyvals...) } diff --git a/internal/pkg/log/std.go b/pkg/dms-common/pkg/log/std.go similarity index 100% rename from internal/pkg/log/std.go rename to pkg/dms-common/pkg/log/std.go diff --git a/pkg/dms-common/register/register.go b/pkg/dms-common/register/register.go index 546a42331..5a7ac18f3 100644 --- a/pkg/dms-common/register/register.go +++ b/pkg/dms-common/register/register.go @@ -9,8 +9,8 @@ import ( ) // RegisterDMSProxyTarget 向DMS注册反向代理,将proxyPrefix开头的请求转发到自身服务 -// eg: name = sqle; url = http://10.1.2.1:5432; proxyPrefix = /v1/sqle 表示要求DMS将/v1/sqle开头的请求转发到sqle服务所在地址 http://10.1.2.1:5432 -func RegisterDMSProxyTarget(ctx context.Context, dmsAddr, targetName, targetAddr string, proxyUrlPrefixs []string) error { +// eg: name = sqle; url = http://10.1.2.1:5432; proxyPrefix = /v1/sqle 表示要求DMS将/v1/sqle开头的请求转发到sqle服务所在地址 http://10.1.2.1:5432 scenario选择代理转发的使用场景,例如:ProxyScenarioInternalService,会用于测试数据库的连通性 +func RegisterDMSProxyTarget(ctx context.Context, dmsAddr, targetName, targetAddr, version string, proxyUrlPrefixs []string, scenario dmsV1.ProxyScenario) error { header := map[string]string{ "Authorization": pkgHttp.DefaultDMSToken, } @@ -20,7 +20,9 @@ func RegisterDMSProxyTarget(ctx context.Context, dmsAddr, targetName, targetAddr DMSProxyTarget: &dmsV1.DMSProxyTarget{ Name: targetName, Addr: targetAddr, + Version: version, ProxyUrlPrefixs: proxyUrlPrefixs, + Scenario: scenario, }, } @@ -32,7 +34,7 @@ func RegisterDMSProxyTarget(ctx context.Context, dmsAddr, targetName, targetAddr return fmt.Errorf("failed to register dms proxy target %v: %v", dmsUrl, err) } if reply.Code != 0 { - return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } return nil @@ -57,7 +59,7 @@ func RegisterDMSPlugin(ctx context.Context, dmsAddr string, plugin *dmsV1.Plugin return fmt.Errorf("failed to register dms plugin %v: %v", dmsUrl, err) } if reply.Code != 0 { - return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Msg) + return fmt.Errorf("http reply code(%v) error: %v", reply.Code, reply.Message) } return nil diff --git a/pkg/dms-common/sql_op/sql_op.go b/pkg/dms-common/sql_op/sql_op.go new file mode 100644 index 000000000..5c71fbb33 --- /dev/null +++ b/pkg/dms-common/sql_op/sql_op.go @@ -0,0 +1,86 @@ +// sqlop 包定义了SQL权限操作的相关结构体,目前用于事前权限校验 +// 背景见:https://github.com/actiontech/dms-ee/issues/125 + +package sqlop + +import "encoding/json" + +func EncodingSQLObjectOps(s *SQLObjectOps) (string, error) { + jsonStr, err := json.Marshal(s) + if err != nil { + return "", err + } + return string(jsonStr), nil +} + +func DecodingSQLObjectOps(s string) (*SQLObjectOps, error) { + var sqlObjectOps SQLObjectOps + err := json.Unmarshal([]byte(s), &sqlObjectOps) + if err != nil { + return nil, err + } + return &sqlObjectOps, nil +} + +type SQLObjectOps struct { + // ObjectOps 表示sql中涉及的对象及对对象的操作 + ObjectOps []*SQLObjectOp + Sql SQLInfo +} + +func NewSQLObjectOps(sql string) *SQLObjectOps { + return &SQLObjectOps{ + ObjectOps: []*SQLObjectOp{}, + Sql: SQLInfo{Sql: sql}, + } +} + +func (s *SQLObjectOps) AddObjectOp(o ...*SQLObjectOp) { + s.ObjectOps = append(s.ObjectOps, o...) +} + +type SQLObjectOp struct { + Op SQLOp // 对象操作 + Object *SQLObject // 对象 +} + +type SQLObject struct { + // Type 表示对象的类型 + Type SQLObjectType + // DatabaseName 表示对象所在的database,若对象不属于database,或无法从Sql中解析出当前database,则为空字符串 + DatabaseName string + // SchemaName 表示对象所在的schema,若对象不属于schema,或无法从Sql中解析出当前schema,则为空字符串 + // 对于一些数据库类型,如PostgreSQL,可能存在schema的概念,此时SchemaName字段应该被使用 + // 对于一些数据库类型,如MySQL,可能不存在schema的概念,或schema的概念与database的概念相同,此时SchemaName字段应该为空字符串 + SchemaName string + // TableName 表示对象的表名,如果对象不是表,则为空字符串 + TableName string +} + +type SQLObjectType string + +const ( + SQLObjectTypeTable SQLObjectType = "Table" + SQLObjectTypeSchema SQLObjectType = "Schema" + SQLObjectTypeDatabase SQLObjectType = "Database" + SQLObjectTypeInstance SQLObjectType = "Instance" + SQLObjectTypeServer SQLObjectType = "Server" +) + +type SQLInfo struct { + Sql string +} +type SQLOp string + +const ( + // 增或改操作 + SQLOpAddOrUpdate SQLOp = "AddOrUpdate" + // 读取操作 + SQLOpRead SQLOp = "Read" + // 删除操作 + SQLOpDelete SQLOp = "Delete" + // 授权操作 + SQLOpGrant SQLOp = "Grant" + // 高权限操作,如锁表、导出表到文件等 + SQLOpAdmin SQLOp = "Admin" +) diff --git a/pkg/params/params.go b/pkg/params/params.go index 57f47ad88..c2c94847e 100644 --- a/pkg/params/params.go +++ b/pkg/params/params.go @@ -136,3 +136,13 @@ func (r *Params) Copy() Params { } return ps } + +type Enum struct { + Value string `json:"value"` + Desc string `json:"desc"` +} + +type ParamsWithEnums struct { + Param + Enums []Enum +} diff --git a/pkg/periods/periods.go b/pkg/periods/periods.go index 48f5c4d2c..f0bc4cf9c 100644 --- a/pkg/periods/periods.go +++ b/pkg/periods/periods.go @@ -4,6 +4,7 @@ import ( "database/sql/driver" "encoding/json" "fmt" + "strings" "time" ) @@ -16,6 +17,27 @@ type Period struct { EndMinute int `json:"end_minute"` } +// ParsePeriods parse string in importing db services csv column like: 09:30-11:30;11:30-13:30;20:30-21:30 to *Periods +func ParsePeriods(s string) (Periods, error) { + start2ends := strings.Split(s, ";") + ps := make(Periods, len(start2ends)) + for k, v := range start2ends { + p := Period{} + // if sth follows "%d:%d-%d:%d", it will be ignored + _, err := fmt.Sscanf(v, "%d:%d-%d:%d", &p.StartHour, &p.StartMinute, &p.EndHour, &p.EndMinute) + if err != nil { + return nil, err + } + ps[k] = &p + } + + if !ps.SelfCheck() { + return nil, fmt.Errorf("self check error, invalid period") + } + + return ps, nil +} + // Scan impl sql.Scanner interface func (r *Periods) Scan(value interface{}) error { if value == nil { diff --git a/pkg/periods/periods_test.go b/pkg/periods/periods_test.go new file mode 100644 index 000000000..6412bd46c --- /dev/null +++ b/pkg/periods/periods_test.go @@ -0,0 +1,471 @@ +package periods + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestPeriods_ScanValue(t *testing.T) { + ps := Periods{ + &Period{ + StartHour: 1, + StartMinute: 2, + EndHour: 3, + EndMinute: 4, + }, + &Period{ + StartHour: 1, + StartMinute: 3, + EndHour: 2, + EndMinute: 4, + }, + &Period{ + StartHour: 2, + StartMinute: 4, + EndHour: 3, + EndMinute: 1, + }, + } + + data, err := ps.Value() + assert.NoError(t, err) + + var ps2 Periods + err = ps2.Scan(data) + assert.NoError(t, err) + assert.Equal(t, ps, ps2) + + ps3 := Periods{ + &Period{ + StartHour: 0, + StartMinute: 2, + EndHour: 3, + EndMinute: 4, + }, + &Period{ + StartHour: 0, + StartMinute: 4, + EndHour: 2, + EndMinute: 4, + }, + &Period{ + StartHour: 0, + StartMinute: 4, + EndHour: 3, + EndMinute: 1, + }, + } + assert.NotEqual(t, ps3, ps2) + + var emptyPs Periods + data, err = emptyPs.Value() + assert.NoError(t, err) + + var emptyPs2 Periods + err = emptyPs2.Scan(data) + assert.NoError(t, err) + assert.Equal(t, emptyPs, emptyPs2) + + data = []byte("this is test scan fail") + var failPs Periods + err = failPs.Scan(data) + assert.Error(t, err) +} + +func TestPeriods_SelfCheck(t *testing.T) { + // Critical Values and Normal Intervals + ps1 := Periods{ + { + StartHour: 0, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 20, + EndHour: 2, + EndMinute: 10, + }, + } + assert.Equal(t, ps1.SelfCheck(), true) + + // The second rule end hour is earlier than start hour + ps2 := Periods{ + { + StartHour: 0, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 2, + StartMinute: 20, + EndHour: 1, + EndMinute: 10, + }, + } + assert.Equal(t, ps2.SelfCheck(), false) + + // The second rule end minute is equal than start minute + ps3 := Periods{ + { + StartHour: 0, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 1, + EndHour: 1, + EndMinute: 1, + }, + } + assert.Equal(t, ps3.SelfCheck(), false) + + // The second rule end minute is earlier than start minute + ps4 := Periods{ + { + StartHour: 0, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 10, + EndHour: 1, + EndMinute: 1, + }, + } + assert.Equal(t, ps4.SelfCheck(), false) + + // The second rule end hour is to large + ps5 := Periods{ + { + StartHour: 0, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 20, + EndHour: 24, + EndMinute: 10, + }, + } + assert.Equal(t, ps5.SelfCheck(), false) + + // The second rule end minutes is to large + ps6 := Periods{ + { + StartHour: 0, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 20, + EndHour: 2, + EndMinute: 60, + }, + } + assert.Equal(t, ps6.SelfCheck(), false) + + // The first start hour is too large + ps7 := Periods{ + { + StartHour: 24, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 20, + EndHour: 2, + EndMinute: 10, + }, + } + assert.Equal(t, ps7.SelfCheck(), false) + + // The first start minute is too large + ps8 := Periods{ + { + StartHour: 0, + StartMinute: 60, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 20, + EndHour: 2, + EndMinute: 10, + }, + } + assert.Equal(t, ps8.SelfCheck(), false) + + // The first start hour is too less + ps9 := Periods{ + { + StartHour: -1, + StartMinute: 0, + EndHour: 23, + EndMinute: 59, + }, { + StartHour: 1, + StartMinute: 20, + EndHour: 2, + EndMinute: 10, + }, + } + assert.Equal(t, ps9.SelfCheck(), false) + + // The first end minute is too less + ps10 := Periods{ + { + StartHour: 0, + StartMinute: 0, + EndHour: 23, + EndMinute: -4, + }, { + StartHour: 1, + StartMinute: 20, + EndHour: 2, + EndMinute: 10, + }, + } + assert.Equal(t, ps10.SelfCheck(), false) + +} + +func TestPeriods_IsWithinScope(t *testing.T) { + ps := Periods{ + { + StartHour: 4, + StartMinute: 3, + EndHour: 5, + EndMinute: 4, + }, { + StartHour: 2, + StartMinute: 1, + EndHour: 3, + EndMinute: 2, + }, + } + + // The first end threshold + t0, err := time.Parse("2006-01-02 15:04:05", "2017-12-08 05:04:03") + assert.NoError(t, err) + assert.Equal(t, ps.IsWithinScope(t0), true) + + // The second start threshold + t1, err := time.Parse("2006-01-02 15:04:05", "2017-12-08 02:01:03") + assert.NoError(t, err) + assert.Equal(t, ps.IsWithinScope(t1), true) + + // in the first interval + t2, err := time.Parse("2006-01-02 15:04:05", "2017-12-08 03:01:53") + assert.NoError(t, err) + assert.Equal(t, ps.IsWithinScope(t2), true) + + // too early + t3, err := time.Parse("2006-01-02 15:04:05", "2017-12-08 01:01:53") + assert.NoError(t, err) + assert.Equal(t, ps.IsWithinScope(t3), false) + + // between two periods + t4, err := time.Parse("2006-01-02 15:04:05", "2017-12-08 03:03:53") + assert.NoError(t, err) + assert.Equal(t, ps.IsWithinScope(t4), false) + + // too late + t5, err := time.Parse("2006-01-02 15:04:05", "2017-12-08 23:01:53") + assert.NoError(t, err) + assert.Equal(t, ps.IsWithinScope(t5), false) + +} + +func TestParsePeriods(t *testing.T) { + tests := []struct { + name string + args string + want Periods + wantErr bool + }{ + { + name: "blank string", + args: "", + want: nil, + wantErr: true, + }, + { + name: "invalid string", + args: "whatever", + want: nil, + wantErr: true, + }, + + { + name: "ok 1 period", + args: "09:30-11:30", + want: []*Period{ + {9, 30, 11, 30}, + }, + wantErr: false, + }, + { + name: "ok 1 period, support(-0)", + args: "-0:10-11:-0", + want: []*Period{ + {0, 10, 11, 0}, + }, + wantErr: false, + }, + { + name: "fail 1 period", + args: "09:30a-11:30", + want: nil, + wantErr: true, + }, + { + name: "fail 1 period", + args: "09:30 11:30", + want: nil, + wantErr: true, + }, + { + name: "fail 1 period", + args: "09:00-11:-10", + want: nil, + wantErr: true, + }, + { + name: "fail 1 period, invalid minute", + args: "09:60-11:30", + want: nil, + wantErr: true, + }, + { + name: "fail 1 period, invalid hour", + args: "09:30-24:30", + want: nil, + wantErr: true, + }, + { + name: "fail 1 period", + args: "9:30-11:300", + want: nil, + wantErr: true, + }, + { + name: "fail 1 period, invalid period", + args: "09:30-08:30", + want: nil, + wantErr: true, + }, + + { + name: "ok 2 periods, no leading zero", + args: "9:30-11:30;11:30-13:30", + want: []*Period{ + {9, 30, 11, 30}, + {11, 30, 13, 30}, + }, + wantErr: false, + }, + { + name: "ok 2 periods, periods disorder", + args: "11:30-13:30;9:30-11:30", + want: []*Period{ + {11, 30, 13, 30}, + {9, 30, 11, 30}, + }, + wantErr: false, + }, + { + name: "ok 2 periods,support(-0)", + args: "-0:-0--0:30;9:-0-11:-0", + want: []*Period{ + {0, 0, 0, 30}, + {9, 0, 11, 0}, + }, + wantErr: false, + }, + { + name: "fail 2 periods,blank", + args: "11:30-13:30;", + want: nil, + wantErr: true, + }, + { + name: "fail 2 periods, unexpected newline", + args: "11:3-13:3;21:0-\n23:0", + want: nil, + wantErr: true, + }, + { + name: "fail 2 periods, periods overlap", + args: "9:3-51:30;9:30-21:30", + want: nil, + wantErr: true, + }, + + { + name: "ok 3 periods disorder", + args: "09:30-11:30;20:30-21:30;11:30-13:30", + want: []*Period{ + {9, 30, 11, 30}, + {20, 30, 21, 30}, + {11, 30, 13, 30}, + }, + wantErr: false, + }, + { + name: "ok 3 periods, no leading zero", + args: "9:3-11:30;20:30-21:30;11:30-13:30", + want: []*Period{ + {9, 3, 11, 30}, + {20, 30, 21, 30}, + {11, 30, 13, 30}, + }, + wantErr: false, + }, + { + name: "fail 3 periods, periods overlap", + args: "9:3-51:30;9:30-21:30;11:30-13:30", + want: nil, + wantErr: true, + }, + + { + name: "ok", + args: "01:30-2:00;2:30-3:0;6:30-7:0;3:30-4:0;7:30-8:0;8:30-9:00;9:30-10:0", + want: []*Period{ + {1, 30, 2, 0}, + {2, 30, 3, 0}, + {6, 30, 7, 0}, + {3, 30, 4, 0}, + {7, 30, 8, 0}, + {8, 30, 9, 0}, + {9, 30, 10, 0}, + }, + wantErr: false, + }, + { + name: "fail ;;", + args: "01:30-2:00;2:30-3:0;;6:30-7:0;3:30-4:0;7:30-8:0;8:30-9:00;9:30-10:0", + want: nil, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ParsePeriods(tt.args) + if err != nil { + t.Logf("ParsePeriods result: %v\n", err) + } + assert.Equalf(t, tt.wantErr, err != nil, "ParsePeriods(%v)", tt.args) + assert.Equalf(t, tt.want, got, "ParsePeriods(%v)", tt.args) + }) + } +} diff --git a/pkg/process_queue/process_queue_repo.go b/pkg/process_queue/process_queue_repo.go index 79aecee02..402736234 100644 --- a/pkg/process_queue/process_queue_repo.go +++ b/pkg/process_queue/process_queue_repo.go @@ -5,7 +5,7 @@ import ( "fmt" "sync" - pkgLog "github.com/actiontech/dms/internal/pkg/log" + pkgLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" utilIo "github.com/actiontech/dms/pkg/dms-common/pkg/io" diff --git a/pkg/process_queue/process_queue_test.go b/pkg/process_queue/process_queue_test.go index a191af02c..2fcfa7d6c 100644 --- a/pkg/process_queue/process_queue_test.go +++ b/pkg/process_queue/process_queue_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - pkgLog "github.com/actiontech/dms/internal/pkg/log" + pkgLog "github.com/actiontech/dms/pkg/dms-common/pkg/log" utilIo "github.com/actiontech/dms/pkg/dms-common/pkg/io" diff --git a/pkg/rand/password.go b/pkg/rand/password.go new file mode 100644 index 000000000..322400cbf --- /dev/null +++ b/pkg/rand/password.go @@ -0,0 +1,21 @@ +package rand + +import ( + "math/rand" + "strings" + "time" +) + +func GenPassword(n int) string { + src := rand.NewSource(time.Now().UnixNano()) + r := rand.New(src) + + chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") + var b strings.Builder + for i := 0; i < n; i++ { + b.WriteRune(chars[r.Intn(len(chars))]) + } + return b.String() +} + + diff --git a/pkg/rand/password_test.go b/pkg/rand/password_test.go new file mode 100644 index 000000000..3acdaa02b --- /dev/null +++ b/pkg/rand/password_test.go @@ -0,0 +1,20 @@ +package rand + +import ( + "math/rand" + "testing" +) + +func TestGenPassword(t *testing.T) { + for i := 0; i < 1000; i++ { + n := rand.Intn(20) + 1 // n in the range of [1,20] + p1 := GenPassword(n) + + if len(p1) != n { + t.Errorf("Password length error: expected %d, actual %d", n, len(p1)) + } + if len(p1) != n { + t.Errorf("The length of the generated password is incorrect:%d != %d", len(p1), n) + } + } +} diff --git a/pkg/timeutil/timeutil.go b/pkg/timeutil/timeutil.go new file mode 100644 index 000000000..abf1c99c9 --- /dev/null +++ b/pkg/timeutil/timeutil.go @@ -0,0 +1,22 @@ +package timeutil + +import "time" + +// ToUTC returns a pointer to the same instant expressed in UTC. +// Returns nil if t is nil. +// +// The go-sql-driver/mysql with loc=Local symmetrically converts on both +// write (In(loc)) and read (parsed as loc), so the time.Time already +// carries the correct instant; calling UTC() only normalises the zone. +func ToUTC(t *time.Time) *time.Time { + if t == nil { + return nil + } + utc := t.UTC() + return &utc +} + +// NowUTC returns the current time in UTC. +func NowUTC() time.Time { + return time.Now().UTC() +} diff --git a/vendor/github.com/99designs/gqlgen/LICENSE b/vendor/github.com/99designs/gqlgen/LICENSE index 10bb21c07..2287a8dba 100644 --- a/vendor/github.com/99designs/gqlgen/LICENSE +++ b/vendor/github.com/99designs/gqlgen/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2020 gqlgen authors +Copyright (c) 2025 gqlgen authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/99designs/gqlgen/api/generate.go b/vendor/github.com/99designs/gqlgen/api/generate.go index 6619dd5cd..3dc5aad8e 100644 --- a/vendor/github.com/99designs/gqlgen/api/generate.go +++ b/vendor/github.com/99designs/gqlgen/api/generate.go @@ -5,6 +5,8 @@ import ( "regexp" "syscall" + "golang.org/x/tools/imports" + "github.com/99designs/gqlgen/codegen" "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/plugin" @@ -13,6 +15,11 @@ import ( "github.com/99designs/gqlgen/plugin/resolvergen" ) +var ( + urlRegex = regexp.MustCompile(`(?s)@link.*\(.*url:\s*?"(.*?)"[^)]+\)`) // regex to grab the url of a link directive, should it exist + versionRegex = regexp.MustCompile(`v(\d+).(\d+)$`) // regex to grab the version number from a url +) + func Generate(cfg *config.Config, option ...Option) error { _ = syscall.Unlink(cfg.Exec.Filename) if cfg.Model.IsDefined() { @@ -26,31 +33,48 @@ func Generate(cfg *config.Config, option ...Option) error { plugins = append(plugins, resolvergen.New()) if cfg.Federation.IsDefined() { if cfg.Federation.Version == 0 { // default to using the user's choice of version, but if unset, try to sort out which federation version to use - urlRegex := regexp.MustCompile(`(?s)@link.*\(.*url:.*?"(.*?)"[^)]+\)`) // regex to grab the url of a link directive, should it exist - // check the sources, and if one is marked as federation v2, we mark the entirety to be generated using that format for _, v := range cfg.Sources { cfg.Federation.Version = 1 urlString := urlRegex.FindStringSubmatch(v.Input) - if urlString != nil && urlString[1] == "https://specs.apollo.dev/federation/v2.0" { - cfg.Federation.Version = 2 - break + // e.g. urlString[1] == "https://specs.apollo.dev/federation/v2.7" + if urlString != nil { + matches := versionRegex.FindStringSubmatch(urlString[1]) + if matches[1] == "2" { + cfg.Federation.Version = 2 + break + } } } } - plugins = append([]plugin.Plugin{federation.New(cfg.Federation.Version)}, plugins...) + federationPlugin, err := federation.New(cfg.Federation.Version, cfg) + if err != nil { + return fmt.Errorf("failed to construct the Federation plugin: %w", err) + } + plugins = append([]plugin.Plugin{federationPlugin}, plugins...) } for _, o := range option { o(cfg, &plugins) } + if cfg.LocalPrefix != "" { + imports.LocalPrefix = cfg.LocalPrefix + } + for _, p := range plugins { if inj, ok := p.(plugin.EarlySourceInjector); ok { if s := inj.InjectSourceEarly(); s != nil { cfg.Sources = append(cfg.Sources, s) } } + if inj, ok := p.(plugin.EarlySourcesInjector); ok { + s, err := inj.InjectSourcesEarly() + if err != nil { + return fmt.Errorf("%s: %w", p.Name(), err) + } + cfg.Sources = append(cfg.Sources, s...) + } } if err := cfg.LoadSchema(); err != nil { @@ -63,6 +87,13 @@ func Generate(cfg *config.Config, option ...Option) error { cfg.Sources = append(cfg.Sources, s) } } + if inj, ok := p.(plugin.LateSourcesInjector); ok { + s, err := inj.InjectSourcesLate(cfg.Schema) + if err != nil { + return fmt.Errorf("%s: %w", p.Name(), err) + } + cfg.Sources = append(cfg.Sources, s...) + } } // LoadSchema again now we have everything @@ -74,6 +105,15 @@ func Generate(cfg *config.Config, option ...Option) error { return fmt.Errorf("generating core failed: %w", err) } + for _, p := range plugins { + if mut, ok := p.(plugin.SchemaMutator); ok { + err := mut.MutateSchema(cfg.Schema) + if err != nil { + return fmt.Errorf("%s: %w", p.Name(), err) + } + } + } + for _, p := range plugins { if mut, ok := p.(plugin.ConfigMutator); ok { err := mut.MutateConfig(cfg) @@ -83,21 +123,15 @@ func Generate(cfg *config.Config, option ...Option) error { } } // Merge again now that the generated models have been injected into the typemap - data, err := codegen.BuildData(cfg) + dataPlugins := make([]any, len(plugins)) + for index := range plugins { + dataPlugins[index] = plugins[index] + } + data, err := codegen.BuildData(cfg, dataPlugins...) if err != nil { return fmt.Errorf("merging type systems failed: %w", err) } - if err = codegen.GenerateCode(data); err != nil { - return fmt.Errorf("generating core failed: %w", err) - } - - if !cfg.SkipModTidy { - if err = cfg.Packages.ModTidy(); err != nil { - return fmt.Errorf("tidy failed: %w", err) - } - } - for _, p := range plugins { if mut, ok := p.(plugin.CodeGenerator); ok { err := mut.GenerateCode(data) @@ -111,6 +145,11 @@ func Generate(cfg *config.Config, option ...Option) error { return fmt.Errorf("generating core failed: %w", err) } + if !cfg.SkipModTidy { + if err = cfg.Packages.ModTidy(); err != nil { + return fmt.Errorf("tidy failed: %w", err) + } + } if !cfg.SkipValidation { if err := validate(cfg); err != nil { return fmt.Errorf("validation failed: %w", err) diff --git a/vendor/github.com/99designs/gqlgen/api/option.go b/vendor/github.com/99designs/gqlgen/api/option.go index d376193df..344aa819c 100644 --- a/vendor/github.com/99designs/gqlgen/api/option.go +++ b/vendor/github.com/99designs/gqlgen/api/option.go @@ -29,19 +29,20 @@ func PrependPlugin(p plugin.Plugin) Option { // ReplacePlugin replaces any existing plugin with a matching plugin name func ReplacePlugin(p plugin.Plugin) Option { return func(cfg *config.Config, plugins *[]plugin.Plugin) { - if plugins != nil { - found := false - ps := *plugins - for i, o := range ps { - if p.Name() == o.Name() { - ps[i] = p - found = true - } - } - if !found { - ps = append(ps, p) + if plugins == nil { + return + } + found := false + ps := *plugins + for i, o := range ps { + if p.Name() == o.Name() { + ps[i] = p + found = true } - *plugins = ps } + if !found { + ps = append(ps, p) + } + *plugins = ps } } diff --git a/vendor/github.com/99designs/gqlgen/codegen/args.go b/vendor/github.com/99designs/gqlgen/codegen/args.go index 0fd30fffd..736680b39 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/args.go +++ b/vendor/github.com/99designs/gqlgen/codegen/args.go @@ -5,9 +5,10 @@ import ( "go/types" "strings" + "github.com/vektah/gqlparser/v2/ast" + "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" ) type ArgSet struct { @@ -17,19 +18,20 @@ type ArgSet struct { type FieldArgument struct { *ast.ArgumentDefinition - TypeReference *config.TypeReference - VarName string // The name of the var in go - Object *Object // A link back to the parent object - Default interface{} // The default value - Directives []*Directive - Value interface{} // value set in Data + TypeReference *config.TypeReference + VarName string // The name of the var in go + Object *Object // A link back to the parent object + Default any // The default value + Directives []*Directive + Value any // value set in Data + CallArgumentDirectivesWithNull bool } -// ImplDirectives get not Builtin and location ARGUMENT_DEFINITION directive +// ImplDirectives get not SkipRuntime and location ARGUMENT_DEFINITION directive func (f *FieldArgument) ImplDirectives() []*Directive { d := make([]*Directive, 0) for i := range f.Directives { - if !f.Directives[i].Builtin && f.Directives[i].IsLocation(ast.LocationArgumentDefinition) { + if !f.Directives[i].SkipRuntime && f.Directives[i].IsLocation(ast.LocationArgumentDefinition) { d = append(d, f.Directives[i]) } } @@ -56,11 +58,12 @@ func (b *builder) buildArg(obj *Object, arg *ast.ArgumentDefinition) (*FieldArgu return nil, err } newArg := FieldArgument{ - ArgumentDefinition: arg, - TypeReference: tr, - Object: obj, - VarName: templates.ToGoPrivate(arg.Name), - Directives: argDirs, + ArgumentDefinition: arg, + TypeReference: tr, + Object: obj, + VarName: templates.ToGoPrivate(arg.Name), + Directives: argDirs, + CallArgumentDirectivesWithNull: b.Config.CallArgumentDirectivesWithNull, } if arg.DefaultValue != nil { @@ -103,9 +106,9 @@ nextArg: return newArgs, nil } -func (a *Data) Args() map[string][]*FieldArgument { +func (d *Data) Args() map[string][]*FieldArgument { ret := map[string][]*FieldArgument{} - for _, o := range a.Objects { + for _, o := range d.Objects { for _, f := range o.Fields { if len(f.Args) > 0 { ret[f.ArgsFunc()] = f.Args @@ -113,9 +116,9 @@ func (a *Data) Args() map[string][]*FieldArgument { } } - for _, d := range a.Directives() { - if len(d.Args) > 0 { - ret[d.ArgsFunc()] = d.Args + for _, directive := range d.Directives() { + if len(directive.Args) > 0 { + ret[directive.ArgsFunc()] = directive.Args } } return ret diff --git a/vendor/github.com/99designs/gqlgen/codegen/args.gotpl b/vendor/github.com/99designs/gqlgen/codegen/args.gotpl index 7b541ae1f..6c267bc65 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/args.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/args.gotpl @@ -1,36 +1,106 @@ +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} + {{ range $name, $args := .Args }} -func (ec *executionContext) {{ $name }}(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { +{{ if $useFunctionSyntaxForExecutionContext -}} +func {{ $name }}(ctx context.Context, ec *executionContext, rawArgs map[string]any) (map[string]any, error) { +{{- else -}} +func (ec *executionContext) {{ $name }}(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { +{{- end }} var err error - args := map[string]interface{}{} + args := map[string]any{} + {{- range $i, $arg := . }} - var arg{{$i}} {{ $arg.TypeReference.GO | ref}} - if tmp, ok := rawArgs[{{$arg.Name|quote}}]; ok { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField({{$arg.Name|quote}})) + {{ if $arg.ImplDirectives }} + {{ if $useFunctionSyntaxForExecutionContext -}} + arg{{$i}}, err := {{ $name }}{{$arg.Name | go}}(ctx, ec, rawArgs) + {{- else -}} + arg{{$i}}, err := ec.{{ $name }}{{$arg.Name | go}}(ctx, rawArgs) + {{- end }} + {{- else -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + arg{{$i}}, err := graphql.ProcessArgFieldWithEC(ctx, ec, rawArgs, {{$arg.Name|quote}}, {{ $arg.TypeReference.UnmarshalFunc }}) + {{- else -}} + arg{{$i}}, err := graphql.ProcessArgField(ctx, rawArgs, {{$arg.Name|quote}}, ec.{{ $arg.TypeReference.UnmarshalFunc }}) + {{- end }} + {{- end }} + if err != nil { + return nil, err + } + args[{{$arg.Name|quote}}] = arg{{$i}} + {{- end }} + return args, nil +} + + {{- range $i, $arg := . }} + {{ if not $arg.ImplDirectives -}} + {{- continue -}} + {{- end }} + {{ if $useFunctionSyntaxForExecutionContext -}} + func {{ $name }}{{$arg.Name | go}}( + ctx context.Context, + ec *executionContext, + rawArgs map[string]any, + ) ({{ $arg.TypeReference.GO | ref}}, error) { + {{- else -}} + func (ec *executionContext) {{ $name }}{{$arg.Name | go}}( + ctx context.Context, + rawArgs map[string]any, + ) ({{ $arg.TypeReference.GO | ref}}, error) { + {{- end }} + {{- if not .CallArgumentDirectivesWithNull}} + {{- /* + We won't call the directive if the argument is null. + Set call_argument_directives_with_null to true to call directives + even if the argument is null. + */ -}} + if _, ok := rawArgs[{{$arg.Name|quote}}]; !ok { + var zeroVal {{ $arg.TypeReference.GO | ref}} + return zeroVal, nil + } + {{end}} + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField({{$arg.Name|quote}})) {{- if $arg.ImplDirectives }} - directive0 := func(ctx context.Context) (interface{}, error) { return ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, tmp) } - {{ template "implDirectives" $arg }} - tmp, err = directive{{$arg.ImplDirectives|len}}(ctx) + directive0 := func(ctx context.Context) (any, error) { + tmp, ok := rawArgs[{{$arg.Name|quote}}] + if !ok { + var zeroVal {{ $arg.TypeReference.GO | ref}} + return zeroVal, nil + } + {{ if $useFunctionSyntaxForExecutionContext -}} + return {{ $arg.TypeReference.UnmarshalFunc }}(ctx, ec, tmp) + {{- else -}} + return ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, tmp) + {{- end }} + } + {{ template "implDirectives" (dict "Field" $arg "UseFunctionSyntaxForExecutionContext" $useFunctionSyntaxForExecutionContext) }} + tmp, err := directive{{$arg.ImplDirectives|len}}(ctx) if err != nil { - return nil, graphql.ErrorOnPath(ctx, err) + var zeroVal {{ $arg.TypeReference.GO | ref}} + return zeroVal, graphql.ErrorOnPath(ctx, err) } if data, ok := tmp.({{ $arg.TypeReference.GO | ref }}) ; ok { - arg{{$i}} = data + return data, nil {{- if $arg.TypeReference.IsNilable }} } else if tmp == nil { - arg{{$i}} = nil + var zeroVal {{ $arg.TypeReference.GO | ref}} + return zeroVal, nil {{- end }} } else { - return nil, graphql.ErrorOnPath(ctx, fmt.Errorf(`unexpected type %T from directive, should be {{ $arg.TypeReference.GO }}`, tmp)) + var zeroVal {{ $arg.TypeReference.GO | ref}} + return zeroVal, graphql.ErrorOnPath(ctx, fmt.Errorf(`unexpected type %T from directive, should be {{ $arg.TypeReference.GO }}`, tmp)) } {{- else }} - arg{{$i}}, err = ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, tmp) - if err != nil { - return nil, err + if tmp, ok := rawArgs[{{$arg.Name|quote}}]; ok { + {{ if $useFunctionSyntaxForExecutionContext -}} + return {{ $arg.TypeReference.UnmarshalFunc }}(ctx, ec, tmp) + {{- else -}} + return ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, tmp) + {{- end }} } + + var zeroVal {{ $arg.TypeReference.GO | ref}} + return zeroVal, nil {{- end }} } - args[{{$arg.Name|quote}}] = arg{{$i}} - {{- end }} - return args, nil -} + {{end}} {{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/binder.go b/vendor/github.com/99designs/gqlgen/codegen/config/binder.go index bedc23bc6..c96b2618d 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/config/binder.go +++ b/vendor/github.com/99designs/gqlgen/codegen/config/binder.go @@ -5,12 +5,13 @@ import ( "fmt" "go/token" "go/types" + "strings" + "github.com/vektah/gqlparser/v2/ast" "golang.org/x/tools/go/packages" "github.com/99designs/gqlgen/codegen/templates" "github.com/99designs/gqlgen/internal/code" - "github.com/vektah/gqlparser/v2/ast" ) var ErrTypeNotFound = errors.New("unable to find type") @@ -20,6 +21,7 @@ type Binder struct { pkgs *code.Packages schema *ast.Schema cfg *Config + tctx *types.Context References []*TypeReference SawInvalid bool objectCache map[string]map[string]types.Object @@ -34,7 +36,7 @@ func (c *Config) NewBinder() *Binder { } func (b *Binder) TypePosition(typ types.Type) token.Position { - named, isNamed := typ.(*types.Named) + named, isNamed := code.Unalias(typ).(*types.Named) if !isNamed { return token.Position{ Filename: "unknown", @@ -59,13 +61,13 @@ func (b *Binder) FindTypeFromName(name string) (types.Type, error) { return b.FindType(pkgName, typeName) } -func (b *Binder) FindType(pkgName string, typeName string) (types.Type, error) { +func (b *Binder) FindType(pkgName, typeName string) (types.Type, error) { if pkgName == "" { - if typeName == "map[string]interface{}" { + if typeName == "map[string]any" || typeName == "map[string]interface{}" { return MapType, nil } - if typeName == "interface{}" { + if typeName == "any" || typeName == "interface{}" { return InterfaceType, nil } } @@ -75,28 +77,37 @@ func (b *Binder) FindType(pkgName string, typeName string) (types.Type, error) { return nil, err } - if fun, isFunc := obj.(*types.Func); isFunc { - return fun.Type().(*types.Signature).Params().At(0).Type(), nil + t := code.Unalias(obj.Type()) + if _, isFunc := obj.(*types.Func); isFunc { + return code.Unalias(t.(*types.Signature).Params().At(0).Type()), nil + } + return t, nil +} + +func (b *Binder) InstantiateType(orig types.Type, targs []types.Type) (types.Type, error) { + if b.tctx == nil { + b.tctx = types.NewContext() } - return obj.Type(), nil + + return types.Instantiate(b.tctx, orig, targs, false) } var ( - MapType = types.NewMap(types.Typ[types.String], types.NewInterfaceType(nil, nil).Complete()) - InterfaceType = types.NewInterfaceType(nil, nil) + MapType = types.NewMap(types.Typ[types.String], types.Universe.Lookup("any").Type()) + InterfaceType = types.Universe.Lookup("any").Type() ) func (b *Binder) DefaultUserObject(name string) (types.Type, error) { models := b.cfg.Models[name].Model if len(models) == 0 { - return nil, fmt.Errorf(name + " not found in typemap") + return nil, fmt.Errorf("%s not found in typemap", name) } - if models[0] == "map[string]interface{}" { + if models[0] == "map[string]any" || models[0] == "map[string]interface{}" { return MapType, nil } - if models[0] == "interface{}" { + if models[0] == "any" || models[0] == "interface{}" { return InterfaceType, nil } @@ -110,12 +121,12 @@ func (b *Binder) DefaultUserObject(name string) (types.Type, error) { return nil, err } - return obj.Type(), nil + return code.Unalias(obj.Type()), nil } -func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, error) { +func (b *Binder) FindObject(pkgName, typeName string) (types.Object, error) { if pkgName == "" { - return nil, fmt.Errorf("package cannot be nil") + return nil, fmt.Errorf("package cannot be nil in FindObject for type: %s", typeName) } pkg := b.pkgs.LoadWithTypes(pkgName) @@ -183,15 +194,19 @@ func (b *Binder) PointerTo(ref *TypeReference) *TypeReference { // TypeReference is used by args and field types. The Definition can refer to both input and output types. type TypeReference struct { - Definition *ast.Definition - GQL *ast.Type - GO types.Type // Type of the field being bound. Could be a pointer or a value type of Target. - Target types.Type // The actual type that we know how to bind to. May require pointer juggling when traversing to fields. - CastType types.Type // Before calling marshalling functions cast from/to this base type - Marshaler *types.Func // When using external marshalling functions this will point to the Marshal function - Unmarshaler *types.Func // When using external marshalling functions this will point to the Unmarshal function - IsMarshaler bool // Does the type implement graphql.Marshaler and graphql.Unmarshaler - IsContext bool // Is the Marshaler/Unmarshaller the context version; applies to either the method or interface variety. + Definition *ast.Definition + GQL *ast.Type + GO types.Type // Type of the field being bound. Could be a pointer or a value type of Target. + Target types.Type // The actual type that we know how to bind to. May require pointer juggling when traversing to fields. + CastType types.Type // Before calling marshalling functions cast from/to this base type + Marshaler *types.Func // When using external marshalling functions this will point to the Marshal function + Unmarshaler *types.Func // When using external marshalling functions this will point to the Unmarshal function + IsMarshaler bool // Does the type implement graphql.Marshaler and graphql.Unmarshaler + IsOmittable bool // Is the type wrapped with Omittable + IsContext bool // Is the Marshaler/Unmarshaller the context version; applies to either the method or interface variety. + PointersInUnmarshalInput bool // Inverse values and pointers in return. + IsRoot bool // Is the type a root level definition such as Query, Mutation or Subscription + EnumValues []EnumValueReference } func (ref *TypeReference) Elem() *TypeReference { @@ -210,91 +225,115 @@ func (ref *TypeReference) Elem() *TypeReference { return nil } -func (t *TypeReference) IsPtr() bool { - _, isPtr := t.GO.(*types.Pointer) +func (ref *TypeReference) IsPtr() bool { + _, isPtr := ref.GO.(*types.Pointer) return isPtr } // fix for https://github.com/golang/go/issues/31103 may make it possible to remove this (may still be useful) -func (t *TypeReference) IsPtrToPtr() bool { - if p, isPtr := t.GO.(*types.Pointer); isPtr { +func (ref *TypeReference) IsPtrToPtr() bool { + if p, isPtr := ref.GO.(*types.Pointer); isPtr { _, isPtr := p.Elem().(*types.Pointer) return isPtr } return false } -func (t *TypeReference) IsNilable() bool { - return IsNilable(t.GO) +func (ref *TypeReference) IsNilable() bool { + return IsNilable(ref.GO) } -func (t *TypeReference) IsSlice() bool { - _, isSlice := t.GO.(*types.Slice) - return t.GQL.Elem != nil && isSlice +func (ref *TypeReference) IsSlice() bool { + _, isSlice := ref.GO.(*types.Slice) + return ref.GQL.Elem != nil && isSlice } -func (t *TypeReference) IsPtrToSlice() bool { - if t.IsPtr() { - _, isPointerToSlice := t.GO.(*types.Pointer).Elem().(*types.Slice) +func (ref *TypeReference) IsPtrToSlice() bool { + if ref.IsPtr() { + _, isPointerToSlice := ref.GO.(*types.Pointer).Elem().(*types.Slice) return isPointerToSlice } return false } -func (t *TypeReference) IsNamed() bool { - _, isSlice := t.GO.(*types.Named) - return isSlice +func (ref *TypeReference) IsPtrToIntf() bool { + if ref.IsPtr() { + _, isPointerToInterface := types.Unalias(ref.GO.(*types.Pointer).Elem()).(*types.Interface) + return isPointerToInterface + } + return false } -func (t *TypeReference) IsStruct() bool { - _, isStruct := t.GO.Underlying().(*types.Struct) - return isStruct +func (ref *TypeReference) IsNamed() bool { + _, ok := ref.GO.(*types.Named) + return ok } -func (t *TypeReference) IsScalar() bool { - return t.Definition.Kind == ast.Scalar +func (ref *TypeReference) IsStruct() bool { + _, ok := ref.GO.Underlying().(*types.Struct) + return ok } -func (t *TypeReference) UniquenessKey() string { +func (ref *TypeReference) IsScalar() bool { + return ref.Definition.Kind == ast.Scalar +} + +func (ref *TypeReference) IsMap() bool { + return ref.GO == MapType +} + +func (ref *TypeReference) UniquenessKey() string { nullability := "O" - if t.GQL.NonNull { + if ref.GQL.NonNull { nullability = "N" } elemNullability := "" - if t.GQL.Elem != nil && t.GQL.Elem.NonNull { + if ref.GQL.Elem != nil && ref.GQL.Elem.NonNull { // Fix for #896 elemNullability = "ᚄ" } - return nullability + t.Definition.Name + "2" + templates.TypeIdentifier(t.GO) + elemNullability + return nullability + ref.Definition.Name + "2" + templates.TypeIdentifier(ref.GO) + elemNullability } -func (t *TypeReference) MarshalFunc() string { - if t.Definition == nil { - panic(errors.New("Definition missing for " + t.GQL.Name())) +func (ref *TypeReference) MarshalFunc() string { + if ref.Definition == nil { + panic(errors.New("Definition missing for " + ref.GQL.Name())) } - if t.Definition.Kind == ast.InputObject { + if ref.Definition.Kind == ast.InputObject { return "" } - return "marshal" + t.UniquenessKey() + return "marshal" + ref.UniquenessKey() +} + +func (ref *TypeReference) MarshalFuncFunctionSyntax() string { + return ref.MarshalFunc() + "F" } -func (t *TypeReference) UnmarshalFunc() string { - if t.Definition == nil { - panic(errors.New("Definition missing for " + t.GQL.Name())) +func (ref *TypeReference) UnmarshalFunc() string { + if ref.Definition == nil { + panic(errors.New("Definition missing for " + ref.GQL.Name())) } - if !t.Definition.IsInputType() { + if !ref.Definition.IsInputType() { return "" } - return "unmarshal" + t.UniquenessKey() + return "unmarshal" + ref.UniquenessKey() +} + +func (ref *TypeReference) UnmarshalFuncFunctionSyntax() string { + return ref.UnmarshalFunc() + "F" +} + +func (ref *TypeReference) IsTargetNilable() bool { + return IsNilable(ref.Target) } -func (t *TypeReference) IsTargetNilable() bool { - return IsNilable(t.Target) +func (ref *TypeReference) HasEnumValues() bool { + return len(ref.EnumValues) > 0 } func (b *Binder) PushRef(ret *TypeReference) { @@ -313,11 +352,42 @@ func isIntf(t types.Type) bool { if t == nil { return true } - _, ok := t.(*types.Interface) + _, ok := types.Unalias(t).(*types.Interface) return ok } +func unwrapOmittable(t types.Type) (types.Type, bool) { + if t == nil { + return nil, false + } + named, ok := t.(*types.Named) + if !ok { + return t, false + } + if named.Origin().String() != "github.com/99designs/gqlgen/graphql.Omittable[T any]" { + return t, false + } + return named.TypeArgs().At(0), true +} + func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret *TypeReference, err error) { + if bindTarget != nil { + bindTarget = code.Unalias(bindTarget) + } + if innerType, ok := unwrapOmittable(bindTarget); ok { + if schemaType.NonNull { + return nil, fmt.Errorf("%s is wrapped with Omittable but non-null", schemaType.Name()) + } + + ref, err := b.TypeReference(schemaType, innerType) + if err != nil { + return nil, err + } + + ref.IsOmittable = true + return ref, err + } + if !isValid(bindTarget) { b.SawInvalid = true return nil, fmt.Errorf("%s has an invalid type", schemaType.Name()) @@ -336,7 +406,7 @@ func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret } for _, model := range b.cfg.Models[schemaType.Name()].Model { - if model == "map[string]interface{}" { + if model == "map[string]any" || model == "map[string]interface{}" { if !isMap(bindTarget) { continue } @@ -344,10 +414,11 @@ func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret Definition: def, GQL: schemaType, GO: MapType, + IsRoot: b.cfg.IsRoot(def), }, nil } - if model == "interface{}" { + if model == "any" || model == "interface{}" { if !isIntf(bindTarget) { continue } @@ -355,6 +426,7 @@ func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret Definition: def, GQL: schemaType, GO: InterfaceType, + IsRoot: b.cfg.IsRoot(def), }, nil } @@ -366,29 +438,35 @@ func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret ref := &TypeReference{ Definition: def, GQL: schemaType, + IsRoot: b.cfg.IsRoot(def), } obj, err := b.FindObject(pkgName, typeName) if err != nil { return nil, err } - - if fun, isFunc := obj.(*types.Func); isFunc { - ref.GO = fun.Type().(*types.Signature).Params().At(0).Type() - ref.IsContext = fun.Type().(*types.Signature).Results().At(0).Type().String() == "github.com/99designs/gqlgen/graphql.ContextMarshaler" + t := code.Unalias(obj.Type()) + if values := b.enumValues(def); len(values) > 0 { + err = b.enumReference(ref, obj, values) + if err != nil { + return nil, err + } + } else if fun, isFunc := obj.(*types.Func); isFunc { + ref.GO = code.Unalias(t.(*types.Signature).Params().At(0).Type()) + ref.IsContext = code.Unalias(t.(*types.Signature).Results().At(0).Type()).String() == "github.com/99designs/gqlgen/graphql.ContextMarshaler" ref.Marshaler = fun ref.Unmarshaler = types.NewFunc(0, fun.Pkg(), "Unmarshal"+typeName, nil) - } else if hasMethod(obj.Type(), "MarshalGQLContext") && hasMethod(obj.Type(), "UnmarshalGQLContext") { - ref.GO = obj.Type() + } else if hasMethod(t, "MarshalGQLContext") && hasMethod(t, "UnmarshalGQLContext") { + ref.GO = t ref.IsContext = true ref.IsMarshaler = true - } else if hasMethod(obj.Type(), "MarshalGQL") && hasMethod(obj.Type(), "UnmarshalGQL") { - ref.GO = obj.Type() + } else if hasMethod(t, "MarshalGQL") && hasMethod(t, "UnmarshalGQL") { + ref.GO = t ref.IsMarshaler = true - } else if underlying := basicUnderlying(obj.Type()); def.IsLeafType() && underlying != nil && underlying.Kind() == types.String { + } else if underlying := basicUnderlying(t); def.IsLeafType() && underlying != nil && underlying.Kind() == types.String { // TODO delete before v1. Backwards compatibility case for named types wrapping strings (see #595) - ref.GO = obj.Type() + ref.GO = t ref.CastType = underlying underlyingRef, err := b.TypeReference(&ast.Type{NamedType: "String"}, nil) @@ -399,7 +477,7 @@ func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret ref.Marshaler = underlyingRef.Marshaler ref.Unmarshaler = underlyingRef.Unmarshaler } else { - ref.GO = obj.Type() + ref.GO = t } ref.Target = ref.GO @@ -407,11 +485,26 @@ func (b *Binder) TypeReference(schemaType *ast.Type, bindTarget types.Type) (ret if bindTarget != nil { if err = code.CompatibleTypes(ref.GO, bindTarget); err != nil { - continue + // if the bind type implements the graphql.ContextMarshaler/graphql.ContextUnmarshaler/graphql.Marshaler/graphql.Unmarshaler interface, we can use it + if hasMethod(bindTarget, "MarshalGQLContext") && hasMethod(bindTarget, "UnmarshalGQLContext") { + ref.IsContext = true + ref.IsMarshaler = true + ref.Marshaler = nil + ref.Unmarshaler = nil + } else if hasMethod(bindTarget, "MarshalGQL") && hasMethod(bindTarget, "UnmarshalGQL") { + ref.IsContext = false + ref.IsMarshaler = true + ref.Marshaler = nil + ref.Unmarshaler = nil + } else { + continue + } } ref.GO = bindTarget } + ref.PointersInUnmarshalInput = b.cfg.ReturnPointersInUnmarshalInput + return ref, nil } @@ -427,6 +520,7 @@ func isValid(t types.Type) bool { } func (b *Binder) CopyModifiersFromAst(t *ast.Type, base types.Type) types.Type { + base = types.Unalias(base) if t.Elem != nil { child := b.CopyModifiersFromAst(t.Elem, base) if _, isStruct := child.Underlying().(*types.Struct); isStruct && !b.cfg.OmitSliceElementPointers { @@ -448,15 +542,19 @@ func (b *Binder) CopyModifiersFromAst(t *ast.Type, base types.Type) types.Type { } func IsNilable(t types.Type) bool { + // Note that we use types.Unalias rather than code.Unalias here + // because we want to always check the underlying type. + // code.Unalias only unwraps aliases in Go 1.23 + t = types.Unalias(t) if namedType, isNamed := t.(*types.Named); isNamed { return IsNilable(namedType.Underlying()) } _, isPtr := t.(*types.Pointer) - _, isMap := t.(*types.Map) + _, isNilableMap := t.(*types.Map) _, isInterface := t.(*types.Interface) _, isSlice := t.(*types.Slice) _, isChan := t.(*types.Chan) - return isPtr || isMap || isInterface || isSlice || isChan + return isPtr || isNilableMap || isInterface || isSlice || isChan } func hasMethod(it types.Type, name string) bool { @@ -477,8 +575,9 @@ func hasMethod(it types.Type, name string) bool { } func basicUnderlying(it types.Type) *types.Basic { + it = types.Unalias(it) if ptr, isPtr := it.(*types.Pointer); isPtr { - it = ptr.Elem() + it = types.Unalias(ptr.Elem()) } namedType, ok := it.(*types.Named) if !ok { @@ -491,3 +590,83 @@ func basicUnderlying(it types.Type) *types.Basic { return nil } + +type EnumValueReference struct { + Definition *ast.EnumValueDefinition + Object types.Object +} + +func (b *Binder) enumValues(def *ast.Definition) map[string]EnumValue { + if def.Kind != ast.Enum { + return nil + } + + if strings.HasPrefix(def.Name, "__") { + return nil + } + + model, ok := b.cfg.Models[def.Name] + if !ok { + return nil + } + + return model.EnumValues +} + +func (b *Binder) enumReference(ref *TypeReference, obj types.Object, values map[string]EnumValue) error { + if len(ref.Definition.EnumValues) != len(values) { + return fmt.Errorf("not all enum values are binded for %v", ref.Definition.Name) + } + + t := code.Unalias(obj.Type()) + if fn, ok := t.(*types.Signature); ok { + ref.GO = code.Unalias(fn.Params().At(0).Type()) + } else { + ref.GO = t + } + + str, err := b.TypeReference(&ast.Type{NamedType: "String"}, nil) + if err != nil { + return err + } + + ref.Marshaler = str.Marshaler + ref.Unmarshaler = str.Unmarshaler + ref.EnumValues = make([]EnumValueReference, 0, len(values)) + + for _, value := range ref.Definition.EnumValues { + v, ok := values[value.Name] + if !ok { + return fmt.Errorf("enum value not found for: %v, of enum: %v", value.Name, ref.Definition.Name) + } + + pkgName, typeName := code.PkgAndType(v.Value) + if pkgName == "" { + return fmt.Errorf("missing package name for %v", value.Name) + } + + valueObj, err := b.FindObject(pkgName, typeName) + if err != nil { + return err + } + + valueTyp := code.Unalias(valueObj.Type()) + if !types.AssignableTo(valueTyp, ref.GO) { + return fmt.Errorf("wrong type: %v, for enum value: %v, expected type: %v, of enum: %v", + valueTyp, value.Name, ref.GO, ref.Definition.Name) + } + + switch valueObj.(type) { + case *types.Const, *types.Var: + ref.EnumValues = append(ref.EnumValues, EnumValueReference{ + Definition: value, + Object: valueObj, + }) + default: + return fmt.Errorf("unsupported enum value for: %v, of enum: %v, only const and var allowed", + value.Name, ref.Definition.Name) + } + } + + return nil +} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/config.go b/vendor/github.com/99designs/gqlgen/codegen/config/config.go index c6de8625f..329195091 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/config/config.go +++ b/vendor/github.com/99designs/gqlgen/codegen/config/config.go @@ -2,38 +2,65 @@ package config import ( "bytes" + "errors" "fmt" + "go/types" + "io" "os" "path/filepath" "regexp" "sort" "strings" - "github.com/99designs/gqlgen/internal/code" "github.com/vektah/gqlparser/v2" "github.com/vektah/gqlparser/v2/ast" + "golang.org/x/tools/go/packages" "gopkg.in/yaml.v3" + + "github.com/99designs/gqlgen/codegen/templates" + "github.com/99designs/gqlgen/internal/code" ) type Config struct { - SchemaFilename StringList `yaml:"schema,omitempty"` - Exec ExecConfig `yaml:"exec"` - Model PackageConfig `yaml:"model,omitempty"` - Federation PackageConfig `yaml:"federation,omitempty"` - Resolver ResolverConfig `yaml:"resolver,omitempty"` - AutoBind []string `yaml:"autobind"` - Models TypeMap `yaml:"models,omitempty"` - StructTag string `yaml:"struct_tag,omitempty"` - Directives map[string]DirectiveConfig `yaml:"directives,omitempty"` - OmitSliceElementPointers bool `yaml:"omit_slice_element_pointers,omitempty"` - OmitGetters bool `yaml:"omit_getters,omitempty"` - StructFieldsAlwaysPointers bool `yaml:"struct_fields_always_pointers,omitempty"` - ResolversAlwaysReturnPointers bool `yaml:"resolvers_always_return_pointers,omitempty"` - SkipValidation bool `yaml:"skip_validation,omitempty"` - SkipModTidy bool `yaml:"skip_mod_tidy,omitempty"` - Sources []*ast.Source `yaml:"-"` - Packages *code.Packages `yaml:"-"` - Schema *ast.Schema `yaml:"-"` + SchemaFilename StringList `yaml:"schema,omitempty"` + Exec ExecConfig `yaml:"exec"` + Model PackageConfig `yaml:"model,omitempty"` + Federation PackageConfig `yaml:"federation,omitempty"` + Resolver ResolverConfig `yaml:"resolver,omitempty"` + AutoBind []string `yaml:"autobind"` + Models TypeMap `yaml:"models,omitempty"` + StructTag string `yaml:"struct_tag,omitempty"` + Directives map[string]DirectiveConfig `yaml:"directives,omitempty"` + LocalPrefix string `yaml:"local_prefix,omitempty"` + GoBuildTags StringList `yaml:"go_build_tags,omitempty"` + GoInitialisms GoInitialismsConfig `yaml:"go_initialisms,omitempty"` + OmitSliceElementPointers bool `yaml:"omit_slice_element_pointers,omitempty"` + OmitGetters bool `yaml:"omit_getters,omitempty"` + OmitInterfaceChecks bool `yaml:"omit_interface_checks,omitempty"` + OmitComplexity bool `yaml:"omit_complexity,omitempty"` + OmitGQLGenFileNotice bool `yaml:"omit_gqlgen_file_notice,omitempty"` + OmitGQLGenVersionInFileNotice bool `yaml:"omit_gqlgen_version_in_file_notice,omitempty"` + OmitRootModels bool `yaml:"omit_root_models,omitempty"` + OmitResolverFields bool `yaml:"omit_resolver_fields,omitempty"` + OmitPanicHandler bool `yaml:"omit_panic_handler,omitempty"` + UseFunctionSyntaxForExecutionContext bool `yaml:"use_function_syntax_for_execution_context,omitempty"` + // If this is set to true, argument directives that + // decorate a field with a null value will still be called. + // + // This enables argument directives to not just mutate + // argument values but to set them even if they're null. + CallArgumentDirectivesWithNull bool `yaml:"call_argument_directives_with_null,omitempty"` + StructFieldsAlwaysPointers bool `yaml:"struct_fields_always_pointers,omitempty"` + ReturnPointersInUnmarshalInput bool `yaml:"return_pointers_in_unmarshalinput,omitempty"` + ResolversAlwaysReturnPointers bool `yaml:"resolvers_always_return_pointers,omitempty"` + NullableInputOmittable bool `yaml:"nullable_input_omittable,omitempty"` + EnableModelJsonOmitemptyTag *bool `yaml:"enable_model_json_omitempty_tag,omitempty"` + EnableModelJsonOmitzeroTag *bool `yaml:"enable_model_json_omitzero_tag,omitempty"` + SkipValidation bool `yaml:"skip_validation,omitempty"` + SkipModTidy bool `yaml:"skip_mod_tidy,omitempty"` + Sources []*ast.Source `yaml:"-"` + Packages *code.Packages `yaml:"-"` + Schema *ast.Schema `yaml:"-"` // Deprecated: use Federation instead. Will be removed next release Federated bool `yaml:"federated,omitempty"` @@ -41,16 +68,28 @@ type Config struct { var cfgFilenames = []string{".gqlgen.yml", "gqlgen.yml", "gqlgen.yaml"} +// templatePackageNames is a list of packages names that the default templates use, in order to preload those for performance considerations +// any additional package added to the base templates should be added here to improve performance and load all packages in bulk +var templatePackageNames = []string{ + "context", "fmt", "io", "strconv", "time", "sync", "strings", "sync/atomic", "embed", "golang.org/x/sync/semaphore", + "errors", "bytes", "github.com/vektah/gqlparser/v2", "github.com/vektah/gqlparser/v2/ast", + "github.com/99designs/gqlgen/graphql", "github.com/99designs/gqlgen/graphql/introspection", +} + // DefaultConfig creates a copy of the default config func DefaultConfig() *Config { + falseValue := false return &Config{ - SchemaFilename: StringList{"schema.graphql"}, - Model: PackageConfig{Filename: "models_gen.go"}, - Exec: ExecConfig{Filename: "generated.go"}, - Directives: map[string]DirectiveConfig{}, - Models: TypeMap{}, - StructFieldsAlwaysPointers: true, - ResolversAlwaysReturnPointers: true, + SchemaFilename: StringList{"schema.graphql"}, + Model: PackageConfig{Filename: "models_gen.go"}, + Exec: ExecConfig{Filename: "generated.go"}, + Directives: map[string]DirectiveConfig{}, + Models: TypeMap{}, + StructFieldsAlwaysPointers: true, + ReturnPointersInUnmarshalInput: false, + ResolversAlwaysReturnPointers: true, + NullableInputOmittable: false, + EnableModelJsonOmitzeroTag: &falseValue, } } @@ -97,14 +136,18 @@ var path2regex = strings.NewReplacer( // LoadConfig reads the gqlgen.yml config file func LoadConfig(filename string) (*Config, error) { - config := DefaultConfig() - b, err := os.ReadFile(filename) if err != nil { return nil, fmt.Errorf("unable to read config: %w", err) } - dec := yaml.NewDecoder(bytes.NewReader(b)) + return ReadConfig(bytes.NewReader(b)) +} + +func ReadConfig(cfgFile io.Reader) (*Config, error) { + config := DefaultConfig() + + dec := yaml.NewDecoder(cfgFile) dec.KnownFields(true) if err := dec.Decode(config); err != nil { @@ -126,6 +169,7 @@ func CompleteConfig(config *Config) error { "include": {SkipRuntime: true}, "deprecated": {SkipRuntime: true}, "specifiedBy": {SkipRuntime: true}, + "oneOf": {SkipRuntime: true}, } for key, value := range defaultDirectives { @@ -188,12 +232,19 @@ func CompleteConfig(config *Config) error { config.Sources = append(config.Sources, &ast.Source{Name: filename, Input: string(schemaRaw)}) } + + config.GoInitialisms.setInitialisms() + return nil } func (c *Config) Init() error { if c.Packages == nil { - c.Packages = &code.Packages{} + c.Packages = code.NewPackages( + code.WithBuildTags(c.GoBuildTags...), + code.PackagePrefixToCache("github.com/99designs/gqlgen/graphql"), + code.WithPreloadNames(templatePackageNames...), + ) } if c.Schema == nil { @@ -207,14 +258,15 @@ func (c *Config) Init() error { return err } + // prefetch all packages in one big packages.Load call + c.Packages.LoadAll(c.packageList()...) + err = c.autobind() if err != nil { return err } c.injectBuiltins() - // prefetch all packages in one big packages.Load call - c.Packages.LoadAll(c.packageList()...) // check everything is valid on the way out err = c.check() @@ -239,21 +291,17 @@ func (c *Config) ReloadAllPackages() { c.Packages.ReloadAll(c.packageList()...) } -func (c *Config) injectTypesFromSchema() error { - c.Directives["goModel"] = DirectiveConfig{ - SkipRuntime: true, - } - - c.Directives["goField"] = DirectiveConfig{ - SkipRuntime: true, - } +func (c *Config) IsRoot(def *ast.Definition) bool { + return def == c.Schema.Query || def == c.Schema.Mutation || def == c.Schema.Subscription +} - c.Directives["goTag"] = DirectiveConfig{ - SkipRuntime: true, +func (c *Config) injectTypesFromSchema() error { + for _, d := range []string{"goModel", "goExtraField", "goField", "goTag", "goEnum"} { + c.Directives[d] = DirectiveConfig{SkipRuntime: true} } for _, schemaType := range c.Schema.Types { - if schemaType == c.Schema.Query || schemaType == c.Schema.Mutation || schemaType == c.Schema.Subscription { + if c.IsRoot(schemaType) { continue } @@ -263,46 +311,154 @@ func (c *Config) injectTypesFromSchema() error { c.Models.Add(schemaType.Name, mv.(string)) } } + if ma := bd.Arguments.ForName("models"); ma != nil { if mvs, err := ma.Value.Value(nil); err == nil { - for _, mv := range mvs.([]interface{}) { + for _, mv := range mvs.([]any) { c.Models.Add(schemaType.Name, mv.(string)) } } } + + if fg := bd.Arguments.ForName("forceGenerate"); fg != nil { + if mv, err := fg.Value.Value(nil); err == nil { + c.Models.ForceGenerate(schemaType.Name, mv.(bool)) + } + } } - if schemaType.Kind == ast.Object || schemaType.Kind == ast.InputObject { + if schemaType.Kind == ast.Object || + schemaType.Kind == ast.InputObject || + schemaType.Kind == ast.Interface { for _, field := range schemaType.Fields { if fd := field.Directives.ForName("goField"); fd != nil { - forceResolver := c.Models[schemaType.Name].Fields[field.Name].Resolver - fieldName := c.Models[schemaType.Name].Fields[field.Name].FieldName + // First, copy map entry for type and field to do modifications + typeMapEntry := c.Models[schemaType.Name] + typeMapFieldEntry := typeMapEntry.Fields[field.Name] + + if ta := fd.Arguments.ForName("type"); ta != nil { + if c.Models.UserDefined(schemaType.Name) { + return fmt.Errorf( + "argument 'type' for directive @goField (src: %s, line: %d) not applicable for user-defined models", + fd.Position.Src.Name, + fd.Position.Line, + ) + } + + if ft, err := ta.Value.Value(nil); err == nil { + typeMapFieldEntry.Type = ft.(string) + } + } if ra := fd.Arguments.ForName("forceResolver"); ra != nil { if fr, err := ra.Value.Value(nil); err == nil { - forceResolver = fr.(bool) + typeMapFieldEntry.Resolver = fr.(bool) } } if na := fd.Arguments.ForName("name"); na != nil { if fr, err := na.Value.Value(nil); err == nil { - fieldName = fr.(string) + typeMapFieldEntry.FieldName = fr.(string) + } + } + + if arg := fd.Arguments.ForName("omittable"); arg != nil { + if k, err := arg.Value.Value(nil); err == nil { + val := k.(bool) + typeMapFieldEntry.Omittable = &val } } - if c.Models[schemaType.Name].Fields == nil { - c.Models[schemaType.Name] = TypeMapEntry{ - Model: c.Models[schemaType.Name].Model, - Fields: map[string]TypeMapField{}, + // May be uninitialized, so do it now. + if typeMapEntry.Fields == nil { + typeMapEntry.Fields = make(map[string]TypeMapField) + } + + // First, copy back probably modificated field settings + typeMapEntry.Fields[field.Name] = typeMapFieldEntry + + // And final copy back probably modificated all type map + c.Models[schemaType.Name] = typeMapEntry + } + } + + if efds := schemaType.Directives.ForNames("goExtraField"); len(efds) != 0 { + for _, efd := range efds { + if t := efd.Arguments.ForName("type"); t != nil { + extraField := ModelExtraField{} + + if tv, err := t.Value.Value(nil); err == nil { + extraField.Type = tv.(string) + } + + if extraField.Type == "" { + return fmt.Errorf( + "argument 'type' for directive @goExtraField (src: %s, line: %d) cannot by empty", + efd.Position.Src.Name, + efd.Position.Line, + ) + } + + if ot := efd.Arguments.ForName("overrideTags"); ot != nil { + if otv, err := ot.Value.Value(nil); err == nil { + extraField.OverrideTags = otv.(string) + } + } + + if d := efd.Arguments.ForName("description"); d != nil { + if dv, err := d.Value.Value(nil); err == nil { + extraField.Description = dv.(string) + } + } + + extraFieldName := "" + if fn := efd.Arguments.ForName("name"); fn != nil { + if fnv, err := fn.Value.Value(nil); err == nil { + extraFieldName = fnv.(string) + } + } + + // First copy, then modify map entry. + typeMapEntry := c.Models[schemaType.Name] + + if extraFieldName == "" { + // Embeddable fields + typeMapEntry.EmbedExtraFields = append(typeMapEntry.EmbedExtraFields, extraField) + } else { + // Regular fields + if typeMapEntry.ExtraFields == nil { + typeMapEntry.ExtraFields = make(map[string]ModelExtraField) + } + typeMapEntry.ExtraFields[extraFieldName] = extraField } + + // Copy back modified map entry + c.Models[schemaType.Name] = typeMapEntry } + } + } + } + + if schemaType.Kind == ast.Enum && !strings.HasPrefix(schemaType.Name, "__") { + values := make(map[string]EnumValue) - c.Models[schemaType.Name].Fields[field.Name] = TypeMapField{ - FieldName: fieldName, - Resolver: forceResolver, + for _, value := range schemaType.EnumValues { + if directive := value.Directives.ForName("goEnum"); directive != nil { + if arg := directive.Arguments.ForName("value"); arg != nil { + if v, err := arg.Value.Value(nil); err == nil { + values[value.Name] = EnumValue{ + Value: v.(string), + } + } } } } + + if len(values) > 0 { + model := c.Models[schemaType.Name] + model.EnumValues = values + c.Models[schemaType.Name] = model + } } } @@ -310,19 +466,74 @@ func (c *Config) injectTypesFromSchema() error { } type TypeMapEntry struct { - Model StringList `yaml:"model"` - Fields map[string]TypeMapField `yaml:"fields,omitempty"` + Model StringList `yaml:"model,omitempty"` + ForceGenerate bool `yaml:"forceGenerate,omitempty"` + Fields map[string]TypeMapField `yaml:"fields,omitempty"` + EnumValues map[string]EnumValue `yaml:"enum_values,omitempty"` + + // Key is the Go name of the field. + ExtraFields map[string]ModelExtraField `yaml:"extraFields,omitempty"` + EmbedExtraFields []ModelExtraField `yaml:"embedExtraFields,omitempty"` } type TypeMapField struct { + // Type is the Go type of the field. + // + // It supports the builtin basic types (like string or int64), named types + // (qualified by the full package path), pointers to those types (prefixed + // with `*`), and slices of those types (prefixed with `[]`). + // + // For example, the following are valid types: + // string + // *github.com/author/package.Type + // []string + // []*github.com/author/package.Type + // + // Note that the type will be referenced from the generated/graphql, which + // means the package it lives in must not reference the generated/graphql + // package to avoid circular imports. + // restrictions. + Type string `yaml:"type"` + Resolver bool `yaml:"resolver"` FieldName string `yaml:"fieldName"` + Omittable *bool `yaml:"omittable"` GeneratedMethod string `yaml:"-"` } +type EnumValue struct { + Value string +} + +type ModelExtraField struct { + // Type is the Go type of the field. + // + // It supports the builtin basic types (like string or int64), named types + // (qualified by the full package path), pointers to those types (prefixed + // with `*`), and slices of those types (prefixed with `[]`). + // + // For example, the following are valid types: + // string + // *github.com/author/package.Type + // []string + // []*github.com/author/package.Type + // + // Note that the type will be referenced from the generated/graphql, which + // means the package it lives in must not reference the generated/graphql + // package to avoid circular imports. + // restrictions. + Type string `yaml:"type"` + + // OverrideTags is an optional override of the Go field tag. + OverrideTags string `yaml:"overrideTags"` + + // Description is an optional the Go field doc-comment. + Description string `yaml:"description"` +} + type StringList []string -func (a *StringList) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (a *StringList) UnmarshalYAML(unmarshal func(any) error) error { var single string err := unmarshal(&single) if err == nil { @@ -404,11 +615,11 @@ func (c *Config) check() error { Declaree: "federation", }) if c.Federation.ImportPath() != c.Exec.ImportPath() { - return fmt.Errorf("federation and exec must be in the same package") + return errors.New("federation and exec must be in the same package") } } if c.Federated { - return fmt.Errorf("federated has been removed, instead use\nfederation:\n filename: path/to/federated.go") + return errors.New("federated has been removed, instead use\nfederation:\n filename: path/to/federated.go") } for importPath, pkg := range fileList { @@ -449,6 +660,14 @@ func (tm TypeMap) Check() error { return fmt.Errorf("model %s: invalid type specifier \"%s\" - you need to specify a struct to map to", typeName, entry.Model) } } + + if len(entry.Model) == 0 { + for enum, v := range entry.EnumValues { + if v.Value != "" { + return fmt.Errorf("model is empty for: %v, but enum value is specified for %v", typeName, enum) + } + } + } } return nil } @@ -458,7 +677,10 @@ func (tm TypeMap) ReferencedPackages() []string { for _, typ := range tm { for _, model := range typ.Model { - if model == "map[string]interface{}" || model == "interface{}" { + if model == "map[string]any" || + model == "map[string]interface{}" || + model == "any" || + model == "interface{}" { continue } pkg, _ := code.PkgAndType(model) @@ -475,14 +697,30 @@ func (tm TypeMap) ReferencedPackages() []string { return pkgs } -func (tm TypeMap) Add(name string, goType string) { +func (tm TypeMap) Add(name, goType string) { modelCfg := tm[name] modelCfg.Model = append(modelCfg.Model, goType) tm[name] = modelCfg } +func (tm TypeMap) ForceGenerate(name string, forceGenerate bool) { + modelCfg := tm[name] + modelCfg.ForceGenerate = forceGenerate + tm[name] = modelCfg +} + type DirectiveConfig struct { SkipRuntime bool `yaml:"skip_runtime"` + + // If the directive implementation is statically defined, don't provide a hook for it + // in the generated server. This is useful for directives that are implemented + // by plugins or the runtime itself. + // + // The function implemmentation should be provided here as a string. + // + // The function should have the following signature: + // func(ctx context.Context, obj any, next graphql.Resolver[, directive arguments if any]) (res any, err error) + Implementation *string } func inStrSlice(haystack []string, needle string) bool { @@ -535,7 +773,7 @@ func (c *Config) autobind() error { ps := c.Packages.LoadAll(c.AutoBind...) for _, t := range c.Schema.Types { - if c.Models.UserDefined(t.Name) { + if c.Models.UserDefined(t.Name) || c.Models[t.Name].ForceGenerate { continue } @@ -543,14 +781,20 @@ func (c *Config) autobind() error { if p == nil || p.Module == nil { return fmt.Errorf("unable to load %s - make sure you're using an import path to a package that exists", c.AutoBind[i]) } - if t := p.Types.Scope().Lookup(t.Name); t != nil { - c.Models.Add(t.Name(), t.Pkg().Path()+"."+t.Name()) + + autobindType := c.lookupAutobindType(p, t) + if autobindType != nil { + c.Models.Add(t.Name, autobindType.Pkg().Path()+"."+autobindType.Name()) break } } } for i, t := range c.Models { + if t.ForceGenerate { + continue + } + for j, m := range t.Model { pkg, typename := code.PkgAndType(m) @@ -574,6 +818,17 @@ func (c *Config) autobind() error { return nil } +func (c *Config) lookupAutobindType(p *packages.Package, schemaType *ast.Definition) types.Object { + // Try binding to either the original schema type name, or the normalized go type name + for _, lookupName := range []string{schemaType.Name, templates.ToGo(schemaType.Name)} { + if t := p.Types.Scope().Lookup(lookupName); t != nil { + return t + } + } + + return nil +} + func (c *Config) injectBuiltins() { builtins := TypeMap{ "__Directive": {Model: StringList{"github.com/99designs/gqlgen/graphql/introspection.Directive"}}, @@ -587,11 +842,15 @@ func (c *Config) injectBuiltins() { "Float": {Model: StringList{"github.com/99designs/gqlgen/graphql.FloatContext"}}, "String": {Model: StringList{"github.com/99designs/gqlgen/graphql.String"}}, "Boolean": {Model: StringList{"github.com/99designs/gqlgen/graphql.Boolean"}}, - "Int": {Model: StringList{ - "github.com/99designs/gqlgen/graphql.Int", - "github.com/99designs/gqlgen/graphql.Int32", - "github.com/99designs/gqlgen/graphql.Int64", - }}, + "Int": { + // FIXME: using int / int64 for Int is not spec compliant and introduces + // security risks. We should default to int32. + Model: StringList{ + "github.com/99designs/gqlgen/graphql.Int", + "github.com/99designs/gqlgen/graphql.Int32", + "github.com/99designs/gqlgen/graphql.Int64", + }, + }, "ID": { Model: StringList{ "github.com/99designs/gqlgen/graphql.ID", @@ -608,6 +867,12 @@ func (c *Config) injectBuiltins() { // These are additional types that are injected if defined in the schema as scalars. extraBuiltins := TypeMap{ + "Int64": { + Model: StringList{ + "github.com/99designs/gqlgen/graphql.Int", + "github.com/99designs/gqlgen/graphql.Int64", + }, + }, "Time": {Model: StringList{"github.com/99designs/gqlgen/graphql.Time"}}, "Map": {Model: StringList{"github.com/99designs/gqlgen/graphql.Map"}}, "Upload": {Model: StringList{"github.com/99designs/gqlgen/graphql.Upload"}}, @@ -623,7 +888,11 @@ func (c *Config) injectBuiltins() { func (c *Config) LoadSchema() error { if c.Packages != nil { - c.Packages = &code.Packages{} + c.Packages = code.NewPackages( + code.WithBuildTags(c.GoBuildTags...), + code.PackagePrefixToCache("github.com/99designs/gqlgen/graphql"), + code.WithPreloadNames(templatePackageNames...), + ) } if err := c.check(); err != nil { diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/exec.go b/vendor/github.com/99designs/gqlgen/codegen/config/exec.go index fe1dccd21..37ec2c30b 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/config/exec.go +++ b/vendor/github.com/99designs/gqlgen/codegen/config/exec.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "go/types" "path/filepath" @@ -19,6 +20,12 @@ type ExecConfig struct { // Only for follow-schema layout: FilenameTemplate string `yaml:"filename_template,omitempty"` // String template with {name} as placeholder for base name. DirName string `yaml:"dir"` + + // Maximum number of goroutines in concurrency to use when running multiple child resolvers + // Suppressing the number of goroutines generated can reduce memory consumption per request, + // but processing time may increase due to the reduced number of concurrences + // Default: 0 (unlimited) + WorkerLimit uint `yaml:"worker_limit"` } type ExecLayout string @@ -38,15 +45,15 @@ func (r *ExecConfig) Check() error { switch r.Layout { case ExecLayoutSingleFile: if r.Filename == "" { - return fmt.Errorf("filename must be specified when using single-file layout") + return errors.New("filename must be specified when using single-file layout") } if !strings.HasSuffix(r.Filename, ".go") { - return fmt.Errorf("filename should be path to a go source file when using single-file layout") + return errors.New("filename should be path to a go source file when using single-file layout") } r.Filename = abs(r.Filename) case ExecLayoutFollowSchema: if r.DirName == "" { - return fmt.Errorf("dir must be specified when using follow-schema layout") + return errors.New("dir must be specified when using follow-schema layout") } r.DirName = abs(r.DirName) default: @@ -54,7 +61,7 @@ func (r *ExecConfig) Check() error { } if strings.ContainsAny(r.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") + return errors.New("package should be the output package name only, do not include the output filename") } if r.Package == "" && r.Dir() != "" { diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/initialisms.go b/vendor/github.com/99designs/gqlgen/codegen/config/initialisms.go new file mode 100644 index 000000000..432c56e06 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/codegen/config/initialisms.go @@ -0,0 +1,42 @@ +package config + +import ( + "strings" + + "github.com/99designs/gqlgen/codegen/templates" +) + +// GoInitialismsConfig allows to modify the default behavior of naming Go methods, types and properties +type GoInitialismsConfig struct { + // If true, the Initialisms won't get appended to the default ones but replace them + ReplaceDefaults bool `yaml:"replace_defaults"` + // Custom initialisms to be added or to replace the default ones + Initialisms []string `yaml:"initialisms"` +} + +// setInitialisms adjusts GetInitialisms based on its settings. +func (i GoInitialismsConfig) setInitialisms() { + toUse := i.determineGoInitialisms() + templates.GetInitialisms = func() map[string]bool { + return toUse + } +} + +// determineGoInitialisms returns the Go initialisms to be used, based on its settings. +func (i GoInitialismsConfig) determineGoInitialisms() (initialismsToUse map[string]bool) { + if i.ReplaceDefaults { + initialismsToUse = make(map[string]bool, len(i.Initialisms)) + for _, initialism := range i.Initialisms { + initialismsToUse[strings.ToUpper(initialism)] = true + } + } else { + initialismsToUse = make(map[string]bool, len(templates.CommonInitialisms)+len(i.Initialisms)) + for initialism, value := range templates.CommonInitialisms { + initialismsToUse[strings.ToUpper(initialism)] = value + } + for _, initialism := range i.Initialisms { + initialismsToUse[strings.ToUpper(initialism)] = true + } + } + return initialismsToUse +} diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/package.go b/vendor/github.com/99designs/gqlgen/codegen/config/package.go index faacd1496..a399b2cc0 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/config/package.go +++ b/vendor/github.com/99designs/gqlgen/codegen/config/package.go @@ -1,7 +1,7 @@ package config import ( - "fmt" + "errors" "go/types" "path/filepath" "strings" @@ -10,9 +10,11 @@ import ( ) type PackageConfig struct { - Filename string `yaml:"filename,omitempty"` - Package string `yaml:"package,omitempty"` - Version int `yaml:"version,omitempty"` + Filename string `yaml:"filename,omitempty"` + Package string `yaml:"package,omitempty"` + Version int `yaml:"version,omitempty"` + ModelTemplate string `yaml:"model_template,omitempty"` + Options map[string]bool `yaml:"options,omitempty"` } func (c *PackageConfig) ImportPath() string { @@ -42,13 +44,13 @@ func (c *PackageConfig) IsDefined() bool { func (c *PackageConfig) Check() error { if strings.ContainsAny(c.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") + return errors.New("package should be the output package name only, do not include the output filename") } if c.Filename == "" { - return fmt.Errorf("filename must be specified") + return errors.New("filename must be specified") } if !strings.HasSuffix(c.Filename, ".go") { - return fmt.Errorf("filename should be path to a go source file") + return errors.New("filename should be path to a go source file") } c.Filename = abs(c.Filename) diff --git a/vendor/github.com/99designs/gqlgen/codegen/config/resolver.go b/vendor/github.com/99designs/gqlgen/codegen/config/resolver.go index cd03f1887..fa0744e10 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/config/resolver.go +++ b/vendor/github.com/99designs/gqlgen/codegen/config/resolver.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "go/types" "path/filepath" @@ -10,12 +11,15 @@ import ( ) type ResolverConfig struct { - Filename string `yaml:"filename,omitempty"` - FilenameTemplate string `yaml:"filename_template,omitempty"` - Package string `yaml:"package,omitempty"` - Type string `yaml:"type,omitempty"` - Layout ResolverLayout `yaml:"layout,omitempty"` - DirName string `yaml:"dir"` + Filename string `yaml:"filename,omitempty"` + FilenameTemplate string `yaml:"filename_template,omitempty"` + Package string `yaml:"package,omitempty"` + Type string `yaml:"type,omitempty"` + Layout ResolverLayout `yaml:"layout,omitempty"` + DirName string `yaml:"dir"` + OmitTemplateComment bool `yaml:"omit_template_comment,omitempty"` + ResolverTemplate string `yaml:"resolver_template,omitempty"` + PreserveResolver bool `yaml:"preserve_resolver,omitempty"` } type ResolverLayout string @@ -57,7 +61,7 @@ func (r *ResolverConfig) Check() error { } if strings.ContainsAny(r.Package, "./\\") { - return fmt.Errorf("package should be the output package name only, do not include the output filename") + return errors.New("package should be the output package name only, do not include the output filename") } if r.Package == "" && r.Dir() != "" { diff --git a/vendor/github.com/99designs/gqlgen/codegen/data.go b/vendor/github.com/99designs/gqlgen/codegen/data.go index 592140ae6..d3d8cd89a 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/data.go +++ b/vendor/github.com/99designs/gqlgen/codegen/data.go @@ -1,6 +1,7 @@ package codegen import ( + "errors" "fmt" "os" "path/filepath" @@ -34,6 +35,7 @@ type Data struct { MutationRoot *Object SubscriptionRoot *Object AugmentedSources []AugmentedSource + Plugins []any } func (d *Data) HasEmbeddableSources() bool { @@ -62,6 +64,30 @@ type builder struct { Directives map[string]*Directive } +// Get only the directives which should have a user provided definition on server instantiation +func (d *Data) UserDirectives() DirectiveList { + res := DirectiveList{} + directives := d.Directives() + for k, directive := range directives { + if directive.Implementation == nil { + res[k] = directive + } + } + return res +} + +// Get only the directives which should have a statically provided definition +func (d *Data) BuiltInDirectives() DirectiveList { + res := DirectiveList{} + directives := d.Directives() + for k, directive := range directives { + if directive.Implementation != nil { + res[k] = directive + } + } + return res +} + // Get only the directives which are defined in the config's sources. func (d *Data) Directives() DirectiveList { res := DirectiveList{} @@ -76,7 +102,7 @@ func (d *Data) Directives() DirectiveList { return res } -func BuildData(cfg *config.Config) (*Data, error) { +func BuildData(cfg *config.Config, plugins ...any) (*Data, error) { // We reload all packages to allow packages to be compared correctly. cfg.ReloadAllPackages() @@ -95,7 +121,7 @@ func BuildData(cfg *config.Config) (*Data, error) { dataDirectives := make(map[string]*Directive) for name, d := range b.Directives { - if !d.Builtin { + if !d.SkipRuntime { dataDirectives[name] = d } } @@ -105,6 +131,7 @@ func BuildData(cfg *config.Config) (*Data, error) { AllDirectives: dataDirectives, Schema: b.Schema, Interfaces: map[string]*Interface{}, + Plugins: plugins, } for _, schemaType := range b.Schema.Types { @@ -135,7 +162,7 @@ func BuildData(cfg *config.Config) (*Data, error) { if s.Schema.Query != nil { s.QueryRoot = s.Objects.ByName(s.Schema.Query.Name) } else { - return nil, fmt.Errorf("query entry point missing") + return nil, errors.New("query entry point missing") } if s.Schema.Mutation != nil { @@ -153,11 +180,11 @@ func BuildData(cfg *config.Config) (*Data, error) { s.ReferencedTypes = b.buildTypes() sort.Slice(s.Objects, func(i, j int) bool { - return s.Objects[i].Definition.Name < s.Objects[j].Definition.Name + return s.Objects[i].Name < s.Objects[j].Name }) sort.Slice(s.Inputs, func(i, j int) bool { - return s.Inputs[i].Definition.Name < s.Inputs[j].Definition.Name + return s.Inputs[i].Name < s.Inputs[j].Name }) if b.Binder.SawInvalid { @@ -168,7 +195,7 @@ func BuildData(cfg *config.Config) (*Data, error) { } // otherwise show a generic error message - return nil, fmt.Errorf("invalid types were encountered while traversing the go source code, this probably means the invalid code generated isnt correct. add try adding -v to debug") + return nil, errors.New("invalid types were encountered while traversing the go source code, this probably means the invalid code generated isnt correct. add try adding -v to debug") } aSources := []AugmentedSource{} for _, s := range cfg.Sources { @@ -202,7 +229,7 @@ func BuildData(cfg *config.Config) (*Data, error) { func (b *builder) injectIntrospectionRoots(s *Data) error { obj := s.Objects.ByName(b.Schema.Query.Name) if obj == nil { - return fmt.Errorf("root query type must be defined") + return errors.New("root query type must be defined") } __type, err := b.buildField(obj, &ast.FieldDefinition{ diff --git a/vendor/github.com/99designs/gqlgen/codegen/directive.go b/vendor/github.com/99designs/gqlgen/codegen/directive.go index 973061129..f7a7c1c8a 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/directive.go +++ b/vendor/github.com/99designs/gqlgen/codegen/directive.go @@ -2,11 +2,12 @@ package codegen import ( "fmt" - "strconv" "strings" - "github.com/99designs/gqlgen/codegen/templates" "github.com/vektah/gqlparser/v2/ast" + + "github.com/99designs/gqlgen/codegen/config" + "github.com/99designs/gqlgen/codegen/templates" ) type DirectiveList map[string]*Directive @@ -18,9 +19,10 @@ func (dl DirectiveList) LocationDirectives(location string) DirectiveList { type Directive struct { *ast.DirectiveDefinition - Name string - Args []*FieldArgument - Builtin bool + Name string + Args []*FieldArgument + + config.DirectiveConfig } // IsLocation check location directive @@ -81,7 +83,7 @@ func (b *builder) buildDirectives() (map[string]*Directive, error) { DirectiveDefinition: dir, Name: name, Args: args, - Builtin: b.Config.Directives[name].SkipRuntime, + DirectiveConfig: b.Config.Directives[name], } } @@ -91,7 +93,7 @@ func (b *builder) buildDirectives() (map[string]*Directive, error) { func (b *builder) getDirectives(list ast.DirectiveList) ([]*Directive, error) { dirs := make([]*Directive, len(list)) for i, d := range list { - argValues := make(map[string]interface{}, len(d.Arguments)) + argValues := make(map[string]any, len(d.Arguments)) for _, da := range d.Arguments { val, err := da.Value.Value(nil) if err != nil { @@ -121,9 +123,8 @@ func (b *builder) getDirectives(list ast.DirectiveList) ([]*Directive, error) { Name: d.Name, Args: args, DirectiveDefinition: list[i].Definition, - Builtin: b.Config.Directives[d.Name].SkipRuntime, + DirectiveConfig: b.Config.Directives[d.Name], } - } return dirs, nil @@ -141,7 +142,7 @@ func (d *Directive) CallArgs() string { args := []string{"ctx", "obj", "n"} for _, arg := range d.Args { - args = append(args, "args["+strconv.Quote(arg.Name)+"].("+templates.CurrentImports.LookupType(arg.TypeReference.GO)+")") + args = append(args, fmt.Sprintf("args[%q].(%s)", arg.Name, templates.CurrentImports.LookupType(arg.TypeReference.GO))) } return strings.Join(args, ", ") @@ -162,13 +163,37 @@ func (d *Directive) ResolveArgs(obj string, next int) string { return strings.Join(args, ", ") } +func (d *Directive) CallName() string { + return ucFirst(d.Name) +} + func (d *Directive) Declaration() string { - res := ucFirst(d.Name) + " func(ctx context.Context, obj interface{}, next graphql.Resolver" + res := d.CallName() + " func(ctx context.Context, obj any, next graphql.Resolver" for _, arg := range d.Args { res += fmt.Sprintf(", %s %s", templates.ToGoPrivate(arg.Name), templates.CurrentImports.LookupType(arg.TypeReference.GO)) } - res += ") (res interface{}, err error)" + res += ") (res any, err error)" return res } + +func (d *Directive) IsBuiltIn() bool { + return d.Implementation != nil +} + +func (d *Directive) CallPath() string { + if d.IsBuiltIn() { + return "builtInDirective" + d.CallName() + } + + return "ec.directives." + d.CallName() +} + +func (d *Directive) FunctionImpl() string { + if d.Implementation == nil { + return "" + } + + return d.CallPath() + " = " + *d.Implementation +} diff --git a/vendor/github.com/99designs/gqlgen/codegen/directives.gotpl b/vendor/github.com/99designs/gqlgen/codegen/directives.gotpl index 23bcf0f87..54544bd6c 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/directives.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/directives.gotpl @@ -1,46 +1,66 @@ -{{ define "implDirectives" }}{{ $in := .DirectiveObjName }} - {{- range $i, $directive := .ImplDirectives -}} - directive{{add $i 1}} := func(ctx context.Context) (interface{}, error) { +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} + +{{ define "implDirectives" }} + {{ $in := .Field.DirectiveObjName }} + {{ $useFunctionSyntaxForExecutionContext := .UseFunctionSyntaxForExecutionContext }} + {{ $zeroVal := .Field.TypeReference.GO | ref}} + {{- range $i, $directive := .Field.ImplDirectives -}} + directive{{add $i 1}} := func(ctx context.Context) (any, error) { {{- range $arg := $directive.Args }} {{- if notNil "Value" $arg }} + {{ if $useFunctionSyntaxForExecutionContext -}} + {{ $arg.VarName }}, err := {{ $arg.TypeReference.UnmarshalFunc }}(ctx, ec, {{ $arg.Value | dump }}) + {{- else -}} {{ $arg.VarName }}, err := ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, {{ $arg.Value | dump }}) + {{- end }} if err != nil{ - return nil, err + var zeroVal {{$zeroVal}} + return zeroVal, err } {{- else if notNil "Default" $arg }} + {{ if $useFunctionSyntaxForExecutionContext -}} + {{ $arg.VarName }}, err := {{ $arg.TypeReference.UnmarshalFunc }}(ctx, ec, {{ $arg.Default | dump }}) + {{- else -}} {{ $arg.VarName }}, err := ec.{{ $arg.TypeReference.UnmarshalFunc }}(ctx, {{ $arg.Default | dump }}) + {{- end }} if err != nil{ - return nil, err + var zeroVal {{$zeroVal}} + return zeroVal, err } {{- end }} {{- end }} - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.ResolveArgs $in $i }}) + {{- if not $directive.IsBuiltIn}} + if {{$directive.CallPath}} == nil { + var zeroVal {{$zeroVal}} + return zeroVal, errors.New("directive {{$directive.Name}} is not implemented") + } + {{- end}} + return {{$directive.CallPath}}({{$directive.ResolveArgs $in $i }}) } {{ end -}} {{ end }} {{define "queryDirectives"}} + {{ $useFunctionSyntaxForExecutionContext := .UseFunctionSyntaxForExecutionContext }} for _, d := range obj.Directives { switch d.Name { - {{- range $directive := . }} + {{- range $directive := .DirectiveList }} case "{{$directive.Name}}": {{- if $directive.Args }} rawArgs := d.ArgumentMap(ec.Variables) + {{ if $useFunctionSyntaxForExecutionContext -}} + args, err := {{ $directive.ArgsFunc }}(ctx,ec,rawArgs) + {{- else -}} args, err := ec.{{ $directive.ArgsFunc }}(ctx,rawArgs) + {{- end }} if err != nil { ec.Error(ctx, err) return graphql.Null } {{- end }} n := next - next = func(ctx context.Context) (interface{}, error) { - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}}) + next = func(ctx context.Context) (any, error) { + {{- template "callDirective" $directive -}} } {{- end }} } @@ -57,27 +77,52 @@ return graphql.Null {{end}} +{{define "callDirective"}} + {{- if not .IsBuiltIn}} + if {{.CallPath}} == nil { + return nil, errors.New("directive {{.Name}} is not implemented") + } + {{- end}} + return {{.CallPath}}({{.CallArgs}}) +{{end}} + {{ if .Directives.LocationDirectives "QUERY" }} -func (ec *executionContext) _queryMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (interface{}, error)) graphql.Marshaler { - {{ template "queryDirectives" .Directives.LocationDirectives "QUERY" }} +{{ if $useFunctionSyntaxForExecutionContext -}} +func _queryMiddleware(ctx context.Context, ec *executionContext, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) graphql.Marshaler { +{{- else -}} +func (ec *executionContext) _queryMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) graphql.Marshaler { +{{- end }} + {{ template "queryDirectives" (dict "DirectiveList" (.Directives.LocationDirectives "QUERY") "UseFunctionSyntaxForExecutionContext" $useFunctionSyntaxForExecutionContext) }} } {{ end }} {{ if .Directives.LocationDirectives "MUTATION" }} -func (ec *executionContext) _mutationMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (interface{}, error)) graphql.Marshaler { - {{ template "queryDirectives" .Directives.LocationDirectives "MUTATION" }} +{{ if $useFunctionSyntaxForExecutionContext -}} +func _mutationMiddleware(ctx context.Context, ec *executionContext, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) graphql.Marshaler { +{{- else -}} +func (ec *executionContext) _mutationMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) graphql.Marshaler { +{{- end }} + {{ template "queryDirectives" (dict "DirectiveList" (.Directives.LocationDirectives "MUTATION") "UseFunctionSyntaxForExecutionContext" $useFunctionSyntaxForExecutionContext) }} } {{ end }} {{ if .Directives.LocationDirectives "SUBSCRIPTION" }} -func (ec *executionContext) _subscriptionMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (interface{}, error)) func(ctx context.Context) graphql.Marshaler { +{{ if $useFunctionSyntaxForExecutionContext -}} +func _subscriptionMiddleware(ctx context.Context, ec *executionContext, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) func(ctx context.Context) graphql.Marshaler { +{{- else -}} +func (ec *executionContext) _subscriptionMiddleware(ctx context.Context, obj *ast.OperationDefinition, next func(ctx context.Context) (any, error)) func(ctx context.Context) graphql.Marshaler { +{{- end }} for _, d := range obj.Directives { switch d.Name { {{- range $directive := .Directives.LocationDirectives "SUBSCRIPTION" }} case "{{$directive.Name}}": {{- if $directive.Args }} rawArgs := d.ArgumentMap(ec.Variables) + {{ if $useFunctionSyntaxForExecutionContext -}} + args, err := {{ $directive.ArgsFunc }}(ctx,ec,rawArgs) + {{- else -}} args, err := ec.{{ $directive.ArgsFunc }}(ctx,rawArgs) + {{- end }} if err != nil { ec.Error(ctx, err) return func(ctx context.Context) graphql.Marshaler { @@ -86,11 +131,8 @@ func (ec *executionContext) _subscriptionMiddleware(ctx context.Context, obj *as } {{- end }} n := next - next = func(ctx context.Context) (interface{}, error) { - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}}) + next = func(ctx context.Context) (any, error) { + {{- template "callDirective" $directive -}} } {{- end }} } @@ -113,7 +155,11 @@ func (ec *executionContext) _subscriptionMiddleware(ctx context.Context, obj *as {{ end }} {{ if .Directives.LocationDirectives "FIELD" }} - func (ec *executionContext) _fieldMiddleware(ctx context.Context, obj interface{}, next graphql.Resolver) interface{} { + {{ if $useFunctionSyntaxForExecutionContext -}} + func _fieldMiddleware(ctx context.Context, ec *executionContext, obj any, next graphql.Resolver) graphql.Resolver { + {{- else -}} + func (ec *executionContext) _fieldMiddleware(ctx context.Context, obj any, next graphql.Resolver) graphql.Resolver { + {{- end }} {{- if .Directives.LocationDirectives "FIELD" }} fc := graphql.GetFieldContext(ctx) for _, d := range fc.Field.Directives { @@ -122,28 +168,24 @@ func (ec *executionContext) _subscriptionMiddleware(ctx context.Context, obj *as case "{{$directive.Name}}": {{- if $directive.Args }} rawArgs := d.ArgumentMap(ec.Variables) + {{ if $useFunctionSyntaxForExecutionContext -}} + args, err := {{ $directive.ArgsFunc }}(ctx,ec,rawArgs) + {{- else -}} args, err := ec.{{ $directive.ArgsFunc }}(ctx,rawArgs) + {{- end }} if err != nil { ec.Error(ctx, err) return nil } {{- end }} n := next - next = func(ctx context.Context) (interface{}, error) { - if ec.directives.{{$directive.Name|ucFirst}} == nil { - return nil, errors.New("directive {{$directive.Name}} is not implemented") - } - return ec.directives.{{$directive.Name|ucFirst}}({{$directive.CallArgs}}) + next = func(ctx context.Context) (any, error) { + {{- template "callDirective" $directive -}} } {{- end }} } } {{- end }} - res, err := ec.ResolverMiddleware(ctx, next) - if err != nil { - ec.Error(ctx, err) - return nil - } - return res + return next } {{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/field.go b/vendor/github.com/99designs/gqlgen/codegen/field.go index a33cc18e5..460fa6990 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/field.go +++ b/vendor/github.com/99designs/gqlgen/codegen/field.go @@ -3,17 +3,20 @@ package codegen import ( "errors" "fmt" + goast "go/ast" "go/types" "log" "reflect" "strconv" "strings" - "github.com/99designs/gqlgen/codegen/config" - "github.com/99designs/gqlgen/codegen/templates" "github.com/vektah/gqlparser/v2/ast" "golang.org/x/text/cases" "golang.org/x/text/language" + + "github.com/99designs/gqlgen/codegen/config" + "github.com/99designs/gqlgen/codegen/templates" + "github.com/99designs/gqlgen/internal/code" ) type Field struct { @@ -27,9 +30,9 @@ type Field struct { Args []*FieldArgument // A list of arguments to be passed to this field MethodHasContext bool // If this is bound to a go method, does the method also take a context NoErr bool // If this is bound to a go method, does that method have an error as the second argument - VOkFunc bool // If this is bound to a go method, is it of shape (interface{}, bool) + VOkFunc bool // If this is bound to a go method, is it of shape (any, bool) Object *Object // A link back to the parent object - Default interface{} // The default value + Default any // The default value Stream bool // does this field return a channel? Directives []*Directive } @@ -142,7 +145,7 @@ func (b *builder) bindField(obj *Object, f *Field) (errret error) { f.GoFieldName = b.Config.Models[obj.Name].Fields[f.Name].FieldName } - target, err := b.findBindTarget(obj.Type.(*types.Named), f.GoFieldName) + target, err := b.findBindTarget(obj.Type, f.GoFieldName) if err != nil { return err } @@ -151,6 +154,11 @@ func (b *builder) bindField(obj *Object, f *Field) (errret error) { switch target := target.(type) { case nil: + // Skips creating a resolver for any root types + if b.Config.IsRoot(b.Schema.Types[f.Type.Name()]) { + return nil + } + objPos := b.Binder.TypePosition(obj.Type) return fmt.Errorf( "%s:%d adding resolver method for %s.%s, nothing matched", @@ -167,7 +175,7 @@ func (b *builder) bindField(obj *Object, f *Field) (errret error) { } else if s := sig.Results(); s.Len() == 2 && s.At(1).Type().String() == "bool" { f.VOkFunc = true } else if sig.Results().Len() != 2 { - return fmt.Errorf("method has wrong number of args") + return errors.New("method has wrong number of args") } params := sig.Params() // If the first argument is the context, remove it from the comparison and set @@ -222,7 +230,7 @@ func (b *builder) bindField(obj *Object, f *Field) (errret error) { } // findBindTarget attempts to match the name to a field or method on a Type -// with the following priorites: +// with the following priorities: // 1. Any Fields with a struct tag (see config.StructTag). Errors if more than one match is found // 2. Any method or field with a matching name. Errors if more than one match is found // 3. Same logic again for embedded fields @@ -280,7 +288,7 @@ func (b *builder) findBindStructTagTarget(in types.Type, name string) (types.Obj tags := reflect.StructTag(t.Tag(i)) if val, ok := tags.Lookup(b.Config.StructTag); ok && equalFieldName(val, name) { if found != nil { - return nil, fmt.Errorf("tag %s is ambigious; multiple fields have the same tag value of %s", b.Config.StructTag, val) + return nil, fmt.Errorf("tag %s is ambiguous; multiple fields have the same tag value of %s", b.Config.StructTag, val) } found = field @@ -311,7 +319,7 @@ func (b *builder) findBindMethodTarget(in types.Type, name string) (types.Object func (b *builder) findBindMethoderTarget(methodFunc func(i int) *types.Func, methodCount int, name string) (types.Object, error) { var found types.Object - for i := 0; i < methodCount; i++ { + for i := range methodCount { method := methodFunc(i) if !method.Exported() || !strings.EqualFold(method.Name(), name) { continue @@ -373,7 +381,7 @@ func (b *builder) findBindStructEmbedsTarget(strukt *types.Struct, name string) continue } - fieldType := field.Type() + fieldType := code.Unalias(field.Type()) if ptr, ok := fieldType.(*types.Pointer); ok { fieldType = ptr.Elem() } @@ -435,7 +443,7 @@ func (f *Field) ImplDirectives() []*Directive { loc = ast.LocationInputFieldDefinition } for i := range f.Directives { - if !f.Directives[i].Builtin && + if !f.Directives[i].SkipRuntime && (f.Directives[i].IsLocation(loc, ast.LocationObject) || f.Directives[i].IsLocation(loc, ast.LocationInputObject)) { d = append(d, f.Directives[i]) } @@ -473,9 +481,9 @@ func (f *Field) GoNameUnexported() string { func (f *Field) ShortInvocation() string { caser := cases.Title(language.English, cases.NoLower) if f.Object.Kind == ast.InputObject { - return fmt.Sprintf("%s().%s(ctx, &it, data)", caser.String(f.Object.Definition.Name), f.GoFieldName) + return fmt.Sprintf("%s().%s(ctx, &it, data)", caser.String(f.Object.Name), f.GoFieldName) } - return fmt.Sprintf("%s().%s(%s)", caser.String(f.Object.Definition.Name), f.GoFieldName, f.CallArgs()) + return fmt.Sprintf("%s().%s(%s)", caser.String(f.Object.Name), f.GoFieldName, f.CallArgs()) } func (f *Field) ArgsFunc() string { @@ -483,11 +491,11 @@ func (f *Field) ArgsFunc() string { return "" } - return "field_" + f.Object.Definition.Name + "_" + f.Name + "_args" + return "field_" + f.Object.Name + "_" + f.Name + "_args" } func (f *Field) FieldContextFunc() string { - return "fieldContext_" + f.Object.Definition.Name + "_" + f.Name + return "fieldContext_" + f.Object.Name + "_" + f.Name } func (f *Field) ChildFieldContextFunc(name string) string { @@ -499,10 +507,24 @@ func (f *Field) ResolverType() string { return "" } - return fmt.Sprintf("%s().%s(%s)", f.Object.Definition.Name, f.GoFieldName, f.CallArgs()) + return fmt.Sprintf("%s().%s(%s)", f.Object.Name, f.GoFieldName, f.CallArgs()) +} + +func (f *Field) IsInputObject() bool { + return f.Object.Kind == ast.InputObject +} + +func (f *Field) IsRoot() bool { + return f.Object.Root } func (f *Field) ShortResolverDeclaration() string { + return f.ShortResolverSignature(nil) +} + +// ShortResolverSignature is identical to ShortResolverDeclaration, +// but respects previous naming (return) conventions, if any. +func (f *Field) ShortResolverSignature(ft *goast.FuncType) string { if f.Object.Kind == ast.InputObject { return fmt.Sprintf("(ctx context.Context, obj %s, data %s) error", templates.CurrentImports.LookupType(f.Object.Reference()), @@ -523,11 +545,27 @@ func (f *Field) ShortResolverDeclaration() string { if f.Object.Stream { result = "<-chan " + result } - - res += fmt.Sprintf(") (%s, error)", result) + // Named return. + var namedV, namedE string + if ft != nil { + if ft.Results != nil && len(ft.Results.List) > 0 && len(ft.Results.List[0].Names) > 0 { + namedV = ft.Results.List[0].Names[0].Name + } + if ft.Results != nil && len(ft.Results.List) > 1 && len(ft.Results.List[1].Names) > 0 { + namedE = ft.Results.List[1].Names[0].Name + } + } + res += fmt.Sprintf(") (%s %s, %s error)", namedV, result, namedE) return res } +func (f *Field) GoResultName() (string, bool) { + name := fmt.Sprintf("%v", f.TypeReference.GO) + splits := strings.Split(name, "/") + + return splits[len(splits)-1], strings.HasPrefix(name, "[]") +} + func (f *Field) ComplexitySignature() string { res := "func(childComplexity int" for _, arg := range f.Args { @@ -550,7 +588,7 @@ func (f *Field) CallArgs() string { args := make([]string, 0, len(f.Args)+2) if f.IsResolver { - args = append(args, "rctx") + args = append(args, "ctx") if !f.Object.Root { args = append(args, "obj") @@ -564,11 +602,11 @@ func (f *Field) CallArgs() string { if iface, ok := arg.TypeReference.GO.(*types.Interface); ok && iface.Empty() { tmp = fmt.Sprintf(` - func () interface{} { + func () any { if fc.Args["%s"] == nil { return nil } - return fc.Args["%s"].(interface{}) + return fc.Args["%s"].(any) }()`, arg.Name, arg.Name, ) } diff --git a/vendor/github.com/99designs/gqlgen/codegen/field.gotpl b/vendor/github.com/99designs/gqlgen/codegen/field.gotpl index e47b958dd..09f3c32c9 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/field.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/field.gotpl @@ -1,68 +1,96 @@ +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} + {{- range $object := .Objects }}{{- range $field := $object.Fields }} +{{ if $useFunctionSyntaxForExecutionContext -}} +func _{{$object.Name}}_{{$field.Name}}(ctx context.Context, ec *executionContext, field graphql.CollectedField{{ if not $object.Root }}, obj {{$object.Reference | ref}}{{end}}) (ret {{ if $object.Stream }}func(ctx context.Context){{ end }}graphql.Marshaler) { +{{- else -}} func (ec *executionContext) _{{$object.Name}}_{{$field.Name}}(ctx context.Context, field graphql.CollectedField{{ if not $object.Root }}, obj {{$object.Reference | ref}}{{end}}) (ret {{ if $object.Stream }}func(ctx context.Context){{ end }}graphql.Marshaler) { +{{- end }} {{- $null := "graphql.Null" }} {{- if $object.Stream }} {{- $null = "nil" }} {{- end }} - fc, err := ec.{{ $field.FieldContextFunc }}(ctx, field) - if err != nil { - return {{ $null }} - } - ctx = graphql.WithFieldContext(ctx, fc) - defer func () { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - ret = {{ $null }} - } - }() - {{- if $.AllDirectives.LocationDirectives "FIELD" }} - resTmp := ec._fieldMiddleware(ctx, {{if $object.Root}}nil{{else}}obj{{end}}, func(rctx context.Context) (interface{}, error) { - {{ template "field" $field }} - }) - {{ else }} - resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { - {{ template "field" $field }} - }) + + {{- if $field.TypeReference.IsRoot }} + {{ if $useFunctionSyntaxForExecutionContext -}} + fc, err := {{ $field.FieldContextFunc }}(ctx, ec, field) + {{- else -}} + fc, err := ec.{{ $field.FieldContextFunc }}(ctx, field) + {{- end }} if err != nil { - ec.Error(ctx, err) return {{ $null }} } - {{- end }} - if resTmp == nil { - {{- if $field.TypeReference.GQL.NonNull }} - if !graphql.HasFieldError(ctx, fc) { - ec.Errorf(ctx, "must not be null") + ctx = graphql.WithFieldContext(ctx, fc) + {{- if not $.Config.OmitPanicHandler }} + defer func () { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = {{ $null }} } + }() + {{- end }} + + {{- if $field.TypeReference.IsPtr }} + res := &{{ $field.TypeReference.Elem.GO | ref }}{} + {{- else }} + res := {{ $field.TypeReference.GO | ref }}{} {{- end }} - return {{ $null }} - } - {{- if $object.Stream }} - return func(ctx context.Context) graphql.Marshaler { - select { - case res, ok := <-resTmp.(<-chan {{$field.TypeReference.GO | ref}}): - if !ok { - return nil - } - return graphql.WriterFunc(func(w io.Writer) { - w.Write([]byte{'{'}) - graphql.MarshalString(field.Alias).MarshalGQL(w) - w.Write([]byte{':'}) - ec.{{ $field.TypeReference.MarshalFunc }}(ctx, field.Selections, res).MarshalGQL(w) - w.Write([]byte{'}'}) - }) - case <-ctx.Done(): - return nil - } - } - {{- else }} - res := resTmp.({{$field.TypeReference.GO | ref}}) fc.Result = res + {{ if $useFunctionSyntaxForExecutionContext -}} + return {{ $field.TypeReference.MarshalFunc }}(ctx, ec, field.Selections, res) + {{- else -}} return ec.{{ $field.TypeReference.MarshalFunc }}(ctx, field.Selections, res) + {{- end }} + {{- else}} + return graphql.ResolveField{{- if $object.Stream }}Stream{{- end }}( + ctx, + ec.OperationContext, + field, + {{ if $useFunctionSyntaxForExecutionContext -}} + func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { return {{ $field.FieldContextFunc }}(ctx, ec, field) }, + {{- else -}} + ec.{{ $field.FieldContextFunc }}, + {{- end }} + func(ctx context.Context) (any, error) { + {{- template "fieldDefinition" $field }} + }, + {{if or ($.AllDirectives.LocationDirectives "FIELD") $field.HasDirectives -}} + func(ctx context.Context, next graphql.Resolver) graphql.Resolver { + {{- if $field.HasDirectives -}} + directive0 := next + {{ template "implDirectives" (dict "Field" $field "UseFunctionSyntaxForExecutionContext" $useFunctionSyntaxForExecutionContext) }} + next = directive{{$field.ImplDirectives|len}} + {{end}} + {{- if $.AllDirectives.LocationDirectives "FIELD" -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + return _fieldMiddleware(ctx, ec, {{if $object.Root}}nil{{else}}obj{{end}}, next) + {{- else -}} + return ec._fieldMiddleware(ctx, {{if $object.Root}}nil{{else}}obj{{end}}, next) + {{- end }} + {{- else -}} + return next + {{end -}} + }, + {{else -}} + nil, + {{end -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + func(ctx context.Context, selections ast.SelectionSet, v {{ $field.TypeReference.GO | ref }}) graphql.Marshaler { return {{ $field.TypeReference.MarshalFunc }}(ctx, ec, selections, v) }, + {{- else -}} + ec.{{ $field.TypeReference.MarshalFunc }}, + {{- end }} + {{ not $.Config.OmitPanicHandler }}, + {{ $field.TypeReference.GQL.NonNull }}, + ) {{- end }} } -func (ec *executionContext) {{ $field.FieldContextFunc }}(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +{{ if $useFunctionSyntaxForExecutionContext -}} +func {{ $field.FieldContextFunc }}({{ if not $field.Args }}_{{ else }}ctx{{ end }} context.Context, ec *executionContext, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +{{- else -}} +func (ec *executionContext) {{ $field.FieldContextFunc }}({{ if not $field.Args }}_{{ else }}ctx{{ end }} context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +{{- end }} fc = &graphql.FieldContext{ Object: {{quote $field.Object.Name}}, Field: field, @@ -77,7 +105,11 @@ func (ec *executionContext) {{ $field.FieldContextFunc }}(ctx context.Context, f switch field.Name { {{- range $f := $field.TypeReference.Definition.Fields }} case "{{ $f.Name }}": + {{ if $useFunctionSyntaxForExecutionContext -}} + return {{ $field.ChildFieldContextFunc $f.Name }}(ctx, ec, field) + {{- else -}} return ec.{{ $field.ChildFieldContextFunc $f.Name }}(ctx, field) + {{- end }} {{- end }} } return nil, fmt.Errorf("no field named %q was found under type {{ $field.TypeReference.Definition.Name }}", field.Name) @@ -85,16 +117,22 @@ func (ec *executionContext) {{ $field.FieldContextFunc }}(ctx context.Context, f }, } {{- if $field.Args }} + {{- if not $.Config.OmitPanicHandler }} defer func () { if r := recover(); r != nil { err = ec.Recover(ctx, r) ec.Error(ctx, err) } }() + {{- end }} ctx = graphql.WithFieldContext(ctx, fc) + {{ if $useFunctionSyntaxForExecutionContext -}} + if fc.Args, err = {{ $field.ArgsFunc }}(ctx, ec, field.ArgumentMap(ec.Variables)); err != nil { + {{- else -}} if fc.Args, err = ec.{{ $field.ArgsFunc }}(ctx, field.ArgumentMap(ec.Variables)); err != nil { + {{- end }} ec.Error(ctx, err) - return + return fc, err } {{- end }} return fc, nil @@ -102,31 +140,12 @@ func (ec *executionContext) {{ $field.FieldContextFunc }}(ctx context.Context, f {{- end }}{{- end}} -{{ define "field" }} - {{- if .HasDirectives -}} - directive0 := func(rctx context.Context) (interface{}, error) { - ctx = rctx // use context from middleware stack in children - {{ template "fieldDefinition" . }} - } - {{ template "implDirectives" . }} - tmp, err := directive{{.ImplDirectives|len}}(rctx) - if err != nil { - return nil, graphql.ErrorOnPath(ctx, err) - } - if tmp == nil { - return nil, nil - } - if data, ok := tmp.({{if .Stream}}<-chan {{end}}{{ .TypeReference.GO | ref }}) ; ok { - return data, nil - } - return nil, fmt.Errorf(`unexpected type %T from directive, should be {{if .Stream}}<-chan {{end}}{{ .TypeReference.GO }}`, tmp) - {{- else -}} - ctx = rctx // use context from middleware stack in children - {{ template "fieldDefinition" . }} - {{- end -}} -{{ end }} - {{ define "fieldDefinition" }} + {{- if or .IsResolver .IsMethod -}} + {{- if gt (len .Args) 0 -}} + fc := graphql.GetFieldContext(ctx) + {{- end }} + {{ end }} {{- if .IsResolver -}} return ec.resolvers.{{ .ShortInvocation }} {{- else if .IsMap -}} diff --git a/vendor/github.com/99designs/gqlgen/codegen/generate.go b/vendor/github.com/99designs/gqlgen/codegen/generate.go index 1ce8c329d..3d88b0458 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/generate.go +++ b/vendor/github.com/99designs/gqlgen/codegen/generate.go @@ -4,14 +4,13 @@ import ( "embed" "errors" "fmt" - "os" "path/filepath" - "runtime" "strings" + "github.com/vektah/gqlparser/v2/ast" + "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" ) //go:embed *.gotpl @@ -19,7 +18,7 @@ var codegenTemplates embed.FS func GenerateCode(data *Data) error { if !data.Config.Exec.IsDefined() { - return fmt.Errorf("missing exec config") + return errors.New("missing exec config") } switch data.Config.Exec.Layout { @@ -128,24 +127,18 @@ func addBuild(filename string, p *ast.Position, data *Data, builds *map[string]* } } +//go:embed root_.gotpl +var rootTemplate string + // Root file contains top-level definitions that should not be duplicated across the generated // files for each schema file. func generateRootFile(data *Data) error { dir := data.Config.Exec.DirName path := filepath.Join(dir, "root_.generated.go") - _, thisFile, _, _ := runtime.Caller(0) - rootDir := filepath.Dir(thisFile) - templatePath := filepath.Join(rootDir, "root_.gotpl") - templateBytes, err := os.ReadFile(templatePath) - if err != nil { - return err - } - template := string(templateBytes) - return templates.Render(templates.Options{ PackageName: data.Config.Exec.Package, - Template: template, + Template: rootTemplate, Filename: path, Data: data, RegionTags: false, diff --git a/vendor/github.com/99designs/gqlgen/codegen/generated!.gotpl b/vendor/github.com/99designs/gqlgen/codegen/generated!.gotpl index 0998c7750..b09d770e7 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/generated!.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/generated!.gotpl @@ -1,3 +1,4 @@ +{{/* Context object: codegen.Data */}} {{ reserveImport "context" }} {{ reserveImport "fmt" }} {{ reserveImport "io" }} @@ -9,16 +10,19 @@ {{ reserveImport "bytes" }} {{ reserveImport "embed" }} +{{ reserveImport "golang.org/x/sync/semaphore"}} {{ reserveImport "github.com/vektah/gqlparser/v2" "gqlparser" }} {{ reserveImport "github.com/vektah/gqlparser/v2/ast" }} {{ reserveImport "github.com/99designs/gqlgen/graphql" }} {{ reserveImport "github.com/99designs/gqlgen/graphql/introspection" }} +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} {{ if eq .Config.Exec.Layout "single-file" }} // NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { return &executableSchema{ + schema: cfg.Schema, resolvers: cfg.Resolvers, directives: cfg.Directives, complexity: cfg.Complexity, @@ -26,6 +30,7 @@ } type Config struct { + Schema *ast.Schema Resolvers ResolverRoot Directives DirectiveRoot Complexity ComplexityRoot @@ -45,12 +50,13 @@ } type DirectiveRoot struct { - {{ range $directive := .Directives }} + {{ range $directive := .UserDirectives }} {{- $directive.Declaration }} {{ end }} } type ComplexityRoot struct { + {{- if not .Config.OmitComplexity }} {{ range $object := .Objects }} {{ if not $object.IsReserved -}} {{ ucFirst $object.Name }} struct { @@ -63,6 +69,7 @@ } {{- end }} {{ end }} + {{- end }} } {{ end }} @@ -90,20 +97,31 @@ {{- end }} {{- end }} +{{ range $directive := .BuiltInDirectives }} + var ( + {{- $directive.FunctionImpl }} + ) +{{ end }} + {{ if eq .Config.Exec.Layout "single-file" }} type executableSchema struct { + schema *ast.Schema resolvers ResolverRoot directives DirectiveRoot complexity ComplexityRoot } func (e *executableSchema) Schema() *ast.Schema { + if e.schema != nil { + return e.schema + } return parsedSchema } - func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { - ec := executionContext{nil, e} + func (e *executableSchema) Complexity(ctx context.Context, typeName, field string, childComplexity int, rawArgs map[string]any) (int, bool) { + ec := executionContext{nil, e, 0, 0, nil} _ = ec + {{ if not .Config.OmitComplexity -}} switch typeName + "." + field { {{ range $object := .Objects }} {{ if not $object.IsReserved }} @@ -117,53 +135,88 @@ break } {{ if $field.Args }} - args, err := ec.{{ $field.ArgsFunc }}(context.TODO(),rawArgs) + {{ if $useFunctionSyntaxForExecutionContext -}} + args, err := {{ $field.ArgsFunc }}(ctx, &ec, rawArgs) + {{- else -}} + args, err := ec.{{ $field.ArgsFunc }}(ctx,rawArgs) + {{- end }} if err != nil { return 0, false } {{ end }} return e.complexity.{{ucFirst $object.Name}}.{{$field.GoFieldName}}(childComplexity{{if $field.Args}}, {{$field.ComplexityArgs}} {{ end }}), true - {{ end }} + {{- end }} {{- end }} {{- end }} {{ end }} {{ end }} {{ end }} } + {{- end }} return 0, false } func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { - rc := graphql.GetOperationContext(ctx) - ec := executionContext{rc, e} + opCtx := graphql.GetOperationContext(ctx) + ec := executionContext{opCtx, e, 0, 0, make(chan graphql.DeferredResult)} inputUnmarshalMap := graphql.BuildUnmarshalerMap( {{- range $input := .Inputs -}} {{ if not $input.HasUnmarshal }} + {{ if $useFunctionSyntaxForExecutionContext -}} + unmarshalInput{{ $input.Name }}, + {{- else -}} ec.unmarshalInput{{ $input.Name }}, + {{- end }} {{- end }} {{- end }} ) first := true - switch rc.Operation.Operation { + switch opCtx.Operation.Operation { {{- if .QueryRoot }} case ast.Query: return func(ctx context.Context) *graphql.Response { - if !first { return nil } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - {{ if .Directives.LocationDirectives "QUERY" -}} - data := ec._queryMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet), nil - }) - {{- else -}} - data := ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} + var response graphql.Response + var data graphql.Marshaler + if first { + first = false + ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) + {{ if .Directives.LocationDirectives "QUERY" -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + data = _queryMiddleware(ctx, &ec, opCtx.Operation, func(ctx context.Context) (any, error){ + return _{{.QueryRoot.Name}}(ctx, ec, opCtx.Operation.SelectionSet), nil + {{- else -}} + data = ec._queryMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error){ + return ec._{{.QueryRoot.Name}}(ctx, opCtx.Operation.SelectionSet), nil + {{- end }} + }) + {{- else -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + data = _{{.QueryRoot.Name}}(ctx, &ec, opCtx.Operation.SelectionSet) + {{- else -}} + data = ec._{{.QueryRoot.Name}}(ctx, opCtx.Operation.SelectionSet) + {{- end }} + {{- end }} + } else { + if atomic.LoadInt32(&ec.pendingDeferred) > 0 { + result := <-ec.deferredResults + atomic.AddInt32(&ec.pendingDeferred, -1) + data = result.Result + response.Path = result.Path + response.Label = result.Label + response.Errors = result.Errors + } else { + return nil + } + } var buf bytes.Buffer data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), + response.Data = buf.Bytes() + if atomic.LoadInt32(&ec.deferred) > 0 { + hasNext := atomic.LoadInt32(&ec.pendingDeferred) > 0 + response.HasNext = &hasNext } + + return &response } {{ end }} @@ -173,11 +226,20 @@ first = false ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) {{ if .Directives.LocationDirectives "MUTATION" -}} - data := ec._mutationMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet), nil + {{ if $useFunctionSyntaxForExecutionContext -}} + data := _mutationMiddleware(ctx, &ec, opCtx.Operation, func(ctx context.Context) (any, error){ + return _{{.MutationRoot.Name}}(ctx, ec, opCtx.Operation.SelectionSet), nil + {{- else -}} + data := ec._mutationMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error){ + return ec._{{.MutationRoot.Name}}(ctx, opCtx.Operation.SelectionSet), nil + {{- end }} }) {{- else -}} - data := ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet) + {{ if $useFunctionSyntaxForExecutionContext -}} + data := _{{.MutationRoot.Name}}(ctx, &ec, opCtx.Operation.SelectionSet) + {{- else -}} + data := ec._{{.MutationRoot.Name}}(ctx, opCtx.Operation.SelectionSet) + {{- end }} {{- end }} var buf bytes.Buffer data.MarshalGQL(&buf) @@ -190,11 +252,20 @@ {{- if .SubscriptionRoot }} case ast.Subscription: {{ if .Directives.LocationDirectives "SUBSCRIPTION" -}} - next := ec._subscriptionMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet),nil + {{ if $useFunctionSyntaxForExecutionContext -}} + next := _subscriptionMiddleware(ctx, &ec, opCtx.Operation, func(ctx context.Context) (any, error){ + return _{{.SubscriptionRoot.Name}}(ctx, ec, opCtx.Operation.SelectionSet),nil + {{- else -}} + next := ec._subscriptionMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error){ + return ec._{{.SubscriptionRoot.Name}}(ctx, opCtx.Operation.SelectionSet),nil + {{- end }} }) {{- else -}} - next := ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet) + {{ if $useFunctionSyntaxForExecutionContext -}} + next := _{{.SubscriptionRoot.Name}}(ctx, &ec, opCtx.Operation.SelectionSet) + {{- else -}} + next := ec._{{.SubscriptionRoot.Name}}(ctx, opCtx.Operation.SelectionSet) + {{- end }} {{- end }} var buf bytes.Buffer @@ -220,20 +291,42 @@ type executionContext struct { *graphql.OperationContext *executableSchema + deferred int32 + pendingDeferred int32 + deferredResults chan graphql.DeferredResult + } + + func (ec *executionContext) processDeferredGroup(dg graphql.DeferredGroup) { + atomic.AddInt32(&ec.pendingDeferred, 1) + go func () { + ctx := graphql.WithFreshResponseContext(dg.Context) + dg.FieldSet.Dispatch(ctx) + ds := graphql.DeferredResult{ + Path: dg.Path, + Label: dg.Label, + Result: dg.FieldSet, + Errors: graphql.GetErrors(ctx), + } + // null fields should bubble up + if dg.FieldSet.Invalids > 0 { + ds.Result = graphql.Null + } + ec.deferredResults <- ds + }() } func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { if ec.DisableIntrospection { return nil, errors.New("introspection disabled") } - return introspection.WrapSchema(parsedSchema), nil + return introspection.WrapSchema(ec.Schema()), nil } func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { if ec.DisableIntrospection { return nil, errors.New("introspection disabled") } - return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]), nil + return introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil } {{if .HasEmbeddableSources }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/input.gotpl b/vendor/github.com/99designs/gqlgen/codegen/input.gotpl index 116fe9ce7..6b674b6f9 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/input.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/input.gotpl @@ -1,9 +1,23 @@ +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} + {{- range $input := .Inputs }} {{- if not .HasUnmarshal }} - func (ec *executionContext) unmarshalInput{{ .Name }}(ctx context.Context, obj interface{}) ({{.Type | ref}}, error) { - var it {{.Type | ref}} - asMap := map[string]interface{}{} - for k, v := range obj.(map[string]interface{}) { + {{- $it := "it" }} + {{- if .PointersInUnmarshalInput }} + {{- $it = "&it" }} + {{- end }} + {{ if $useFunctionSyntaxForExecutionContext -}} + func unmarshalInput{{ .Name }}(ctx context.Context, ec *executionContext, obj any) ({{ if .PointersInUnmarshalInput }}*{{ end }}{{.Type | ref}}, error) { + {{- else -}} + func (ec *executionContext) unmarshalInput{{ .Name }}(ctx context.Context, obj any) ({{ if .PointersInUnmarshalInput }}*{{ end }}{{.Type | ref}}, error) { + {{- end }} + {{- if $input.IsMap }} + it := make(map[string]any, len(obj.(map[string]any))) + {{- else }} + var it {{.Type | ref}} + {{- end }} + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { asMap[k] = v } {{ range $field := .Fields}} @@ -23,55 +37,82 @@ switch k { {{- range $field := .Fields }} case {{$field.Name|quote}}: - var err error - + {{- $lhs := (printf "it.%s" $field.GoFieldName) }} + {{- if $input.IsMap }} + {{- $lhs = (printf "it[%q]" $field.Name) }} + {{- end }} ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField({{$field.Name|quote}})) {{- if $field.ImplDirectives }} - directive0 := func(ctx context.Context) (interface{}, error) { return ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) } - {{ template "implDirectives" $field }} + {{ if $useFunctionSyntaxForExecutionContext -}} + directive0 := func(ctx context.Context) (any, error) { return {{ $field.TypeReference.UnmarshalFunc }}(ctx, ec, v) } + {{- else -}} + directive0 := func(ctx context.Context) (any, error) { return ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) } + {{- end }} + {{ template "implDirectives" (dict "Field" $field "UseFunctionSyntaxForExecutionContext" $useFunctionSyntaxForExecutionContext) }} tmp, err := directive{{$field.ImplDirectives|len}}(ctx) if err != nil { - return it, graphql.ErrorOnPath(ctx, err) + return {{$it}}, graphql.ErrorOnPath(ctx, err) } if data, ok := tmp.({{ $field.TypeReference.GO | ref }}) ; ok { {{- if $field.IsResolver }} if err = ec.resolvers.{{ $field.ShortInvocation }}; err != nil { - return it, err + return {{$it}}, err } {{- else }} - it.{{$field.GoFieldName}} = data + {{- if $field.TypeReference.IsOmittable }} + {{ $lhs }} = graphql.OmittableOf(data) + {{- else }} + {{ $lhs }} = data + {{- end }} {{- end }} {{- if $field.TypeReference.IsNilable }} {{- if not $field.IsResolver }} } else if tmp == nil { - it.{{$field.GoFieldName}} = nil + {{- if $field.TypeReference.IsOmittable }} + {{ $lhs }} = graphql.OmittableOf[{{ $field.TypeReference.GO | ref }}](nil) + {{- else }} + {{ $lhs }} = nil + {{- end }} {{- end }} {{- end }} } else { err := fmt.Errorf(`unexpected type %T from directive, should be {{ $field.TypeReference.GO }}`, tmp) - return it, graphql.ErrorOnPath(ctx, err) + return {{$it}}, graphql.ErrorOnPath(ctx, err) } {{- else }} {{- if $field.IsResolver }} + {{ if $useFunctionSyntaxForExecutionContext -}} + data, err := {{ $field.TypeReference.UnmarshalFunc }}(ctx, ec, v) + {{- else -}} data, err := ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) + {{- end }} if err != nil { - return it, err + return {{$it}}, err } if err = ec.resolvers.{{ $field.ShortInvocation }}; err != nil { - return it, err + return {{$it}}, err } {{- else }} - it.{{$field.GoFieldName}}, err = ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) + {{ if $useFunctionSyntaxForExecutionContext -}} + data, err := {{ $field.TypeReference.UnmarshalFunc }}(ctx, ec, v) + {{- else -}} + data, err := ec.{{ $field.TypeReference.UnmarshalFunc }}(ctx, v) + {{- end }} if err != nil { - return it, err + return {{$it}}, err } + {{- if $field.TypeReference.IsOmittable }} + {{ $lhs }} = graphql.OmittableOf(data) + {{- else }} + {{ $lhs }} = data + {{- end }} {{- end }} {{- end }} {{- end }} } } - return it, nil + return {{$it}}, nil } {{- end }} {{ end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/interface.go b/vendor/github.com/99designs/gqlgen/codegen/interface.go index cdc4d4d32..729e93f08 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/interface.go +++ b/vendor/github.com/99designs/gqlgen/codegen/interface.go @@ -3,6 +3,7 @@ package codegen import ( "fmt" "go/types" + "sort" "github.com/vektah/gqlparser/v2/ast" @@ -40,7 +41,20 @@ func (b *builder) buildInterface(typ *ast.Definition) (*Interface, error) { return nil, fmt.Errorf("%s is not an interface", i.Type) } - for _, implementor := range b.Schema.GetPossibleTypes(typ) { + // Sort so that more specific types are evaluated first. + implementors := b.Schema.GetPossibleTypes(typ) + + sort.SliceStable(implementors, func(i, j int) bool { + if len(implementors[i].Interfaces) != len(implementors[j].Interfaces) { + return len(implementors[i].Interfaces) > len(implementors[j].Interfaces) + } + // if they have the same name, they probably ARE the same + // so we need to rely on SliceStable or else order is + // non-deterministic and causes test failures + return implementors[i].Name > implementors[j].Name + }) + + for _, implementor := range implementors { obj, err := b.Binder.DefaultUserObject(implementor.Name) if err != nil { return nil, fmt.Errorf("%s has no backing go type", implementor.Name) diff --git a/vendor/github.com/99designs/gqlgen/codegen/interface.gotpl b/vendor/github.com/99designs/gqlgen/codegen/interface.gotpl index e9d560c8f..ee975a51a 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/interface.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/interface.gotpl @@ -1,6 +1,12 @@ +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} + {{- range $interface := .Interfaces }} +{{ if $useFunctionSyntaxForExecutionContext -}} +func _{{$interface.Name}}(ctx context.Context, ec *executionContext, sel ast.SelectionSet, obj {{$interface.Type | ref}}) graphql.Marshaler { +{{- else -}} func (ec *executionContext) _{{$interface.Name}}(ctx context.Context, sel ast.SelectionSet, obj {{$interface.Type | ref}}) graphql.Marshaler { +{{- end }} switch obj := (obj).(type) { case nil: return graphql.Null @@ -11,7 +17,11 @@ func (ec *executionContext) _{{$interface.Name}}(ctx context.Context, sel ast.Se return graphql.Null } {{- end }} + {{ if $useFunctionSyntaxForExecutionContext -}} + return _{{$implementor.Name}}(ctx, ec, sel, {{ if $implementor.TakeRef }}&{{ end }}obj) + {{- else -}} return ec._{{$implementor.Name}}(ctx, sel, {{ if $implementor.TakeRef }}&{{ end }}obj) + {{- end }} {{- end }} default: panic(fmt.Errorf("unexpected type %T", obj)) diff --git a/vendor/github.com/99designs/gqlgen/codegen/object.go b/vendor/github.com/99designs/gqlgen/codegen/object.go index a9cb34061..81dce31e2 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/object.go +++ b/vendor/github.com/99designs/gqlgen/codegen/object.go @@ -7,10 +7,11 @@ import ( "strings" "unicode" - "github.com/99designs/gqlgen/codegen/config" "github.com/vektah/gqlparser/v2/ast" "golang.org/x/text/cases" "golang.org/x/text/language" + + "github.com/99designs/gqlgen/codegen/config" ) type GoFieldType int @@ -25,14 +26,15 @@ const ( type Object struct { *ast.Definition - Type types.Type - ResolverInterface types.Type - Root bool - Fields []*Field - Implements []*ast.Definition - DisableConcurrency bool - Stream bool - Directives []*Directive + Type types.Type + ResolverInterface types.Type + Root bool + Fields []*Field + Implements []*ast.Definition + DisableConcurrency bool + Stream bool + Directives []*Directive + PointersInUnmarshalInput bool } func (b *builder) buildObject(typ *ast.Definition) (*Object, error) { @@ -42,11 +44,12 @@ func (b *builder) buildObject(typ *ast.Definition) (*Object, error) { } caser := cases.Title(language.English, cases.NoLower) obj := &Object{ - Definition: typ, - Root: b.Schema.Query == typ || b.Schema.Mutation == typ || b.Schema.Subscription == typ, - DisableConcurrency: typ == b.Schema.Mutation, - Stream: typ == b.Schema.Subscription, - Directives: dirs, + Definition: typ, + Root: b.Config.IsRoot(typ), + DisableConcurrency: typ == b.Schema.Mutation, + Stream: typ == b.Schema.Subscription, + Directives: dirs, + PointersInUnmarshalInput: b.Config.ReturnPointersInUnmarshalInput, ResolverInterface: types.NewNamed( types.NewTypeName(0, b.Config.Exec.Pkg(), caser.String(typ.Name)+"Resolver", nil), nil, @@ -110,8 +113,8 @@ func (o *Object) HasResolvers() bool { } func (o *Object) HasUnmarshal() bool { - if o.Type == config.MapType { - return true + if o.IsMap() { + return false } for i := 0; i < o.Type.(*types.Named).NumMethods(); i++ { if o.Type.(*types.Named).Method(i).Name() == "UnmarshalGQL" { @@ -144,16 +147,30 @@ func (o *Object) IsConcurrent() bool { } func (o *Object) IsReserved() bool { - return strings.HasPrefix(o.Definition.Name, "__") + return strings.HasPrefix(o.Name, "__") +} + +func (o *Object) IsMap() bool { + return o.Type == config.MapType } func (o *Object) Description() string { return o.Definition.Description } +func (o *Object) HasField(name string) bool { + for _, f := range o.Fields { + if f.Name == name { + return true + } + } + + return false +} + func (os Objects) ByName(name string) *Object { for i, o := range os { - if strings.EqualFold(o.Definition.Name, name) { + if strings.EqualFold(o.Name, name) { return os[i] } } diff --git a/vendor/github.com/99designs/gqlgen/codegen/object.gotpl b/vendor/github.com/99designs/gqlgen/codegen/object.gotpl index 1fbdfacec..f42d35743 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/object.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/object.gotpl @@ -1,9 +1,15 @@ +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} + {{- range $object := .Objects }} var {{ $object.Name|lcFirst}}Implementors = {{$object.Implementors}} {{- if .Stream }} +{{ if $useFunctionSyntaxForExecutionContext -}} +func _{{$object.Name}}(ctx context.Context, ec *executionContext, sel ast.SelectionSet) func(ctx context.Context) graphql.Marshaler { +{{- else -}} func (ec *executionContext) _{{$object.Name}}(ctx context.Context, sel ast.SelectionSet) func(ctx context.Context) graphql.Marshaler { +{{- end }} fields := graphql.CollectFields(ec.OperationContext, sel, {{$object.Name|lcFirst}}Implementors) ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ Object: {{$object.Name|quote}}, @@ -16,95 +22,153 @@ func (ec *executionContext) _{{$object.Name}}(ctx context.Context, sel ast.Selec switch fields[0].Name { {{- range $field := $object.Fields }} case "{{$field.Name}}": + {{ if $useFunctionSyntaxForExecutionContext -}} + return _{{$object.Name}}_{{$field.Name}}(ctx, ec, fields[0]) + {{- else -}} return ec._{{$object.Name}}_{{$field.Name}}(ctx, fields[0]) + {{- end }} {{- end }} default: panic("unknown field " + strconv.Quote(fields[0].Name)) } } {{- else }} + +{{ if $useFunctionSyntaxForExecutionContext -}} +func _{{$object.Name}}(ctx context.Context, ec *executionContext, sel ast.SelectionSet{{ if not $object.Root }},obj {{$object.Reference | ref }}{{ end }}) graphql.Marshaler { +{{- else -}} func (ec *executionContext) _{{$object.Name}}(ctx context.Context, sel ast.SelectionSet{{ if not $object.Root }},obj {{$object.Reference | ref }}{{ end }}) graphql.Marshaler { +{{- end }} fields := graphql.CollectFields(ec.OperationContext, sel, {{$object.Name|lcFirst}}Implementors) - {{- if $object.Root }} - ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ - Object: {{$object.Name|quote}}, - }) - {{end}} + {{- if $object.Root }} + ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ + Object: {{$object.Name|quote}}, + }) + {{end}} + out := graphql.NewFieldSet(fields) - var invalids uint32 + deferred := make(map[string]*graphql.FieldSet) for i, field := range fields { - {{- if $object.Root }} - innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ - Object: field.Name, - Field: field, - }) - {{end}} - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString({{$object.Name|quote}}) - {{- range $field := $object.Fields }} - case "{{$field.Name}}": - {{- if $field.IsConcurrent }} - field := field - - innerFunc := func(ctx context.Context) (res graphql.Marshaler) { - defer func() { - if r := recover(); r != nil { - ec.Error(ctx, ec.Recover(ctx, r)) - } - }() - res = ec._{{$object.Name}}_{{$field.Name}}(ctx, field{{if not $object.Root}}, obj{{end}}) - {{- if $field.TypeReference.GQL.NonNull }} - if res == graphql.Null { - {{- if $object.IsConcurrent }} - atomic.AddUint32(&invalids, 1) - {{- else }} - invalids++ - {{- end }} - } - {{- end }} - return res - } - - {{if $object.Root}} - rrm := func(ctx context.Context) graphql.Marshaler { - return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc) - } - {{end}} - - out.Concurrently(i, func() graphql.Marshaler { - {{- if $object.Root -}} - return rrm(innerCtx) - {{- else -}} - return innerFunc(ctx) - {{end}} - }) - {{- else }} - {{if $object.Root}} - out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { - return ec._{{$object.Name}}_{{$field.Name}}(ctx, field) - }) - {{else}} - out.Values[i] = ec._{{$object.Name}}_{{$field.Name}}(ctx, field, obj) - {{end}} - - {{- if $field.TypeReference.GQL.NonNull }} - if out.Values[i] == graphql.Null { - {{- if $object.IsConcurrent }} - atomic.AddUint32(&invalids, 1) - {{- else }} - invalids++ - {{- end }} - } - {{- end }} - {{- end }} - {{- end }} - default: - panic("unknown field " + strconv.Quote(field.Name)) - } + {{- if $object.Root }} + innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ + Object: field.Name, + Field: field, + }) + {{end}} + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString({{$object.Name|quote}}) + {{- range $field := $object.Fields }} + case "{{$field.Name}}": + {{- if $field.IsConcurrent }} + field := field + + innerFunc := func(ctx context.Context, {{ if $field.TypeReference.GQL.NonNull }}fs{{ else }}_{{ end }} *graphql.FieldSet) (res graphql.Marshaler) { + {{- if not $.Config.OmitPanicHandler }} + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + {{- end }} + {{ if $useFunctionSyntaxForExecutionContext -}} + res = _{{$object.Name}}_{{$field.Name}}(ctx, ec, field{{if not $object.Root}}, obj{{end}}) + {{- else -}} + res = ec._{{$object.Name}}_{{$field.Name}}(ctx, field{{if not $object.Root}}, obj{{end}}) + {{- end }} + {{- if $field.TypeReference.GQL.NonNull }} + if res == graphql.Null { + {{- if $object.IsConcurrent }} + atomic.AddUint32(&fs.Invalids, 1) + {{- else }} + fs.Invalids++ + {{- end }} + } + {{- end }} + return res + } + + {{if $object.Root}} + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + {{end}} + + {{if not $object.Root}} + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + {{end}} + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { + {{- if $object.Root -}} + return rrm(innerCtx) + {{- else -}} + return innerFunc(ctx, out) + {{- end -}} + }) + {{- else }} + {{- if $object.Root -}} + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + {{ if $useFunctionSyntaxForExecutionContext -}} + return _{{$object.Name}}_{{$field.Name}}(ctx, ec, field) + {{- else -}} + return ec._{{$object.Name}}_{{$field.Name}}(ctx, field) + {{- end }} + }) + {{- else -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + out.Values[i] = _{{$object.Name}}_{{$field.Name}}(ctx, ec, field, obj) + {{- else -}} + out.Values[i] = ec._{{$object.Name}}_{{$field.Name}}(ctx, field, obj) + {{- end }} + {{- end -}} + + {{- if $field.TypeReference.GQL.NonNull }} + if out.Values[i] == graphql.Null { + {{- if $object.IsConcurrent }} + atomic.AddUint32(&out.Invalids, 1) + {{- else }} + out.Invalids++ + {{- end }} + } + {{- end }} + {{- end }} + {{- end }} + default: + panic("unknown field " + strconv.Quote(field.Name)) + } } - out.Dispatch() - if invalids > 0 { return graphql.Null } + out.Dispatch(ctx) + if out.Invalids > 0 { return graphql.Null } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + return out } {{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/root_.gotpl b/vendor/github.com/99designs/gqlgen/codegen/root_.gotpl index 2f2a98262..f84d0f9d4 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/root_.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/root_.gotpl @@ -1,3 +1,4 @@ +{{/* Context object: codegen.Data */}} {{ reserveImport "context" }} {{ reserveImport "fmt" }} {{ reserveImport "io" }} @@ -14,9 +15,12 @@ {{ reserveImport "github.com/99designs/gqlgen/graphql" }} {{ reserveImport "github.com/99designs/gqlgen/graphql/introspection" }} +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} + // NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { return &executableSchema{ + schema: cfg.Schema, resolvers: cfg.Resolvers, directives: cfg.Directives, complexity: cfg.Complexity, @@ -24,6 +28,7 @@ func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { } type Config struct { + Schema *ast.Schema Resolvers ResolverRoot Directives DirectiveRoot Complexity ComplexityRoot @@ -43,12 +48,13 @@ type ResolverRoot interface { } type DirectiveRoot struct { -{{ range $directive := .Directives }} +{{ range $directive := .UserDirectives }} {{- $directive.Declaration }} {{ end }} } type ComplexityRoot struct { +{{- if not .Config.OmitComplexity }} {{ range $object := .Objects }} {{ if not $object.IsReserved -}} {{ ucFirst $object.Name }} struct { @@ -61,21 +67,33 @@ type ComplexityRoot struct { } {{- end }} {{ end }} +{{- end }} } +{{ range $directive := .BuiltInDirectives }} + var ( + {{- $directive.FunctionImpl }} + ) +{{ end }} + type executableSchema struct { + schema *ast.Schema resolvers ResolverRoot directives DirectiveRoot complexity ComplexityRoot } func (e *executableSchema) Schema() *ast.Schema { + if e.schema != nil { + return e.schema + } return parsedSchema } -func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { - ec := executionContext{nil, e} +func (e *executableSchema) Complexity(ctx context.Context, typeName, field string, childComplexity int, rawArgs map[string]any) (int, bool) { + ec := executionContext{nil, e, 0, 0, nil} _ = ec + {{- if not .Config.OmitComplexity }} switch typeName + "." + field { {{ range $object := .Objects }} {{ if not $object.IsReserved }} @@ -89,7 +107,11 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in break } {{ if $field.Args }} - args, err := ec.{{ $field.ArgsFunc }}(context.TODO(),rawArgs) + {{ if $useFunctionSyntaxForExecutionContext -}} + args, err := {{ $field.ArgsFunc }}(ctx, &ec, rawArgs) + {{- else -}} + args, err := ec.{{ $field.ArgsFunc }}(ctx,rawArgs) + {{- end }} if err != nil { return 0, false } @@ -102,40 +124,71 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in {{ end }} {{ end }} } + {{- end }} return 0, false } func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { - rc := graphql.GetOperationContext(ctx) - ec := executionContext{rc, e} + opCtx := graphql.GetOperationContext(ctx) + ec := executionContext{opCtx, e, 0, 0, make(chan graphql.DeferredResult)} inputUnmarshalMap := graphql.BuildUnmarshalerMap( {{- range $input := .Inputs -}} {{ if not $input.HasUnmarshal }} + {{ if $useFunctionSyntaxForExecutionContext -}} + unmarshalInput{{ $input.Name }}, + {{- else -}} ec.unmarshalInput{{ $input.Name }}, + {{- end }} {{- end }} {{- end }} ) first := true - switch rc.Operation.Operation { + switch opCtx.Operation.Operation { {{- if .QueryRoot }} case ast.Query: return func(ctx context.Context) *graphql.Response { - if !first { return nil } - first = false - ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) - {{ if .Directives.LocationDirectives "QUERY" -}} - data := ec._queryMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet), nil - }) - {{- else -}} - data := ec._{{.QueryRoot.Name}}(ctx, rc.Operation.SelectionSet) - {{- end }} + var response graphql.Response + var data graphql.Marshaler + if first { + first = false + ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) + {{ if .Directives.LocationDirectives "QUERY" -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + data = _queryMiddleware(ctx, ec, opCtx.Operation, func(ctx context.Context) (any, error){ + return _{{.QueryRoot.Name}}(ctx, &ec, opCtx.Operation.SelectionSet), nil + {{- else -}} + data = ec._queryMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error){ + return ec._{{.QueryRoot.Name}}(ctx, opCtx.Operation.SelectionSet), nil + {{- end }} + }) + {{- else -}} + {{ if $useFunctionSyntaxForExecutionContext -}} + data = _{{.QueryRoot.Name}}(ctx, &ec, opCtx.Operation.SelectionSet) + {{- else -}} + data = ec._{{.QueryRoot.Name}}(ctx, opCtx.Operation.SelectionSet) + {{- end }} + {{- end }} + } else { + if atomic.LoadInt32(&ec.pendingDeferred) > 0 { + result := <-ec.deferredResults + atomic.AddInt32(&ec.pendingDeferred, -1) + data = result.Result + response.Path = result.Path + response.Label = result.Label + response.Errors = result.Errors + } else { + return nil + } + } var buf bytes.Buffer data.MarshalGQL(&buf) - - return &graphql.Response{ - Data: buf.Bytes(), + response.Data = buf.Bytes() + if atomic.LoadInt32(&ec.deferred) > 0 { + hasNext := atomic.LoadInt32(&ec.pendingDeferred) > 0 + response.HasNext = &hasNext } + + return &response } {{ end }} @@ -145,11 +198,20 @@ func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { first = false ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) {{ if .Directives.LocationDirectives "MUTATION" -}} - data := ec._mutationMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet), nil + {{ if $useFunctionSyntaxForExecutionContext -}} + data := _mutationMiddleware(ctx, &ec, opCtx.Operation, func(ctx context.Context) (any, error){ + return _{{.MutationRoot.Name}}(ctx, ec, opCtx.Operation.SelectionSet), nil + {{- else -}} + data := ec._mutationMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error){ + return ec._{{.MutationRoot.Name}}(ctx, opCtx.Operation.SelectionSet), nil + {{- end }} }) {{- else -}} - data := ec._{{.MutationRoot.Name}}(ctx, rc.Operation.SelectionSet) + {{ if $useFunctionSyntaxForExecutionContext -}} + data := _{{.MutationRoot.Name}}(ctx, &ec, opCtx.Operation.SelectionSet) + {{- else -}} + data := ec._{{.MutationRoot.Name}}(ctx, opCtx.Operation.SelectionSet) + {{- end }} {{- end }} var buf bytes.Buffer data.MarshalGQL(&buf) @@ -162,11 +224,20 @@ func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { {{- if .SubscriptionRoot }} case ast.Subscription: {{ if .Directives.LocationDirectives "SUBSCRIPTION" -}} - next := ec._subscriptionMiddleware(ctx, rc.Operation, func(ctx context.Context) (interface{}, error){ - return ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet),nil + {{ if $useFunctionSyntaxForExecutionContext -}} + next := _subscriptionMiddleware(ctx, &ec, opCtx.Operation, func(ctx context.Context) (any, error){ + return _{{.SubscriptionRoot.Name}}(ctx, ec, opCtx.Operation.SelectionSet),nil + {{- else -}} + next := ec._subscriptionMiddleware(ctx, opCtx.Operation, func(ctx context.Context) (any, error){ + return ec._{{.SubscriptionRoot.Name}}(ctx, opCtx.Operation.SelectionSet),nil + {{- end }} }) {{- else -}} - next := ec._{{.SubscriptionRoot.Name}}(ctx, rc.Operation.SelectionSet) + {{ if $useFunctionSyntaxForExecutionContext -}} + next := _{{.SubscriptionRoot.Name}}(ctx, &ec, opCtx.Operation.SelectionSet) + {{- else -}} + next := ec._{{.SubscriptionRoot.Name}}(ctx, opCtx.Operation.SelectionSet) + {{- end }} {{- end }} var buf bytes.Buffer @@ -192,20 +263,42 @@ func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { type executionContext struct { *graphql.OperationContext *executableSchema + deferred int32 + pendingDeferred int32 + deferredResults chan graphql.DeferredResult +} + +func (ec *executionContext) processDeferredGroup(dg graphql.DeferredGroup) { + atomic.AddInt32(&ec.pendingDeferred, 1) + go func () { + ctx := graphql.WithFreshResponseContext(dg.Context) + dg.FieldSet.Dispatch(ctx) + ds := graphql.DeferredResult{ + Path: dg.Path, + Label: dg.Label, + Result: dg.FieldSet, + Errors: graphql.GetErrors(ctx), + } + // null fields should bubble up + if dg.FieldSet.Invalids > 0 { + ds.Result = graphql.Null + } + ec.deferredResults <- ds + }() } func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { if ec.DisableIntrospection { return nil, errors.New("introspection disabled") } - return introspection.WrapSchema(parsedSchema), nil + return introspection.WrapSchema(ec.Schema()), nil } func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { if ec.DisableIntrospection { return nil, errors.New("introspection disabled") } - return introspection.WrapTypeFromDef(parsedSchema, parsedSchema.Types[name]), nil + return introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil } diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/import.go b/vendor/github.com/99designs/gqlgen/codegen/templates/import.go index 00a82ea5e..c26bdeab7 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/templates/import.go +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/import.go @@ -1,6 +1,7 @@ package templates import ( + "errors" "fmt" "go/types" "strconv" @@ -45,7 +46,7 @@ func (s *Imports) Reserve(path string, aliases ...string) (string, error) { panic("empty ambient import") } - // if we are referencing our own package we dont need an import + // if we are referencing our own package we don't need an import if code.ImportPathForDir(s.destDir) == path { return "", nil } @@ -62,11 +63,11 @@ func (s *Imports) Reserve(path string, aliases ...string) (string, error) { if existing.Alias == alias { return "", nil } - return "", fmt.Errorf("ambient import already exists") + return "", errors.New("ambient import already exists") } if alias := s.findByAlias(alias); alias != nil { - return "", fmt.Errorf("ambient import collides on an alias") + return "", errors.New("ambient import collides on an alias") } s.imports = append(s.imports, &Import{ @@ -85,7 +86,7 @@ func (s *Imports) Lookup(path string) string { path = code.NormalizeVendor(path) - // if we are referencing our own package we dont need an import + // if we are referencing our own package we don't need an import if code.ImportPathForDir(s.destDir) == path { return "" } diff --git a/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go b/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go index 159df77c9..f5d6c639a 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go +++ b/vendor/github.com/99designs/gqlgen/codegen/templates/templates.go @@ -2,6 +2,7 @@ package templates import ( "bytes" + "errors" "fmt" "go/types" "io/fs" @@ -18,7 +19,6 @@ import ( "unicode" "github.com/99designs/gqlgen/internal/code" - "github.com/99designs/gqlgen/internal/imports" ) @@ -53,7 +53,7 @@ type Options struct { // FileNotice is notice written below the package line FileNotice string // Data will be passed to the template execution. - Data interface{} + Data any Funcs template.FuncMap // Packages cache, you can find me on config.Config @@ -72,7 +72,7 @@ var ( // files inside the directory where you wrote the plugin. func Render(cfg Options) error { if CurrentImports != nil { - panic(fmt.Errorf("recursive or concurrent call to RenderToFile detected")) + panic(errors.New("recursive or concurrent call to RenderToFile detected")) } CurrentImports = &Imports{packages: cfg.Packages, destDir: filepath.Dir(cfg.Filename)} @@ -88,26 +88,31 @@ func Render(cfg Options) error { } roots := make([]string, 0, len(t.Templates())) - for _, template := range t.Templates() { + for _, templ := range t.Templates() { // templates that end with _.gotpl are special files we don't want to include - if strings.HasSuffix(template.Name(), "_.gotpl") || + if strings.HasSuffix(templ.Name(), "_.gotpl") || // filter out templates added with {{ template xxx }} syntax inside the template file - !strings.HasSuffix(template.Name(), ".gotpl") { + !strings.HasSuffix(templ.Name(), ".gotpl") { continue } - roots = append(roots, template.Name()) + roots = append(roots, templ.Name()) } // then execute all the important looking ones in order, adding them to the same file - sort.Slice(roots, func(i, j int) bool { + sort.SliceStable(roots, func(i, j int) bool { // important files go first - if strings.HasSuffix(roots[i], "!.gotpl") { + if strings.HasSuffix(roots[i], "!.gotpl") && + !strings.HasSuffix(roots[j], "!.gotpl") { return true } - if strings.HasSuffix(roots[j], "!.gotpl") { + if strings.HasSuffix(roots[j], "!.gotpl") && + !strings.HasSuffix(roots[i], "!.gotpl") { return false } + // files that have identical names are sorted dependent on input order + // so we rely on SliceStable here to ensure deterministic results + // to avoid test failures return roots[i] < roots[j] }) @@ -172,7 +177,7 @@ func parseTemplates(cfg Options, t *template.Template) (*template.Template, erro fileSystem = cfg.TemplateFS } else { // load path relative to calling source file - _, callerFile, _, _ := runtime.Caller(1) + _, callerFile, _, _ := runtime.Caller(2) rootDir := filepath.Dir(callerFile) fileSystem = os.DirFS(rootDir) } @@ -185,7 +190,7 @@ func parseTemplates(cfg Options, t *template.Template) (*template.Template, erro return t, nil } -func center(width int, pad string, s string) string { +func center(width int, pad, s string) string { if len(s)+2 > width { return s } @@ -202,10 +207,13 @@ func Funcs() template.FuncMap { "rawQuote": rawQuote, "dump": Dump, "ref": ref, + "obj": obj, "ts": TypeIdentifier, "call": Call, + "dict": dict, "prefixLines": prefixLines, "notNil": notNil, + "strSplit": StrSplit, "reserveImport": CurrentImports.Reserve, "lookupImport": CurrentImports.Lookup, "go": ToGo, @@ -215,7 +223,7 @@ func Funcs() template.FuncMap { "add": func(a, b int) int { return a + b }, - "render": func(filename string, tpldata interface{}) (*bytes.Buffer, error) { + "render": func(filename string, tpldata any) (*bytes.Buffer, error) { return render(resolveName(filename, 0), tpldata) }, } @@ -245,45 +253,31 @@ func isDelimiter(c rune) bool { } func ref(p types.Type) string { - return CurrentImports.LookupType(p) + typeString := CurrentImports.LookupType(p) + // TODO(steve): figure out why this is needed + // otherwise inconsistent sometimes + // see https://github.com/99designs/gqlgen/issues/3414#issuecomment-2822856422 + if typeString == "interface{}" { + return "any" + } + if typeString == "map[string]interface{}" { + return "map[string]any" + } + // assuming that some other container interface{} type + // like []interface{} or something needs coercion to any + if strings.Contains(typeString, "interface{}") { + return strings.ReplaceAll(typeString, "interface{}", "any") + } + return typeString } -var pkgReplacer = strings.NewReplacer( - "/", "ᚋ", - ".", "ᚗ", - "-", "ᚑ", - "~", "א", -) - -func TypeIdentifier(t types.Type) string { - res := "" - for { - switch it := t.(type) { - case *types.Pointer: - t.Underlying() - res += "ᚖ" - t = it.Elem() - case *types.Slice: - res += "ᚕ" - t = it.Elem() - case *types.Named: - res += pkgReplacer.Replace(it.Obj().Pkg().Path()) - res += "ᚐ" - res += it.Obj().Name() - return res - case *types.Basic: - res += it.Name() - return res - case *types.Map: - res += "map" - return res - case *types.Interface: - res += "interface" - return res - default: - panic(fmt.Errorf("unexpected type %T", it)) - } +func obj(obj types.Object) string { + pkg := CurrentImports.Lookup(obj.Pkg().Path()) + if pkg != "" { + pkg += "." } + + return pkg + obj.Name() } func Call(p *types.Func) string { @@ -301,6 +295,21 @@ func Call(p *types.Func) string { return pkg + p.Name() } +func dict(values ...any) (map[string]any, error) { + if len(values)%2 != 0 { + return nil, errors.New("invalid dict call: arguments must be key-value pairs") + } + m := make(map[string]any, len(values)/2) + for i := 0; i < len(values); i += 2 { + key, ok := values[i].(string) + if !ok { + return nil, errors.New("dict keys must be strings") + } + m[key] = values[i+1] + } + return m, nil +} + func resetModelNames() { modelNamesMu.Lock() defer modelNamesMu.Unlock() @@ -503,21 +512,40 @@ func wordWalker(str string, f func(*wordInfo)) { } i++ + initialisms := GetInitialisms() // [w,i) is a word. word := string(runes[w:i]) - if !eow && commonInitialisms[word] && !unicode.IsLower(runes[i]) { + if !eow && initialisms[word] && !unicode.IsLower(runes[i]) { // through // split IDFoo → ID, Foo // but URLs → URLs } else if !eow { - if commonInitialisms[word] { + if initialisms[word] { hasCommonInitial = true } continue } matchCommonInitial := false - if commonInitialisms[strings.ToUpper(word)] { + upperWord := strings.ToUpper(word) + if initialisms[upperWord] { + // If the uppercase word (string(runes[w:i]) is "ID" or "IP" + // AND + // the word is the first two characters of the current word + // AND + // that is not the end of the word + // AND + // the length of the remaining string is greater than 3 + // AND + // the third rune is an uppercase one + // THEN + // do NOT count this as an initialism. + switch upperWord { + case "ID", "IP": + if remainingRunes := runes[w:]; word == string(remainingRunes[:2]) && !eow && len(remainingRunes) > 3 && unicode.IsUpper(remainingRunes[3]) { + continue + } + } hasCommonInitial = true matchCommonInitial = true } @@ -573,62 +601,11 @@ func sanitizeKeywords(name string) string { return name } -// commonInitialisms is a set of common initialisms. -// Only add entries that are highly unlikely to be non-initialisms. -// For instance, "ID" is fine (Freudian code is rare), but "AND" is not. -var commonInitialisms = map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "CSV": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTP": true, - "HTTPS": true, - "ICMP": true, - "ID": true, - "IP": true, - "JSON": true, - "KVK": true, - "LHS": true, - "PDF": true, - "PGP": true, - "QPS": true, - "QR": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "SVG": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "URI": true, - "URL": true, - "UTF8": true, - "UUID": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, -} - func rawQuote(s string) string { return "`" + strings.ReplaceAll(s, "`", "`+\"`\"+`") + "`" } -func notNil(field string, data interface{}) bool { +func notNil(field string, data any) bool { v := reflect.ValueOf(data) if v.Kind() == reflect.Ptr { @@ -642,12 +619,16 @@ func notNil(field string, data interface{}) bool { return val.IsValid() && !val.IsNil() } -func Dump(val interface{}) string { +func StrSplit(s, sep string) []string { + return strings.Split(s, sep) +} + +func Dump(val any) string { switch val := val.(type) { case int: return strconv.Itoa(val) case int64: - return fmt.Sprintf("%d", val) + return strconv.FormatInt(val, 10) case float64: return fmt.Sprintf("%f", val) case string: @@ -656,15 +637,15 @@ func Dump(val interface{}) string { return strconv.FormatBool(val) case nil: return "nil" - case []interface{}: + case []any: var parts []string for _, part := range val { parts = append(parts, Dump(part)) } - return "[]interface{}{" + strings.Join(parts, ",") + "}" - case map[string]interface{}: + return "[]any{" + strings.Join(parts, ",") + "}" + case map[string]any: buf := bytes.Buffer{} - buf.WriteString("map[string]interface{}{") + buf.WriteString("map[string]any{") var keys []string for key := range val { keys = append(keys, key) @@ -702,7 +683,7 @@ func resolveName(name string, skip int) string { return filepath.Join(filepath.Dir(callerFile), name) } -func render(filename string, tpldata interface{}) (*bytes.Buffer, error) { +func render(filename string, tpldata any) (*bytes.Buffer, error) { t := template.New("").Funcs(Funcs()) b, err := os.ReadFile(filename) @@ -738,3 +719,99 @@ func write(filename string, b []byte, packages *code.Packages) error { return nil } + +var pkgReplacer = strings.NewReplacer( + "/", "ᚋ", + ".", "ᚗ", + "-", "ᚑ", + "~", "א", +) + +func TypeIdentifier(t types.Type) string { + res := "" + for { + switch it := code.Unalias(t).(type) { + case *types.Pointer: + t.Underlying() + res += "ᚖ" + t = it.Elem() + case *types.Slice: + res += "ᚕ" + t = it.Elem() + case *types.Named: + res += pkgReplacer.Replace(it.Obj().Pkg().Path()) + res += "ᚐ" + res += it.Obj().Name() + return res + case *types.Basic: + res += it.Name() + return res + case *types.Map: + res += "map" + return res + case *types.Interface: + res += "interface" + return res + default: + panic(fmt.Errorf("unexpected type %T", it)) + } + } +} + +// CommonInitialisms is a set of common initialisms. +// Only add entries that are highly unlikely to be non-initialisms. +// For instance, "ID" is fine (Freudian code is rare), but "AND" is not. +var CommonInitialisms = map[string]bool{ + "ACL": true, + "API": true, + "ASCII": true, + "CPU": true, + "CSS": true, + "CSV": true, + "DNS": true, + "EOF": true, + "GUID": true, + "HTML": true, + "HTTP": true, + "HTTPS": true, + "ICMP": true, + "ID": true, + "IP": true, + "JSON": true, + "KVK": true, + "LHS": true, + "PDF": true, + "PGP": true, + "QPS": true, + "QR": true, + "RAM": true, + "RHS": true, + "RPC": true, + "SLA": true, + "SMTP": true, + "SQL": true, + "SSH": true, + "SVG": true, + "TCP": true, + "TLS": true, + "TTL": true, + "UDP": true, + "UI": true, + "UID": true, + "URI": true, + "URL": true, + "UTF8": true, + "UUID": true, + "VM": true, + "XML": true, + "XMPP": true, + "XSRF": true, + "XSS": true, + "AWS": true, + "GCP": true, +} + +// GetInitialisms returns the initialisms to capitalize in Go names. If unchanged, default initialisms will be returned +var GetInitialisms = func() map[string]bool { + return CommonInitialisms +} diff --git a/vendor/github.com/99designs/gqlgen/codegen/type.go b/vendor/github.com/99designs/gqlgen/codegen/type.go index 20b09dc97..dcd9d2910 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/type.go +++ b/vendor/github.com/99designs/gqlgen/codegen/type.go @@ -26,7 +26,7 @@ func processType(ret map[string]*config.TypeReference, ref *config.TypeReference } ret[key] = ref - if ref.IsSlice() || ref.IsPtrToSlice() || ref.IsPtrToPtr() { + if ref.IsSlice() || ref.IsPtrToSlice() || ref.IsPtrToPtr() || ref.IsPtrToIntf() { processType(ret, ref.Elem()) } } diff --git a/vendor/github.com/99designs/gqlgen/codegen/type.gotpl b/vendor/github.com/99designs/gqlgen/codegen/type.gotpl index d5c391958..dd0e2a7ba 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/type.gotpl +++ b/vendor/github.com/99designs/gqlgen/codegen/type.gotpl @@ -1,22 +1,33 @@ +{{ $useFunctionSyntaxForExecutionContext := .Config.UseFunctionSyntaxForExecutionContext }} {{- range $type := .ReferencedTypes }} {{ with $type.UnmarshalFunc }} - func (ec *executionContext) {{ . }}(ctx context.Context, v interface{}) ({{ $type.GO | ref }}, error) { + {{ if $useFunctionSyntaxForExecutionContext -}} + func {{ . }}(ctx context.Context, ec *executionContext, v any) ({{ $type.GO | ref }}, error) { + {{- else -}} + func (ec *executionContext) {{ . }}(ctx context.Context, v any) ({{ $type.GO | ref }}, error) { + {{- end -}} {{- if and $type.IsNilable (not $type.GQL.NonNull) (not $type.IsPtrToPtr) }} if v == nil { return nil, nil } {{- end }} - {{- if $type.IsPtrToSlice }} + {{- if or $type.IsPtrToSlice $type.IsPtrToIntf }} + {{ if $useFunctionSyntaxForExecutionContext -}} + res, err := {{ $type.Elem.UnmarshalFunc }}(ctx, ec, v) + {{- else -}} res, err := ec.{{ $type.Elem.UnmarshalFunc }}(ctx, v) + {{- end }} return &res, graphql.ErrorOnPath(ctx, err) {{- else if $type.IsSlice }} - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } + var vSlice []any + vSlice = graphql.CoerceList(v) var err error res := make([]{{$type.GO.Elem | ref}}, len(vSlice)) for i := range vSlice { ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + {{ if $useFunctionSyntaxForExecutionContext -}} + res[i], err = {{ $type.Elem.UnmarshalFunc }}(ctx, ec, vSlice[i]) + {{- else -}} res[i], err = ec.{{ $type.Elem.UnmarshalFunc }}(ctx, vSlice[i]) + {{- end }} if err != nil { return nil, err } @@ -25,7 +36,11 @@ {{- else if and $type.IsPtrToPtr (not $type.Unmarshaler) (not $type.IsMarshaler) }} var pres {{ $type.Elem.GO | ref }} if v != nil { + {{ if $useFunctionSyntaxForExecutionContext -}} + res, err := {{ $type.Elem.UnmarshalFunc }}(ctx, ec, v) + {{- else -}} res, err := ec.{{ $type.Elem.UnmarshalFunc }}(ctx, v) + {{- end }} if err != nil { return nil, graphql.ErrorOnPath(ctx, err) } @@ -34,7 +49,14 @@ return &pres, nil {{- else }} {{- if $type.Unmarshaler }} - {{- if $type.CastType }} + {{- if $type.HasEnumValues }} + tmp, err := {{ $type.Unmarshaler | call }}(v) + {{ if $useFunctionSyntaxForExecutionContext -}} + res := {{ $type.UnmarshalFuncFunctionSyntax }}[tmp] + {{- else -}} + res := {{ $type.UnmarshalFunc }}[tmp] + {{- end -}} + {{- else if $type.CastType }} {{- if $type.IsContext }} tmp, err := {{ $type.Unmarshaler | call }}(ctx, v) {{- else }} @@ -59,8 +81,6 @@ {{- else}} return res, graphql.ErrorOnPath(ctx, err) {{- end }} - {{- else if eq ($type.GO | ref) "map[string]interface{}" }} - return v.(map[string]interface{}), nil {{- else if $type.IsMarshaler }} {{- if and $type.IsNilable $type.Elem }} var res = new({{ $type.Elem.GO | ref }}) @@ -72,12 +92,18 @@ {{- else }} err := res.UnmarshalGQL(v) {{- end }} - return res, graphql.ErrorOnPath(ctx, err) + return res, graphql.ErrorOnPath(ctx, err) {{- else }} + {{ if $useFunctionSyntaxForExecutionContext -}} + res, err := unmarshalInput{{ $type.GQL.Name }}(ctx, ec, v) + {{- else -}} res, err := ec.unmarshalInput{{ $type.GQL.Name }}(ctx, v) - {{- if $type.IsNilable }} + {{- end }} + {{- if and $type.IsNilable (not $type.IsMap) (not $type.PointersInUnmarshalInput) }} return &res, graphql.ErrorOnPath(ctx, err) - {{- else}} + {{- else if and (not $type.IsNilable) $type.PointersInUnmarshalInput }} + return *res, graphql.ErrorOnPath(ctx, err) + {{- else }} return res, graphql.ErrorOnPath(ctx, err) {{- end }} {{- end }} @@ -86,9 +112,17 @@ {{- end }} {{ with $type.MarshalFunc }} + {{ if $useFunctionSyntaxForExecutionContext -}} + func {{ . }}(ctx context.Context, ec *executionContext, sel ast.SelectionSet, v {{ $type.GO | ref }}) graphql.Marshaler { + {{- else -}} func (ec *executionContext) {{ . }}(ctx context.Context, sel ast.SelectionSet, v {{ $type.GO | ref }}) graphql.Marshaler { - {{- if $type.IsPtrToSlice }} + {{- end -}} + {{- if or $type.IsPtrToSlice $type.IsPtrToIntf }} + {{ if $useFunctionSyntaxForExecutionContext -}} + return {{ $type.Elem.MarshalFunc }}(ctx, ec, sel, *v) + {{- else -}} return ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, *v) + {{- end }} {{- else if $type.IsSlice }} {{- if not $type.GQL.NonNull }} if v == nil { @@ -98,6 +132,9 @@ ret := make(graphql.Array, len(v)) {{- if not $type.IsScalar }} var wg sync.WaitGroup + {{- if gt $.Config.Exec.WorkerLimit 0 }} + sm := semaphore.NewWeighted({{ $.Config.Exec.WorkerLimit }}) + {{- end }} isLen1 := len(v) == 1 if !isLen1 { wg.Add(len(v)) @@ -112,24 +149,49 @@ } ctx := graphql.WithFieldContext(ctx, fc) f := func(i int) { + {{- if not $.Config.OmitPanicHandler }} defer func() { if r := recover(); r != nil { ec.Error(ctx, ec.Recover(ctx, r)) ret = nil } }() + {{- end }} if !isLen1 { - defer wg.Done() + {{- if gt $.Config.Exec.WorkerLimit 0 }} + defer func(){ + sm.Release(1) + wg.Done() + }() + {{- else }} + defer wg.Done() + {{- end }} } + {{ if $useFunctionSyntaxForExecutionContext -}} + ret[i] = {{ $type.Elem.MarshalFunc }}(ctx, ec, sel, v[i]) + {{- else -}} ret[i] = ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, v[i]) + {{- end }} } if isLen1 { f(i) } else { - go f(i) + {{- if gt $.Config.Exec.WorkerLimit 0 }} + if err := sm.Acquire(ctx, 1); err != nil { + ec.Error(ctx, ctx.Err()) + } else { + go f(i) + } + {{- else }} + go f(i) + {{- end }} } {{ else }} + {{ if $useFunctionSyntaxForExecutionContext -}} + ret[i] = {{ $type.Elem.MarshalFunc }}(ctx, ec, sel, v[i]) + {{- else -}} ret[i] = ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, v[i]) + {{- end }} {{- end }} } {{ if not $type.IsScalar }} wg.Wait() {{ end }} @@ -145,7 +207,11 @@ if v == nil { return graphql.Null } + {{ if $useFunctionSyntaxForExecutionContext -}} + return {{ $type.Elem.MarshalFunc }}(ctx, ec, sel, *v) + {{- else -}} return ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, *v) + {{- end }} {{- else }} {{- if $type.IsNilable }} if v == nil { @@ -164,13 +230,26 @@ return v {{- end }} {{- else if $type.Marshaler }} + _ = sel + {{- if and (not $type.GQL.NonNull) (not $type.IsContext) }} + _ = ctx + {{- end }} {{- $v := "v" }} {{- if and $type.IsTargetNilable (not $type.IsNilable) }} {{- $v = "&v" }} {{- else if and (not $type.IsTargetNilable) $type.IsNilable }} {{- $v = "*v" }} {{- end }} - res := {{ $type.Marshaler | call }}({{- if $type.CastType }}{{ $type.CastType | ref }}({{ $v }}){{else}}{{ $v }}{{- end }}) + {{- if $type.HasEnumValues }} + {{- if $useFunctionSyntaxForExecutionContext -}} + {{- $v = printf "%v[%v]" $type.MarshalFuncFunctionSyntax $v }} + {{- else -}} + {{- $v = printf "%v[%v]" $type.MarshalFunc $v }} + {{- end -}} + {{- else if $type.CastType }} + {{- $v = printf "%v(%v)" ($type.CastType | ref) $v}} + {{- end }} + res := {{ $type.Marshaler | call }}({{ $v }}) {{- if $type.GQL.NonNull }} if res == graphql.Null { if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { @@ -183,10 +262,56 @@ {{- else }} return res {{- end }} + {{- else if $type.IsRoot }} + {{- if eq $type.Definition.Name "Subscription" }} + {{ if $useFunctionSyntaxForExecutionContext -}} + res := _{{$type.Definition.Name}}(ctx, ec, sel) + {{- else -}} + res := ec._{{$type.Definition.Name}}(ctx, sel) + {{- end }} + return res(ctx) + {{- else }} + {{ if $useFunctionSyntaxForExecutionContext -}} + return _{{$type.Definition.Name}}(ctx, ec, sel) + {{- else -}} + return ec._{{$type.Definition.Name}}(ctx, sel) + {{- end }} + {{- end }} {{- else }} + {{ if $useFunctionSyntaxForExecutionContext -}} + return _{{$type.Definition.Name}}(ctx, ec, sel, {{ if not $type.IsNilable}}&{{end}} v) + {{- else -}} return ec._{{$type.Definition.Name}}(ctx, sel, {{ if not $type.IsNilable}}&{{end}} v) + {{- end }} {{- end }} {{- end }} } {{- end }} + + {{- if and $type.HasEnumValues (not $type.IsSlice) }} + {{- $enum := $type.GO }} + {{- if $type.IsNilable }} + {{- $enum = $type.GO.Elem }} + {{- end }} + var ( + {{ if $useFunctionSyntaxForExecutionContext -}} + {{ $type.UnmarshalFuncFunctionSyntax }} = map[string]{{ $enum | ref }}{ + {{- else -}} + {{ $type.UnmarshalFunc }} = map[string]{{ $enum | ref }}{ + {{- end -}} + {{- range $value := $type.EnumValues }} + "{{ $value.Definition.Name }}": {{ $value.Object | obj }}, + {{- end }} + } + {{ if $useFunctionSyntaxForExecutionContext -}} + {{ $type.MarshalFuncFunctionSyntax }} = map[{{ $enum | ref }}]string{ + {{- else -}} + {{ $type.MarshalFunc }} = map[{{ $enum | ref }}]string{ + {{- end -}} + {{- range $value := $type.EnumValues }} + {{ $value.Object | obj }}: "{{ $value.Definition.Name }}", + {{- end }} + } + ) + {{- end }} {{- end }} diff --git a/vendor/github.com/99designs/gqlgen/codegen/util.go b/vendor/github.com/99designs/gqlgen/codegen/util.go index fa2ceed3d..f3b2d5f9e 100644 --- a/vendor/github.com/99designs/gqlgen/codegen/util.go +++ b/vendor/github.com/99designs/gqlgen/codegen/util.go @@ -12,6 +12,7 @@ func findGoNamedType(def types.Type) (*types.Named, error) { } namedType, ok := def.(*types.Named) + //nolint:staticcheck // yes, it is bad to end in newline here if !ok { return nil, fmt.Errorf("expected %s to be a named type, instead found %T\n", def.String(), def) } @@ -41,6 +42,7 @@ func findGoInterface(def types.Type) (*types.Interface, error) { func equalFieldName(source, target string) bool { source = strings.ReplaceAll(source, "_", "") + source = strings.ReplaceAll(source, ",omitempty", "") target = strings.ReplaceAll(target, "_", "") return strings.EqualFold(source, target) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/any.go b/vendor/github.com/99designs/gqlgen/graphql/any.go index 6ea8bf2ea..be600b2f4 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/any.go +++ b/vendor/github.com/99designs/gqlgen/graphql/any.go @@ -5,7 +5,7 @@ import ( "io" ) -func MarshalAny(v interface{}) Marshaler { +func MarshalAny(v any) Marshaler { return WriterFunc(func(w io.Writer) { err := json.NewEncoder(w).Encode(v) if err != nil { @@ -14,6 +14,6 @@ func MarshalAny(v interface{}) Marshaler { }) } -func UnmarshalAny(v interface{}) (interface{}, error) { +func UnmarshalAny(v any) (any, error) { return v, nil } diff --git a/vendor/github.com/99designs/gqlgen/graphql/args.go b/vendor/github.com/99designs/gqlgen/graphql/args.go new file mode 100644 index 000000000..0638da37d --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/graphql/args.go @@ -0,0 +1,42 @@ +package graphql + +import ( + "context" +) + +// ProcessArgField Parses argument value without Execution Context +// This function is called from generated code +func ProcessArgField[T any]( + ctx context.Context, + rawArgs map[string]any, + fieldName string, + valueMapperFn func(ctx context.Context, value any) (T, error), +) (T, error) { + value, exists := rawArgs[fieldName] + if !exists { + var zeroVal T + return zeroVal, nil + } + + ctx = WithPathContext(ctx, NewPathWithField(fieldName)) + return valueMapperFn(ctx, value) +} + +// ProcessArgFieldWithEC Parses argument value with Execution Context +// This function is called from generated code +func ProcessArgFieldWithEC[T, EC any]( + ctx context.Context, + ec EC, + rawArgs map[string]any, + fieldName string, + valueMapperFn func(ctx context.Context, ec EC, value any) (T, error), +) (T, error) { + value, exists := rawArgs[fieldName] + if !exists { + var zeroVal T + return zeroVal, nil + } + + ctx = WithPathContext(ctx, NewPathWithField(fieldName)) + return valueMapperFn(ctx, ec, value) +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/bool.go b/vendor/github.com/99designs/gqlgen/graphql/bool.go index f435e0c09..d9797a38e 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/bool.go +++ b/vendor/github.com/99designs/gqlgen/graphql/bool.go @@ -3,24 +3,25 @@ package graphql import ( "fmt" "io" + "strconv" "strings" ) func MarshalBoolean(b bool) Marshaler { - if b { - return WriterFunc(func(w io.Writer) { w.Write(trueLit) }) - } - return WriterFunc(func(w io.Writer) { w.Write(falseLit) }) + str := strconv.FormatBool(b) + return WriterFunc(func(w io.Writer) { w.Write([]byte(str)) }) } -func UnmarshalBoolean(v interface{}) (bool, error) { +func UnmarshalBoolean(v any) (bool, error) { switch v := v.(type) { case string: - return strings.ToLower(v) == "true", nil + return strings.EqualFold(v, "true"), nil case int: return v != 0, nil case bool: return v, nil + case nil: + return false, nil default: return false, fmt.Errorf("%T is not a bool", v) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/cache.go b/vendor/github.com/99designs/gqlgen/graphql/cache.go index fe86ca350..836d98682 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/cache.go +++ b/vendor/github.com/99designs/gqlgen/graphql/cache.go @@ -3,27 +3,33 @@ package graphql import "context" // Cache is a shared store for APQ and query AST caching -type Cache interface { +type Cache[T any] interface { // Get looks up a key's value from the cache. - Get(ctx context.Context, key string) (value interface{}, ok bool) + Get(ctx context.Context, key string) (value T, ok bool) // Add adds a value to the cache. - Add(ctx context.Context, key string, value interface{}) + Add(ctx context.Context, key string, value T) } // MapCache is the simplest implementation of a cache, because it can not evict it should only be used in tests -type MapCache map[string]interface{} +type MapCache[T any] map[string]T // Get looks up a key's value from the cache. -func (m MapCache) Get(ctx context.Context, key string) (value interface{}, ok bool) { +func (m MapCache[T]) Get(_ context.Context, key string) (value T, ok bool) { v, ok := m[key] return v, ok } // Add adds a value to the cache. -func (m MapCache) Add(ctx context.Context, key string, value interface{}) { m[key] = value } +func (m MapCache[T]) Add(_ context.Context, key string, value T) { m[key] = value } -type NoCache struct{} +type NoCache[T any] struct{} -func (n NoCache) Get(ctx context.Context, key string) (value interface{}, ok bool) { return nil, false } -func (n NoCache) Add(ctx context.Context, key string, value interface{}) {} +var _ Cache[string] = (*NoCache[string])(nil) + +func (n NoCache[T]) Get(_ context.Context, _ string) (value T, ok bool) { + var val T + return val, false +} + +func (n NoCache[T]) Add(_ context.Context, _ string, _ T) {} diff --git a/vendor/github.com/99designs/gqlgen/graphql/coercion.go b/vendor/github.com/99designs/gqlgen/graphql/coercion.go index d3d3c18b2..92ab87477 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/coercion.go +++ b/vendor/github.com/99designs/gqlgen/graphql/coercion.go @@ -5,52 +5,54 @@ import ( ) // CoerceList applies coercion from a single value to a list. -func CoerceList(v interface{}) []interface{} { - var vSlice []interface{} - if v != nil { - switch v := v.(type) { - case []interface{}: - // already a slice no coercion required - vSlice = v - case []string: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []json.Number: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []bool: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []map[string]interface{}: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []float64: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []float32: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []int: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []int32: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - case []int64: - if len(v) > 0 { - vSlice = []interface{}{v[0]} - } - default: - vSlice = []interface{}{v} +func CoerceList(v any) []any { + var vSlice []any + if v == nil { + return vSlice + } + + switch v := v.(type) { + case []any: + // already a slice no coercion required + vSlice = v + case []string: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []json.Number: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []bool: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []map[string]any: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []float64: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []float32: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []int: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []int32: + if len(v) > 0 { + vSlice = []any{v[0]} + } + case []int64: + if len(v) > 0 { + vSlice = []any{v[0]} } + default: + vSlice = []any{v} } return vSlice } diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_field.go b/vendor/github.com/99designs/gqlgen/graphql/context_field.go index 1f9a6e88d..dbb8d9e9b 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/context_field.go +++ b/vendor/github.com/99designs/gqlgen/graphql/context_field.go @@ -19,13 +19,13 @@ type FieldContext struct { // The name of the type this field belongs to Object string // These are the args after processing, they can be mutated in middleware to change what the resolver will get. - Args map[string]interface{} + Args map[string]any // The raw field Field CollectedField // The index of array in path. Index *int // The result object of resolver - Result interface{} + Result any // IsMethod indicates if the resolver is a method IsMethod bool // IsResolver indicates if the field has a user-specified resolver @@ -34,16 +34,16 @@ type FieldContext struct { // Note that, the returned child FieldContext represents the context as it was // before the execution of the field resolver. For example: // - // srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (interface{}, error) { + // srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (any, error) { // fc := graphql.GetFieldContext(ctx) - // op := graphql.GetOperationContext(ctx) + // opCtx := graphql.GetOperationContext(ctx) // collected := graphql.CollectFields(opCtx, fc.Field.Selections, []string{"User"}) // // child, err := fc.Child(ctx, collected[0]) // if err != nil { // return nil, err // } - // fmt.Println("child context %q with args: %v", child.Field.Name, child.Args) + // fmt.Printf("child context %q with args: %v\n", child.Field.Name, child.Args) // // return next(ctx) // }) @@ -98,7 +98,7 @@ func WithFieldContext(ctx context.Context, rc *FieldContext) context.Context { return context.WithValue(ctx, resolverCtx, rc) } -func equalPath(a ast.Path, b ast.Path) bool { +func equalPath(a, b ast.Path) bool { if len(a) != len(b) { return false } diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_operation.go b/vendor/github.com/99designs/gqlgen/graphql/context_operation.go index 0518ecc6b..696ac1e76 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/context_operation.go +++ b/vendor/github.com/99designs/gqlgen/graphql/context_operation.go @@ -6,6 +6,7 @@ import ( "net/http" "github.com/vektah/gqlparser/v2/ast" + "github.com/vektah/gqlparser/v2/gqlerror" ) // Deprecated: Please update all references to OperationContext instead @@ -13,9 +14,10 @@ type RequestContext = OperationContext type OperationContext struct { RawQuery string - Variables map[string]interface{} + Variables map[string]any OperationName string Doc *ast.QueryDocument + Extensions map[string]any Headers http.Header Operation *ast.OperationDefinition @@ -35,7 +37,7 @@ func (c *OperationContext) Validate(ctx context.Context) error { return errors.New("field 'RawQuery' is required") } if c.Variables == nil { - c.Variables = make(map[string]interface{}) + c.Variables = make(map[string]any) } if c.ResolverMiddleware == nil { return errors.New("field 'ResolverMiddleware' is required") @@ -64,19 +66,19 @@ func GetOperationContext(ctx context.Context) *OperationContext { panic("missing operation context") } -func WithOperationContext(ctx context.Context, rc *OperationContext) context.Context { - return context.WithValue(ctx, operationCtx, rc) +func WithOperationContext(ctx context.Context, opCtx *OperationContext) context.Context { + return context.WithValue(ctx, operationCtx, opCtx) } // HasOperationContext checks if the given context is part of an ongoing operation // // Some errors can happen outside of an operation, eg json unmarshal errors. func HasOperationContext(ctx context.Context) bool { - _, ok := ctx.Value(operationCtx).(*OperationContext) - return ok + val, ok := ctx.Value(operationCtx).(*OperationContext) + return ok && val != nil } -// This is just a convenient wrapper method for CollectFields +// CollectFieldsCtx is just a convenient wrapper method for CollectFields. func CollectFieldsCtx(ctx context.Context, satisfies []string) []CollectedField { resctx := GetFieldContext(ctx) return CollectFields(GetOperationContext(ctx), resctx.Field.Selections, satisfies) @@ -102,16 +104,23 @@ Next: // Errorf sends an error string to the client, passing it through the formatter. // Deprecated: use graphql.AddErrorf(ctx, err) instead -func (c *OperationContext) Errorf(ctx context.Context, format string, args ...interface{}) { +func (c *OperationContext) Errorf(ctx context.Context, format string, args ...any) { AddErrorf(ctx, format, args...) } -// Error sends an error to the client, passing it through the formatter. -// Deprecated: use graphql.AddError(ctx, err) instead +// Error add error or multiple errors (if underlaying type is gqlerror.List) into the stack. +// Then it will be sends to the client, passing it through the formatter. func (c *OperationContext) Error(ctx context.Context, err error) { + if errList, ok := err.(gqlerror.List); ok { + for _, e := range errList { + AddError(ctx, e) + } + return + } + AddError(ctx, err) } -func (c *OperationContext) Recover(ctx context.Context, err interface{}) error { +func (c *OperationContext) Recover(ctx context.Context, err any) error { return ErrorOnPath(ctx, c.RecoverFunc(ctx, err)) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_path.go b/vendor/github.com/99designs/gqlgen/graphql/context_path.go index a46ed83dd..bdb53e7a7 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/context_path.go +++ b/vendor/github.com/99designs/gqlgen/graphql/context_path.go @@ -34,7 +34,6 @@ func (fic *PathContext) Path() ast.Path { if fic.ParentField != nil { fieldPath := fic.ParentField.Path() return append(fieldPath, path...) - } return path diff --git a/vendor/github.com/99designs/gqlgen/graphql/context_response.go b/vendor/github.com/99designs/gqlgen/graphql/context_response.go index c128fdb49..340a4048c 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/context_response.go +++ b/vendor/github.com/99designs/gqlgen/graphql/context_response.go @@ -15,7 +15,7 @@ type responseContext struct { errors gqlerror.List errorsMu sync.Mutex - extensions map[string]interface{} + extensions map[string]any extensionsMu sync.Mutex } @@ -36,13 +36,24 @@ func WithResponseContext(ctx context.Context, presenterFunc ErrorPresenterFunc, }) } +func WithFreshResponseContext(ctx context.Context) context.Context { + e := getResponseContext(ctx) + return context.WithValue(ctx, resultCtx, &responseContext{ + errorPresenter: e.errorPresenter, + recover: e.recover, + }) +} + // AddErrorf writes a formatted error to the client, first passing it through the error presenter. -func AddErrorf(ctx context.Context, format string, args ...interface{}) { +func AddErrorf(ctx context.Context, format string, args ...any) { AddError(ctx, fmt.Errorf(format, args...)) } // AddError sends an error to the client, first passing it through the error presenter. func AddError(ctx context.Context, err error) { + if err == nil { + return + } c := getResponseContext(ctx) presentedError := c.errorPresenter(ctx, ErrorOnPath(ctx, err)) @@ -52,7 +63,7 @@ func AddError(ctx context.Context, err error) { c.errors = append(c.errors, presentedError) } -func Recover(ctx context.Context, err interface{}) (userMessage error) { +func Recover(ctx context.Context, err any) (userMessage error) { c := getResponseContext(ctx) return ErrorOnPath(ctx, c.recover(ctx, err)) } @@ -117,13 +128,13 @@ func GetErrors(ctx context.Context) gqlerror.List { } // RegisterExtension allows you to add a new extension into the graphql response -func RegisterExtension(ctx context.Context, key string, value interface{}) { +func RegisterExtension(ctx context.Context, key string, value any) { c := getResponseContext(ctx) c.extensionsMu.Lock() defer c.extensionsMu.Unlock() if c.extensions == nil { - c.extensions = make(map[string]interface{}) + c.extensions = make(map[string]any) } if _, ok := c.extensions[key]; ok { @@ -134,16 +145,16 @@ func RegisterExtension(ctx context.Context, key string, value interface{}) { } // GetExtensions returns any extensions registered in the current result context -func GetExtensions(ctx context.Context) map[string]interface{} { +func GetExtensions(ctx context.Context) map[string]any { ext := getResponseContext(ctx).extensions if ext == nil { - return map[string]interface{}{} + return map[string]any{} } return ext } -func GetExtension(ctx context.Context, name string) interface{} { +func GetExtension(ctx context.Context, name string) any { ext := getResponseContext(ctx).extensions if ext == nil { return nil diff --git a/vendor/github.com/99designs/gqlgen/graphql/deferred.go b/vendor/github.com/99designs/gqlgen/graphql/deferred.go new file mode 100644 index 000000000..1aeb48c18 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/graphql/deferred.go @@ -0,0 +1,26 @@ +package graphql + +import ( + "context" + + "github.com/vektah/gqlparser/v2/ast" + "github.com/vektah/gqlparser/v2/gqlerror" +) + +type Deferrable struct { + Label string +} + +type DeferredGroup struct { + Path ast.Path + Label string + FieldSet *FieldSet + Context context.Context +} + +type DeferredResult struct { + Path ast.Path + Label string + Result Marshaler + Errors gqlerror.List +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/duration.go b/vendor/github.com/99designs/gqlgen/graphql/duration.go new file mode 100644 index 000000000..be84b5a4a --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/graphql/duration.go @@ -0,0 +1,51 @@ +package graphql + +import ( + "errors" + "time" + + dur "github.com/sosodev/duration" +) + +// UnmarshalDuration returns the duration from a string in ISO8601 format +// PnDTnHnMn.nS with days considered to be exactly 24 hours. +// See https://en.wikipedia.org/wiki/ISO_8601#Durations +// P - Period +// D - D is the +// T - T is the time designator that precedes the time components +// H - H is the hour designator that follows the value for the number of hours. +// M - M is the minute designator that follows the value for the number of minutes. +// S - S is the second designator that follows the value for the number of seconds. +// "PT20.345S" -- parses as "20.345 seconds" +// "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds) +// "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds) +// "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds) +func UnmarshalDuration(v any) (time.Duration, error) { + input, ok := v.(string) + if !ok { + return 0, errors.New("input must be a string") + } + + d2, err := dur.Parse(input) + if err != nil { + return 0, err + } + return d2.ToTimeDuration(), nil +} + +// MarshalDuration returns the duration in ISO8601 format +// PnDTnHnMn.nS with days considered to be exactly 24 hours. +// See https://en.wikipedia.org/wiki/ISO_8601#Durations +// P - Period +// D - D is the +// T - T is the time designator that precedes the time components +// H - H is the hour designator that follows the value for the number of hours. +// M - M is the minute designator that follows the value for the number of minutes. +// S - S is the second designator that follows the value for the number of seconds. +// "PT20.345S" -- parses as "20.345 seconds" +// "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds) +// "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds) +// "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds) +func MarshalDuration(d time.Duration) Marshaler { + return MarshalString(dur.Format(d)) +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/errcode/codes.go b/vendor/github.com/99designs/gqlgen/graphql/errcode/codes.go index 854b206f4..58ca7cbee 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/errcode/codes.go +++ b/vendor/github.com/99designs/gqlgen/graphql/errcode/codes.go @@ -40,7 +40,7 @@ func Set(err error, value string) { } if gqlErr.Extensions == nil { - gqlErr.Extensions = map[string]interface{}{} + gqlErr.Extensions = map[string]any{} } gqlErr.Extensions["code"] = value diff --git a/vendor/github.com/99designs/gqlgen/graphql/error.go b/vendor/github.com/99designs/gqlgen/graphql/error.go index f816bef6b..bfcecd9a8 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/error.go +++ b/vendor/github.com/99designs/gqlgen/graphql/error.go @@ -10,6 +10,9 @@ import ( type ErrorPresenterFunc func(ctx context.Context, err error) *gqlerror.Error func DefaultErrorPresenter(ctx context.Context, err error) *gqlerror.Error { + if err == nil { + return nil + } var gqlErr *gqlerror.Error if errors.As(err, &gqlErr) { return gqlErr diff --git a/vendor/github.com/99designs/gqlgen/graphql/executable_schema.go b/vendor/github.com/99designs/gqlgen/graphql/executable_schema.go index 618916228..4870e4fc8 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/executable_schema.go +++ b/vendor/github.com/99designs/gqlgen/graphql/executable_schema.go @@ -12,13 +12,12 @@ import ( type ExecutableSchema interface { Schema() *ast.Schema - Complexity(typeName, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) + Complexity(ctx context.Context, typeName, fieldName string, childComplexity int, args map[string]any) (int, bool) Exec(ctx context.Context) ResponseHandler } // CollectFields returns the set of fields from an ast.SelectionSet where all collected fields satisfy at least one of the GraphQL types -// passed through satisfies. Providing an empty or nil slice for satisfies will return collect all fields regardless of fragment -// type conditions. +// passed through satisfies. Providing an empty slice for satisfies will collect all fields regardless of fragment type conditions. func CollectFields(reqCtx *OperationContext, selSet ast.SelectionSet, satisfies []string) []CollectedField { return collectFields(reqCtx, selSet, satisfies, map[string]bool{}) } @@ -42,22 +41,31 @@ func collectFields(reqCtx *OperationContext, selSet ast.SelectionSet, satisfies if !shouldIncludeNode(sel.Directives, reqCtx.Variables) { continue } - if len(satisfies) > 0 && !instanceOf(sel.TypeCondition, satisfies) { + if !doesFragmentConditionMatch(sel.TypeCondition, satisfies) { continue } + + shouldDefer, label := deferrable(sel.Directives, reqCtx.Variables) for _, childField := range collectFields(reqCtx, sel.SelectionSet, satisfies, visited) { - f := getOrCreateAndAppendField(&groupedFields, childField.Name, childField.Alias, childField.ObjectDefinition, func() CollectedField { return childField }) + f := getOrCreateAndAppendField( + &groupedFields, childField.Name, childField.Alias, childField.ObjectDefinition, + func() CollectedField { return childField }) f.Selections = append(f.Selections, childField.Selections...) + if shouldDefer { + f.Deferrable = &Deferrable{ + Label: label, + } + } } case *ast.FragmentSpread: - if !shouldIncludeNode(sel.Directives, reqCtx.Variables) { - continue - } fragmentName := sel.Name if _, seen := visited[fragmentName]; seen { continue } + if !shouldIncludeNode(sel.Directives, reqCtx.Variables) { + continue + } visited[fragmentName] = true fragment := reqCtx.Doc.Fragments.ForName(fragmentName) @@ -65,14 +73,19 @@ func collectFields(reqCtx *OperationContext, selSet ast.SelectionSet, satisfies // should never happen, validator has already run panic(fmt.Errorf("missing fragment %s", fragmentName)) } - - if len(satisfies) > 0 && !instanceOf(fragment.TypeCondition, satisfies) { + if !doesFragmentConditionMatch(fragment.TypeCondition, satisfies) { continue } + shouldDefer, label := deferrable(sel.Directives, reqCtx.Variables) for _, childField := range collectFields(reqCtx, fragment.SelectionSet, satisfies, visited) { - f := getOrCreateAndAppendField(&groupedFields, childField.Name, childField.Alias, childField.ObjectDefinition, func() CollectedField { return childField }) + f := getOrCreateAndAppendField(&groupedFields, + childField.Name, childField.Alias, childField.ObjectDefinition, + func() CollectedField { return childField }) f.Selections = append(f.Selections, childField.Selections...) + if shouldDefer { + f.Deferrable = &Deferrable{Label: label} + } } default: @@ -87,18 +100,34 @@ type CollectedField struct { *ast.Field Selections ast.SelectionSet + Deferrable *Deferrable } -func instanceOf(val string, satisfies []string) bool { - for _, s := range satisfies { - if val == s { +func doesFragmentConditionMatch(typeCondition string, satisfies []string) bool { + // To allow simplified "collect all" types behavior, pass an empty list of types + // that the type condition must satisfy: we will apply the fragment regardless of + // type condition. + if len(satisfies) == 0 { + return true + } + + // When the type condition is not set (... { field }) we will apply the fragment + // to any satisfying types. + if typeCondition == "" { + return true + } + + // To handle abstract types we pass in a list of all known types that the current + // type will satisfy. + for _, satisfyingType := range satisfies { + if typeCondition == satisfyingType { return true } } return false } -func getOrCreateAndAppendField(c *[]CollectedField, name string, alias string, objectDefinition *ast.Definition, creator func() CollectedField) *CollectedField { +func getOrCreateAndAppendField(c *[]CollectedField, name, alias string, objectDefinition *ast.Definition, creator func() CollectedField) *CollectedField { for i, cf := range *c { if cf.Name == name && cf.Alias == alias { if cf.ObjectDefinition == objectDefinition { @@ -132,7 +161,7 @@ func getOrCreateAndAppendField(c *[]CollectedField, name string, alias string, o return &(*c)[len(*c)-1] } -func shouldIncludeNode(directives ast.DirectiveList, variables map[string]interface{}) bool { +func shouldIncludeNode(directives ast.DirectiveList, variables map[string]any) bool { if len(directives) == 0 { return true } @@ -150,7 +179,33 @@ func shouldIncludeNode(directives ast.DirectiveList, variables map[string]interf return !skip && include } -func resolveIfArgument(d *ast.Directive, variables map[string]interface{}) bool { +func deferrable(directives ast.DirectiveList, variables map[string]any) (shouldDefer bool, label string) { + d := directives.ForName("defer") + if d == nil { + return false, "" + } + + shouldDefer = true + + for _, arg := range d.Arguments { + switch arg.Name { + case "if": + if value, err := arg.Value.Value(variables); err == nil { + shouldDefer, _ = value.(bool) + } + case "label": + if value, err := arg.Value.Value(variables); err == nil { + label, _ = value.(string) + } + default: + panic(fmt.Sprintf("defer: argument '%s' not supported", arg.Name)) + } + } + + return shouldDefer, label +} + +func resolveIfArgument(d *ast.Directive, variables map[string]any) bool { arg := d.Arguments.ForName("if") if arg == nil { panic(fmt.Sprintf("%s: argument 'if' not defined", d.Name)) diff --git a/vendor/github.com/99designs/gqlgen/graphql/executable_schema_mock.go b/vendor/github.com/99designs/gqlgen/graphql/executable_schema_mock.go index 5d7433162..90bdc9b3b 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/executable_schema_mock.go +++ b/vendor/github.com/99designs/gqlgen/graphql/executable_schema_mock.go @@ -15,28 +15,28 @@ var _ ExecutableSchema = &ExecutableSchemaMock{} // ExecutableSchemaMock is a mock implementation of ExecutableSchema. // -// func TestSomethingThatUsesExecutableSchema(t *testing.T) { +// func TestSomethingThatUsesExecutableSchema(t *testing.T) { // -// // make and configure a mocked ExecutableSchema -// mockedExecutableSchema := &ExecutableSchemaMock{ -// ComplexityFunc: func(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) { -// panic("mock out the Complexity method") -// }, -// ExecFunc: func(ctx context.Context) ResponseHandler { -// panic("mock out the Exec method") -// }, -// SchemaFunc: func() *ast.Schema { -// panic("mock out the Schema method") -// }, -// } +// // make and configure a mocked ExecutableSchema +// mockedExecutableSchema := &ExecutableSchemaMock{ +// ComplexityFunc: func(ctx context.Context, typeName string, fieldName string, childComplexity int, args map[string]any) (int, bool) { +// panic("mock out the Complexity method") +// }, +// ExecFunc: func(ctx context.Context) ResponseHandler { +// panic("mock out the Exec method") +// }, +// SchemaFunc: func() *ast.Schema { +// panic("mock out the Schema method") +// }, +// } // -// // use mockedExecutableSchema in code that requires ExecutableSchema -// // and then make assertions. +// // use mockedExecutableSchema in code that requires ExecutableSchema +// // and then make assertions. // -// } +// } type ExecutableSchemaMock struct { // ComplexityFunc mocks the Complexity method. - ComplexityFunc func(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) + ComplexityFunc func(ctx context.Context, typeName string, fieldName string, childComplexity int, args map[string]any) (int, bool) // ExecFunc mocks the Exec method. ExecFunc func(ctx context.Context) ResponseHandler @@ -48,6 +48,8 @@ type ExecutableSchemaMock struct { calls struct { // Complexity holds details about calls to the Complexity method. Complexity []struct { + // Ctx is the ctx argument value. + Ctx context.Context // TypeName is the typeName argument value. TypeName string // FieldName is the fieldName argument value. @@ -55,7 +57,7 @@ type ExecutableSchemaMock struct { // ChildComplexity is the childComplexity argument value. ChildComplexity int // Args is the args argument value. - Args map[string]interface{} + Args map[string]any } // Exec holds details about calls to the Exec method. Exec []struct { @@ -72,16 +74,18 @@ type ExecutableSchemaMock struct { } // Complexity calls ComplexityFunc. -func (mock *ExecutableSchemaMock) Complexity(typeName string, fieldName string, childComplexity int, args map[string]interface{}) (int, bool) { +func (mock *ExecutableSchemaMock) Complexity(ctx context.Context, typeName string, fieldName string, childComplexity int, args map[string]any) (int, bool) { if mock.ComplexityFunc == nil { panic("ExecutableSchemaMock.ComplexityFunc: method is nil but ExecutableSchema.Complexity was just called") } callInfo := struct { + Ctx context.Context TypeName string FieldName string ChildComplexity int - Args map[string]interface{} + Args map[string]any }{ + Ctx: ctx, TypeName: typeName, FieldName: fieldName, ChildComplexity: childComplexity, @@ -90,23 +94,26 @@ func (mock *ExecutableSchemaMock) Complexity(typeName string, fieldName string, mock.lockComplexity.Lock() mock.calls.Complexity = append(mock.calls.Complexity, callInfo) mock.lockComplexity.Unlock() - return mock.ComplexityFunc(typeName, fieldName, childComplexity, args) + return mock.ComplexityFunc(ctx, typeName, fieldName, childComplexity, args) } // ComplexityCalls gets all the calls that were made to Complexity. // Check the length with: -// len(mockedExecutableSchema.ComplexityCalls()) +// +// len(mockedExecutableSchema.ComplexityCalls()) func (mock *ExecutableSchemaMock) ComplexityCalls() []struct { + Ctx context.Context TypeName string FieldName string ChildComplexity int - Args map[string]interface{} + Args map[string]any } { var calls []struct { + Ctx context.Context TypeName string FieldName string ChildComplexity int - Args map[string]interface{} + Args map[string]any } mock.lockComplexity.RLock() calls = mock.calls.Complexity @@ -132,7 +139,8 @@ func (mock *ExecutableSchemaMock) Exec(ctx context.Context) ResponseHandler { // ExecCalls gets all the calls that were made to Exec. // Check the length with: -// len(mockedExecutableSchema.ExecCalls()) +// +// len(mockedExecutableSchema.ExecCalls()) func (mock *ExecutableSchemaMock) ExecCalls() []struct { Ctx context.Context } { @@ -160,7 +168,8 @@ func (mock *ExecutableSchemaMock) Schema() *ast.Schema { // SchemaCalls gets all the calls that were made to Schema. // Check the length with: -// len(mockedExecutableSchema.SchemaCalls()) +// +// len(mockedExecutableSchema.SchemaCalls()) func (mock *ExecutableSchemaMock) SchemaCalls() []struct { } { var calls []struct { diff --git a/vendor/github.com/99designs/gqlgen/graphql/executor/executor.go b/vendor/github.com/99designs/gqlgen/graphql/executor/executor.go index c46a007b9..40f0b3257 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/executor/executor.go +++ b/vendor/github.com/99designs/gqlgen/graphql/executor/executor.go @@ -3,14 +3,18 @@ package executor import ( "context" - "github.com/99designs/gqlgen/graphql" - "github.com/99designs/gqlgen/graphql/errcode" "github.com/vektah/gqlparser/v2/ast" "github.com/vektah/gqlparser/v2/gqlerror" "github.com/vektah/gqlparser/v2/parser" "github.com/vektah/gqlparser/v2/validator" + "github.com/vektah/gqlparser/v2/validator/rules" + + "github.com/99designs/gqlgen/graphql" + "github.com/99designs/gqlgen/graphql/errcode" ) +const parserTokenNoLimit = 0 + // Executor executes graphql queries against a schema. type Executor struct { es graphql.ExecutableSchema @@ -19,7 +23,11 @@ type Executor struct { errorPresenter graphql.ErrorPresenterFunc recoverFunc graphql.RecoverFunc - queryCache graphql.Cache + queryCache graphql.Cache[*ast.QueryDocument] + + parserTokenLimit int + disableSuggestion bool + defaultRulesFn func() *rules.Rules } var _ graphql.GraphExecutor = &Executor{} @@ -28,20 +36,26 @@ var _ graphql.GraphExecutor = &Executor{} // recovery callbacks, and no query cache or extensions. func New(es graphql.ExecutableSchema) *Executor { e := &Executor{ - es: es, - errorPresenter: graphql.DefaultErrorPresenter, - recoverFunc: graphql.DefaultRecover, - queryCache: graphql.NoCache{}, - ext: processExtensions(nil), + es: es, + errorPresenter: graphql.DefaultErrorPresenter, + recoverFunc: graphql.DefaultRecover, + queryCache: graphql.NoCache[*ast.QueryDocument]{}, + ext: processExtensions(nil), + parserTokenLimit: parserTokenNoLimit, } return e } +// SetDefaultRulesFn is to customize the Default GraphQL Validation Rules +func (e *Executor) SetDefaultRulesFn(f func() *rules.Rules) { + e.defaultRulesFn = f +} + func (e *Executor) CreateOperationContext( ctx context.Context, params *graphql.RawParams, ) (*graphql.OperationContext, gqlerror.List) { - rc := &graphql.OperationContext{ + opCtx := &graphql.OperationContext{ DisableIntrospection: true, RecoverFunc: e.recoverFunc, ResolverMiddleware: e.ext.fieldMiddleware, @@ -51,57 +65,61 @@ func (e *Executor) CreateOperationContext( OperationStart: graphql.GetStartTime(ctx), }, } - ctx = graphql.WithOperationContext(ctx, rc) + ctx = graphql.WithOperationContext(ctx, opCtx) for _, p := range e.ext.operationParameterMutators { if err := p.MutateOperationParameters(ctx, params); err != nil { - return rc, gqlerror.List{err} + return opCtx, gqlerror.List{err} } } - rc.RawQuery = params.Query - rc.OperationName = params.OperationName - rc.Headers = params.Headers + opCtx.RawQuery = params.Query + opCtx.OperationName = params.OperationName + opCtx.Extensions = params.Extensions + opCtx.Headers = params.Headers var listErr gqlerror.List - rc.Doc, listErr = e.parseQuery(ctx, &rc.Stats, params.Query) + opCtx.Doc, listErr = e.parseQuery(ctx, &opCtx.Stats, params.Query) if len(listErr) != 0 { - return rc, listErr + return opCtx, listErr } - rc.Operation = rc.Doc.Operations.ForName(params.OperationName) - if rc.Operation == nil { + opCtx.Operation = opCtx.Doc.Operations.ForName(params.OperationName) + if opCtx.Operation == nil { err := gqlerror.Errorf("operation %s not found", params.OperationName) errcode.Set(err, errcode.ValidationFailed) - return rc, gqlerror.List{err} + return opCtx, gqlerror.List{err} } var err error - rc.Variables, err = validator.VariableValues(e.es.Schema(), rc.Operation, params.Variables) - + opCtx.Variables, err = validator.VariableValues( + e.es.Schema(), + opCtx.Operation, + params.Variables, + ) if err != nil { gqlErr, ok := err.(*gqlerror.Error) if ok { errcode.Set(gqlErr, errcode.ValidationFailed) - return rc, gqlerror.List{gqlErr} + return opCtx, gqlerror.List{gqlErr} } } - rc.Stats.Validation.End = graphql.Now() + opCtx.Stats.Validation.End = graphql.Now() for _, p := range e.ext.operationContextMutators { - if err := p.MutateOperationContext(ctx, rc); err != nil { - return rc, gqlerror.List{err} + if err := p.MutateOperationContext(ctx, opCtx); err != nil { + return opCtx, gqlerror.List{err} } } - return rc, nil + return opCtx, nil } func (e *Executor) DispatchOperation( ctx context.Context, - rc *graphql.OperationContext, + opCtx *graphql.OperationContext, ) (graphql.ResponseHandler, context.Context) { - ctx = graphql.WithOperationContext(ctx, rc) + ctx = graphql.WithOperationContext(ctx, opCtx) var innerCtx context.Context res := e.ext.operationMiddleware(ctx, func(ctx context.Context) graphql.ResponseHandler { @@ -152,11 +170,11 @@ func (e *Executor) DispatchError(ctx context.Context, list gqlerror.List) *graph return resp } -func (e *Executor) PresentRecoveredError(ctx context.Context, err interface{}) error { +func (e *Executor) PresentRecoveredError(ctx context.Context, err any) error { return e.errorPresenter(ctx, e.recoverFunc(ctx, err)) } -func (e *Executor) SetQueryCache(cache graphql.Cache) { +func (e *Executor) SetQueryCache(cache graphql.Cache[*ast.QueryDocument]) { e.queryCache = cache } @@ -168,6 +186,14 @@ func (e *Executor) SetRecoverFunc(f graphql.RecoverFunc) { e.recoverFunc = f } +func (e *Executor) SetParserTokenLimit(limit int) { + e.parserTokenLimit = limit +} + +func (e *Executor) SetDisableSuggestion(value bool) { + e.disableSuggestion = value +} + // parseQuery decodes the incoming query and validates it, pulling from cache if present. // // NOTE: This should NOT look at variables, they will change per request. It should only parse and @@ -185,10 +211,10 @@ func (e *Executor) parseQuery( stats.Parsing.End = now stats.Validation.Start = now - return doc.(*ast.QueryDocument), nil + return doc, nil } - doc, err := parser.ParseQuery(&ast.Source{Input: query}) + doc, err := parser.ParseQueryWithTokenLimit(&ast.Source{Input: query}, e.parserTokenLimit) if err != nil { gqlErr, ok := err.(*gqlerror.Error) if ok { @@ -200,14 +226,34 @@ func (e *Executor) parseQuery( stats.Validation.Start = graphql.Now() - if len(doc.Operations) == 0 { + if doc == nil || len(doc.Operations) == 0 { err = gqlerror.Errorf("no operation provided") gqlErr, _ := err.(*gqlerror.Error) errcode.Set(err, errcode.ValidationFailed) return nil, gqlerror.List{gqlErr} } - listErr := validator.Validate(e.es.Schema(), doc) + var currentRules *rules.Rules + if e.defaultRulesFn == nil { + currentRules = rules.NewDefaultRules() + } else { + currentRules = e.defaultRulesFn() + } + // Customise rules as required + // TODO(steve): consider currentRules.RemoveRule(rules.MaxIntrospectionDepth.Name) + + // swap out the FieldsOnCorrectType rule with one that doesn't provide suggestions + if e.disableSuggestion { + currentRules.RemoveRule("FieldsOnCorrectType") + rule := rules.FieldsOnCorrectTypeRuleWithoutSuggestions + currentRules.AddRule(rule.Name, rule.RuleFunc) + } else { // or vice versa + currentRules.RemoveRule("FieldsOnCorrectTypeWithoutSuggestions") + rule := rules.FieldsOnCorrectTypeRule + currentRules.AddRule(rule.Name, rule.RuleFunc) + } + + listErr := validator.ValidateWithRules(e.es.Schema(), doc, currentRules) if len(listErr) != 0 { for _, e := range listErr { errcode.Set(e, errcode.ValidationFailed) diff --git a/vendor/github.com/99designs/gqlgen/graphql/executor/extensions.go b/vendor/github.com/99designs/gqlgen/graphql/executor/extensions.go index a8eebf110..758d8e4ec 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/executor/extensions.go +++ b/vendor/github.com/99designs/gqlgen/graphql/executor/extensions.go @@ -2,6 +2,7 @@ package executor import ( "context" + "errors" "fmt" "github.com/99designs/gqlgen/graphql" @@ -68,7 +69,7 @@ func processExtensions(exts []graphql.HandlerExtension) extensions { rootFieldMiddleware: func(ctx context.Context, next graphql.RootResolver) graphql.Marshaler { return next(ctx) }, - fieldMiddleware: func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { + fieldMiddleware: func(ctx context.Context, next graphql.Resolver) (res any, err error) { return next(ctx) }, } @@ -105,8 +106,8 @@ func processExtensions(exts []graphql.HandlerExtension) extensions { if p, ok := p.(graphql.FieldInterceptor); ok { previous := e.fieldMiddleware - e.fieldMiddleware = func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { - return p.InterceptField(ctx, func(ctx context.Context) (res interface{}, err error) { + e.fieldMiddleware = func(ctx context.Context, next graphql.Resolver) (res any, err error) { + return p.InterceptField(ctx, func(ctx context.Context) (res any, err error) { return previous(ctx, next) }) } @@ -134,7 +135,7 @@ func (r aroundOpFunc) ExtensionName() string { func (r aroundOpFunc) Validate(schema graphql.ExecutableSchema) error { if r == nil { - return fmt.Errorf("OperationFunc can not be nil") + return errors.New("OperationFunc can not be nil") } return nil } @@ -151,7 +152,7 @@ func (r aroundRespFunc) ExtensionName() string { func (r aroundRespFunc) Validate(schema graphql.ExecutableSchema) error { if r == nil { - return fmt.Errorf("ResponseFunc can not be nil") + return errors.New("ResponseFunc can not be nil") } return nil } @@ -160,7 +161,7 @@ func (r aroundRespFunc) InterceptResponse(ctx context.Context, next graphql.Resp return r(ctx, next) } -type aroundFieldFunc func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) +type aroundFieldFunc func(ctx context.Context, next graphql.Resolver) (res any, err error) func (f aroundFieldFunc) ExtensionName() string { return "InlineFieldFunc" @@ -168,12 +169,12 @@ func (f aroundFieldFunc) ExtensionName() string { func (f aroundFieldFunc) Validate(schema graphql.ExecutableSchema) error { if f == nil { - return fmt.Errorf("FieldFunc can not be nil") + return errors.New("FieldFunc can not be nil") } return nil } -func (f aroundFieldFunc) InterceptField(ctx context.Context, next graphql.Resolver) (res interface{}, err error) { +func (f aroundFieldFunc) InterceptField(ctx context.Context, next graphql.Resolver) (res any, err error) { return f(ctx, next) } @@ -185,7 +186,7 @@ func (f aroundRootFieldFunc) ExtensionName() string { func (f aroundRootFieldFunc) Validate(schema graphql.ExecutableSchema) error { if f == nil { - return fmt.Errorf("RootFieldFunc can not be nil") + return errors.New("RootFieldFunc can not be nil") } return nil } diff --git a/vendor/github.com/99designs/gqlgen/graphql/fieldset.go b/vendor/github.com/99designs/gqlgen/graphql/fieldset.go index 351e266fd..73c048dc3 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/fieldset.go +++ b/vendor/github.com/99designs/gqlgen/graphql/fieldset.go @@ -1,19 +1,21 @@ package graphql import ( + "context" "io" "sync" ) type FieldSet struct { - fields []CollectedField - Values []Marshaler - delayed []delayedResult + fields []CollectedField + Values []Marshaler + Invalids uint32 + delayed []delayedResult } type delayedResult struct { i int - f func() Marshaler + f func(context.Context) Marshaler } func NewFieldSet(fields []CollectedField) *FieldSet { @@ -23,15 +25,20 @@ func NewFieldSet(fields []CollectedField) *FieldSet { } } -func (m *FieldSet) Concurrently(i int, f func() Marshaler) { +func (m *FieldSet) AddField(field CollectedField) { + m.fields = append(m.fields, field) + m.Values = append(m.Values, nil) +} + +func (m *FieldSet) Concurrently(i int, f func(context.Context) Marshaler) { m.delayed = append(m.delayed, delayedResult{i: i, f: f}) } -func (m *FieldSet) Dispatch() { +func (m *FieldSet) Dispatch(ctx context.Context) { if len(m.delayed) == 1 { // only one concurrent task, no need to spawn a goroutine or deal create waitgroups d := m.delayed[0] - m.Values[d.i] = d.f() + m.Values[d.i] = d.f(ctx) } else if len(m.delayed) > 1 { // more than one concurrent task, use the main goroutine to do one, only spawn goroutines for the others @@ -39,25 +46,30 @@ func (m *FieldSet) Dispatch() { for _, d := range m.delayed[1:] { wg.Add(1) go func(d delayedResult) { - m.Values[d.i] = d.f() - wg.Done() + defer wg.Done() + m.Values[d.i] = d.f(ctx) }(d) } - m.Values[m.delayed[0].i] = m.delayed[0].f() + m.Values[m.delayed[0].i] = m.delayed[0].f(ctx) wg.Wait() } } func (m *FieldSet) MarshalGQL(writer io.Writer) { writer.Write(openBrace) + writtenFields := make(map[string]bool, len(m.fields)) for i, field := range m.fields { + if writtenFields[field.Alias] { + continue + } if i != 0 { writer.Write(comma) } writeQuotedString(writer, field.Alias) writer.Write(colon) m.Values[i].MarshalGQL(writer) + writtenFields[field.Alias] = true } writer.Write(closeBrace) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/float.go b/vendor/github.com/99designs/gqlgen/graphql/float.go index ccb825ddb..b140d5bc7 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/float.go +++ b/vendor/github.com/99designs/gqlgen/graphql/float.go @@ -3,6 +3,7 @@ package graphql import ( "context" "encoding/json" + "errors" "fmt" "io" "math" @@ -11,11 +12,11 @@ import ( func MarshalFloat(f float64) Marshaler { return WriterFunc(func(w io.Writer) { - io.WriteString(w, fmt.Sprintf("%g", f)) + fmt.Fprintf(w, "%g", f) }) } -func UnmarshalFloat(v interface{}) (float64, error) { +func UnmarshalFloat(v any) (float64, error) { switch v := v.(type) { case string: return strconv.ParseFloat(v, 64) @@ -27,6 +28,8 @@ func UnmarshalFloat(v interface{}) (float64, error) { return v, nil case json.Number: return strconv.ParseFloat(string(v), 64) + case nil: + return 0, nil default: return 0, fmt.Errorf("%T is not an float", v) } @@ -35,13 +38,13 @@ func UnmarshalFloat(v interface{}) (float64, error) { func MarshalFloatContext(f float64) ContextMarshaler { return ContextWriterFunc(func(ctx context.Context, w io.Writer) error { if math.IsInf(f, 0) || math.IsNaN(f) { - return fmt.Errorf("cannot marshal infinite no NaN float values") + return errors.New("cannot marshal infinite no NaN float values") } - io.WriteString(w, fmt.Sprintf("%g", f)) + fmt.Fprintf(w, "%g", f) return nil }) } -func UnmarshalFloatContext(ctx context.Context, v interface{}) (float64, error) { +func UnmarshalFloatContext(ctx context.Context, v any) (float64, error) { return UnmarshalFloat(v) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/handler.go b/vendor/github.com/99designs/gqlgen/graphql/handler.go index cd358740c..ab2ed4b64 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/handler.go +++ b/vendor/github.com/99designs/gqlgen/graphql/handler.go @@ -16,25 +16,25 @@ type ( ResponseHandler func(ctx context.Context) *Response ResponseMiddleware func(ctx context.Context, next ResponseHandler) *Response - Resolver func(ctx context.Context) (res interface{}, err error) - FieldMiddleware func(ctx context.Context, next Resolver) (res interface{}, err error) + Resolver func(ctx context.Context) (res any, err error) + FieldMiddleware func(ctx context.Context, next Resolver) (res any, err error) RootResolver func(ctx context.Context) Marshaler RootFieldMiddleware func(ctx context.Context, next RootResolver) Marshaler RawParams struct { - Query string `json:"query"` - OperationName string `json:"operationName"` - Variables map[string]interface{} `json:"variables"` - Extensions map[string]interface{} `json:"extensions"` - Headers http.Header `json:"headers"` + Query string `json:"query"` + OperationName string `json:"operationName"` + Variables map[string]any `json:"variables"` + Extensions map[string]any `json:"extensions"` + Headers http.Header `json:"headers"` ReadTime TraceTiming `json:"-"` } GraphExecutor interface { CreateOperationContext(ctx context.Context, params *RawParams) (*OperationContext, gqlerror.List) - DispatchOperation(ctx context.Context, rc *OperationContext) (ResponseHandler, context.Context) + DispatchOperation(ctx context.Context, opCtx *OperationContext) (ResponseHandler, context.Context) DispatchError(ctx context.Context, list gqlerror.List) *Response } @@ -65,7 +65,7 @@ type ( // OperationContextMutator is called after creating the request context, but before executing the root resolver. OperationContextMutator interface { - MutateOperationContext(ctx context.Context, rc *OperationContext) *gqlerror.Error + MutateOperationContext(ctx context.Context, opCtx *OperationContext) *gqlerror.Error } // OperationInterceptor is called for each incoming query, for basic requests the writer will be invoked once, @@ -86,7 +86,7 @@ type ( // FieldInterceptor called around each field FieldInterceptor interface { - InterceptField(ctx context.Context, next Resolver) (res interface{}, err error) + InterceptField(ctx context.Context, next Resolver) (res any, err error) } // Transport provides support for different wire level encodings of graphql requests, eg Form, Get, Post, Websocket @@ -103,7 +103,7 @@ func (p *RawParams) AddUpload(upload Upload, key, path string) *gqlerror.Error { return gqlerror.Errorf("invalid operations paths for key %s", key) } - var ptr interface{} = p.Variables + var ptr any = p.Variables parts := strings.Split(path, ".") // skip the first part (variables) because we started there @@ -114,15 +114,15 @@ func (p *RawParams) AddUpload(upload Upload, key, path string) *gqlerror.Error { } if index, parseNbrErr := strconv.Atoi(p); parseNbrErr == nil { if last { - ptr.([]interface{})[index] = upload + ptr.([]any)[index] = upload } else { - ptr = ptr.([]interface{})[index] + ptr = ptr.([]any)[index] } } else { if last { - ptr.(map[string]interface{})[p] = upload + ptr.(map[string]any)[p] = upload } else { - ptr = ptr.(map[string]interface{})[p] + ptr = ptr.(map[string]any)[p] } } } diff --git a/vendor/github.com/99designs/gqlgen/graphql/id.go b/vendor/github.com/99designs/gqlgen/graphql/id.go index b24605d1d..2a946dfa7 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/id.go +++ b/vendor/github.com/99designs/gqlgen/graphql/id.go @@ -11,7 +11,7 @@ func MarshalID(s string) Marshaler { return MarshalString(s) } -func UnmarshalID(v interface{}) (string, error) { +func UnmarshalID(v any) (string, error) { switch v := v.(type) { case string: return v, nil @@ -22,13 +22,9 @@ func UnmarshalID(v interface{}) (string, error) { case int64: return strconv.FormatInt(v, 10), nil case float64: - return fmt.Sprintf("%f", v), nil + return strconv.FormatFloat(v, 'f', 6, 64), nil case bool: - if v { - return "true", nil - } else { - return "false", nil - } + return strconv.FormatBool(v), nil case nil: return "null", nil default: @@ -42,7 +38,7 @@ func MarshalIntID(i int) Marshaler { }) } -func UnmarshalIntID(v interface{}) (int, error) { +func UnmarshalIntID(v any) (int, error) { switch v := v.(type) { case string: return strconv.Atoi(v) @@ -56,3 +52,32 @@ func UnmarshalIntID(v interface{}) (int, error) { return 0, fmt.Errorf("%T is not an int", v) } } + +func MarshalUintID(i uint) Marshaler { + return WriterFunc(func(w io.Writer) { + writeQuotedString(w, strconv.FormatUint(uint64(i), 10)) + }) +} + +func UnmarshalUintID(v any) (uint, error) { + switch v := v.(type) { + case string: + result, err := strconv.ParseUint(v, 10, 64) + return uint(result), err + case int: + return uint(v), nil + case int64: + return uint(v), nil + case int32: + return uint(v), nil + case uint32: + return uint(v), nil + case uint64: + return uint(v), nil + case json.Number: + result, err := strconv.ParseUint(string(v), 10, 64) + return uint(result), err + default: + return 0, fmt.Errorf("%T is not an uint", v) + } +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/input.go b/vendor/github.com/99designs/gqlgen/graphql/input.go index 88c3efaa6..681fe0801 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/input.go +++ b/vendor/github.com/99designs/gqlgen/graphql/input.go @@ -10,7 +10,7 @@ const unmarshalInputCtx key = "unmarshal_input_context" // BuildUnmarshalerMap returns a map of unmarshal functions of the ExecutableContext // to use with the WithUnmarshalerMap function. -func BuildUnmarshalerMap(unmarshaler ...interface{}) map[reflect.Type]reflect.Value { +func BuildUnmarshalerMap(unmarshaler ...any) map[reflect.Type]reflect.Value { maps := make(map[reflect.Type]reflect.Value) for _, v := range unmarshaler { ft := reflect.TypeOf(v) @@ -28,7 +28,7 @@ func WithUnmarshalerMap(ctx context.Context, maps map[reflect.Type]reflect.Value } // UnmarshalInputFromContext allows unmarshaling input object from a context. -func UnmarshalInputFromContext(ctx context.Context, raw, v interface{}) error { +func UnmarshalInputFromContext(ctx context.Context, raw, v any) error { m, ok := ctx.Value(unmarshalInputCtx).(map[reflect.Type]reflect.Value) if m == nil || !ok { return errors.New("graphql: the input context is empty") diff --git a/vendor/github.com/99designs/gqlgen/graphql/int.go b/vendor/github.com/99designs/gqlgen/graphql/int.go index 57d0d589b..6e799975a 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/int.go +++ b/vendor/github.com/99designs/gqlgen/graphql/int.go @@ -4,76 +4,157 @@ import ( "encoding/json" "fmt" "io" + "math" + "reflect" "strconv" ) func MarshalInt(i int) Marshaler { return WriterFunc(func(w io.Writer) { - io.WriteString(w, strconv.Itoa(i)) + _, _ = io.WriteString(w, strconv.FormatInt(int64(i), 10)) }) } -func UnmarshalInt(v interface{}) (int, error) { - switch v := v.(type) { - case string: - return strconv.Atoi(v) - case int: - return v, nil - case int64: - return int(v), nil - case json.Number: - return strconv.Atoi(string(v)) - default: - return 0, fmt.Errorf("%T is not an int", v) - } +func UnmarshalInt(v any) (int, error) { + return interfaceToSignedNumber[int](v) } -func MarshalInt64(i int64) Marshaler { +func MarshalInt8(i int8) Marshaler { return WriterFunc(func(w io.Writer) { - io.WriteString(w, strconv.FormatInt(i, 10)) + _, _ = io.WriteString(w, strconv.FormatInt(int64(i), 10)) }) } -func UnmarshalInt64(v interface{}) (int64, error) { - switch v := v.(type) { - case string: - return strconv.ParseInt(v, 10, 64) - case int: - return int64(v), nil - case int64: - return v, nil - case json.Number: - return strconv.ParseInt(string(v), 10, 64) - default: - return 0, fmt.Errorf("%T is not an int", v) - } +func UnmarshalInt8(v any) (int8, error) { + return interfaceToSignedNumber[int8](v) +} + +func MarshalInt16(i int16) Marshaler { + return WriterFunc(func(w io.Writer) { + _, _ = io.WriteString(w, strconv.FormatInt(int64(i), 10)) + }) +} + +func UnmarshalInt16(v any) (int16, error) { + return interfaceToSignedNumber[int16](v) } func MarshalInt32(i int32) Marshaler { return WriterFunc(func(w io.Writer) { - io.WriteString(w, strconv.FormatInt(int64(i), 10)) + _, _ = io.WriteString(w, strconv.FormatInt(int64(i), 10)) }) } -func UnmarshalInt32(v interface{}) (int32, error) { +func UnmarshalInt32(v any) (int32, error) { + return interfaceToSignedNumber[int32](v) +} + +func MarshalInt64(i int64) Marshaler { + return WriterFunc(func(w io.Writer) { + _, _ = io.WriteString(w, strconv.FormatInt(i, 10)) + }) +} + +func UnmarshalInt64(v any) (int64, error) { + return interfaceToSignedNumber[int64](v) +} + +type number interface { + int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 +} + +func interfaceToSignedNumber[N number](v any) (N, error) { switch v := v.(type) { + case int, int8, int16, int32, int64: + return safeCastSignedNumber[N](reflect.ValueOf(v).Int()) case string: - iv, err := strconv.ParseInt(v, 10, 32) + iv, err := strconv.ParseInt(v, 10, 64) if err != nil { return 0, err } - return int32(iv), nil - case int: - return int32(v), nil - case int64: - return int32(v), nil + return safeCastSignedNumber[N](iv) case json.Number: - iv, err := strconv.ParseInt(string(v), 10, 32) + iv, err := strconv.ParseInt(string(v), 10, 64) if err != nil { return 0, err } - return int32(iv), nil + return safeCastSignedNumber[N](iv) + case nil: + return 0, nil default: - return 0, fmt.Errorf("%T is not an int", v) + return 0, fmt.Errorf("%T is not an %T", v, N(0)) } } + +// IntegerError is an error type that allows users to identify errors associated +// with receiving an integer value that is not valid for the specific integer +// type designated by the API. IntegerErrors designate otherwise valid unsigned +// or signed 64-bit integers that are invalid in a specific context: they do not +// designate integers that overflow 64-bit versions of the current type. +type IntegerError struct { + Message string +} + +func (e IntegerError) Error() string { + return e.Message +} + +type NumberOverflowError struct { + Value any + *IntegerError +} + +type maxNumber interface { + int64 | uint64 +} + +func newNumberOverflowError[N maxNumber](i any, bitsize int) *NumberOverflowError { + switch v := i.(type) { + case int64: + return &NumberOverflowError{ + Value: v, + IntegerError: &IntegerError{ + Message: fmt.Sprintf("%d overflows signed %d-bit integer", i, bitsize), + }, + } + default: + return &NumberOverflowError{ + Value: v, + IntegerError: &IntegerError{ + Message: fmt.Sprintf("%d overflows unsigned %d-bit integer", i, bitsize), + }, + } + } +} + +func (e *NumberOverflowError) Unwrap() error { + return e.IntegerError +} + +// safeCastSignedNumber converts an int64 to a number of type N. +func safeCastSignedNumber[N number](val int64) (N, error) { + var zero N + switch any(zero).(type) { + case int8: + if val > math.MaxInt8 || val < math.MinInt8 { + return 0, newNumberOverflowError[int64](val, 8) + } + case int16: + if val > math.MaxInt16 || val < math.MinInt16 { + return 0, newNumberOverflowError[int64](val, 16) + } + case int32: + if val > math.MaxInt32 || val < math.MinInt32 { + return 0, newNumberOverflowError[int64](val, 32) + } + case int: + if strconv.IntSize == 32 && (val > math.MaxInt32 || val < math.MinInt32) { + return 0, newNumberOverflowError[int64](val, 32) + } + case int64: + default: + return 0, fmt.Errorf("invalid type %T", zero) + } + + return N(val), nil +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/introspection/introspection.go b/vendor/github.com/99designs/gqlgen/graphql/introspection/introspection.go index 8482d62a8..14c76c46f 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/introspection/introspection.go +++ b/vendor/github.com/99designs/gqlgen/graphql/introspection/introspection.go @@ -1,7 +1,9 @@ // introspection implements the spec defined in https://github.com/facebook/graphql/blob/master/spec/Section%204%20--%20Introspection.md#schema-introspection package introspection -import "github.com/vektah/gqlparser/v2/ast" +import ( + "github.com/vektah/gqlparser/v2/ast" +) type ( Directive struct { @@ -31,6 +33,7 @@ type ( description string DefaultValue *string Type *Type + deprecation *ast.Directive } ) @@ -74,6 +77,25 @@ func (f *Field) IsDeprecated() bool { } func (f *Field) DeprecationReason() *string { + if f.deprecation == nil || !f.IsDeprecated() { + return nil + } + + reason := f.deprecation.Arguments.ForName("reason") + + if reason == nil { + defaultReason := "No longer supported" + return &defaultReason + } + + return &reason.Value.Raw +} + +func (f *InputValue) IsDeprecated() bool { + return f.deprecation != nil +} + +func (f *InputValue) DeprecationReason() *string { if f.deprecation == nil { return nil } diff --git a/vendor/github.com/99designs/gqlgen/graphql/introspection/schema.go b/vendor/github.com/99designs/gqlgen/graphql/introspection/schema.go index b7b0ad94e..897b1a098 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/introspection/schema.go +++ b/vendor/github.com/99designs/gqlgen/graphql/introspection/schema.go @@ -2,7 +2,6 @@ package introspection import ( "sort" - "strings" "github.com/vektah/gqlparser/v2/ast" ) @@ -22,9 +21,6 @@ func (s *Schema) Types() []Type { typeIndex := map[string]Type{} typeNames := make([]string, 0, len(s.schema.Types)) for _, typ := range s.schema.Types { - if strings.HasPrefix(typ.Name, "__") { - continue - } typeNames = append(typeNames, typ.Name) typeIndex[typ.Name] = *WrapTypeFromDef(s.schema, typ) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/introspection/type.go b/vendor/github.com/99designs/gqlgen/graphql/introspection/type.go index c50733d0d..c4145ba11 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/introspection/type.go +++ b/vendor/github.com/99designs/gqlgen/graphql/introspection/type.go @@ -81,6 +81,7 @@ func (t *Type) Fields(includeDeprecated bool) []Field { Name: arg.Name, description: arg.Description, DefaultValue: defaultValue(arg.DefaultValue), + deprecation: f.Directives.ForName("deprecated"), }) } @@ -107,6 +108,7 @@ func (t *Type) InputFields() []InputValue { description: f.Description, Type: WrapTypeFromType(t.schema, f.Type), DefaultValue: defaultValue(f.DefaultValue), + deprecation: f.Directives.ForName("deprecated"), }) } return res @@ -180,6 +182,9 @@ func (t *Type) OfType() *Type { } func (t *Type) SpecifiedByURL() *string { + if t.def == nil { + return nil + } directive := t.def.Directives.ForName("specifiedBy") if t.def.Kind != ast.Scalar || directive == nil { return nil @@ -189,3 +194,14 @@ func (t *Type) SpecifiedByURL() *string { url := directive.Arguments.ForName("url") return &url.Value.Raw } + +func (t *Type) IsOneOf() bool { + if t.def == nil { + return false + } + directive := t.def.Directives.ForName("oneOf") + if t.def.Kind != ast.InputObject || directive == nil { + return false + } + return true +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/jsonw.go b/vendor/github.com/99designs/gqlgen/graphql/jsonw.go index 54e293f1a..16bb63b73 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/jsonw.go +++ b/vendor/github.com/99designs/gqlgen/graphql/jsonw.go @@ -28,7 +28,7 @@ type Marshaler interface { } type Unmarshaler interface { - UnmarshalGQL(v interface{}) error + UnmarshalGQL(v any) error } type ContextMarshaler interface { @@ -36,7 +36,7 @@ type ContextMarshaler interface { } type ContextUnmarshaler interface { - UnmarshalGQLContext(ctx context.Context, v interface{}) error + UnmarshalGQLContext(ctx context.Context, v any) error } type contextMarshalerAdapter struct { diff --git a/vendor/github.com/99designs/gqlgen/graphql/map.go b/vendor/github.com/99designs/gqlgen/graphql/map.go index 1e91d1d98..2120eef96 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/map.go +++ b/vendor/github.com/99designs/gqlgen/graphql/map.go @@ -6,7 +6,7 @@ import ( "io" ) -func MarshalMap(val map[string]interface{}) Marshaler { +func MarshalMap(val map[string]any) Marshaler { return WriterFunc(func(w io.Writer) { err := json.NewEncoder(w).Encode(val) if err != nil { @@ -15,8 +15,8 @@ func MarshalMap(val map[string]interface{}) Marshaler { }) } -func UnmarshalMap(v interface{}) (map[string]interface{}, error) { - if m, ok := v.(map[string]interface{}); ok { +func UnmarshalMap(v any) (map[string]any, error) { + if m, ok := v.(map[string]any); ok { return m, nil } diff --git a/vendor/github.com/99designs/gqlgen/graphql/omittable.go b/vendor/github.com/99designs/gqlgen/graphql/omittable.go new file mode 100644 index 000000000..58c21c8c5 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/graphql/omittable.go @@ -0,0 +1,152 @@ +package graphql + +import ( + "context" + "encoding/json" + "io" +) + +// Omittable is a wrapper around a value that also stores whether it is set +// or not. +type Omittable[T any] struct { + value T + set bool +} + +var ( + _ json.Marshaler = Omittable[struct{}]{} + _ json.Unmarshaler = (*Omittable[struct{}])(nil) +) + +func OmittableOf[T any](value T) Omittable[T] { + return Omittable[T]{ + value: value, + set: true, + } +} + +func (o Omittable[T]) Value() T { + if !o.set { + var zero T + return zero + } + return o.value +} + +func (o Omittable[T]) ValueOK() (T, bool) { + if !o.set { + var zero T + return zero, false + } + return o.value, true +} + +func (o Omittable[T]) IsSet() bool { + return o.set +} + +// IsZero returns true then json.Marshal will omit this value. +// > The "omitzero" option specifies that the field should be omitted from the encoding if the field has a zero value, according to rules: +// > 1) If the field type has an "IsZero() bool" method, that will be used to determine whether the value is zero. +// > 2) Otherwise, the value is zero if it is the zero value for its type. +// https://pkg.go.dev/encoding/json#Marshal +func (o Omittable[T]) IsZero() bool { + return !o.set +} + +func (o Omittable[T]) MarshalJSON() ([]byte, error) { + var value any = o.value + if !o.set { + var zero T + value = zero + } + + return json.Marshal(value) +} + +func (o *Omittable[T]) UnmarshalJSON(bytes []byte) error { + err := json.Unmarshal(bytes, &o.value) + if err != nil { + return err + } + o.set = true + return nil +} + +func (o Omittable[T]) MarshalGQL(w io.Writer) { + var value any = o.value + if !o.set { + var zero T + value = zero + } + + switch marshaler := value.(type) { + case Marshaler: + marshaler.MarshalGQL(w) + case ContextMarshaler: + _ = marshaler.MarshalGQLContext(context.Background(), w) + default: + b, _ := json.Marshal(value) + w.Write(b) + } +} + +func (o *Omittable[T]) UnmarshalGQL(bytes []byte) error { + switch unmarshaler := any(o.value).(type) { + case Unmarshaler: + if err := unmarshaler.UnmarshalGQL(bytes); err != nil { + return err + } + o.set = true + case ContextUnmarshaler: + if err := unmarshaler.UnmarshalGQLContext(context.Background(), bytes); err != nil { + return err + } + o.set = true + default: + if err := json.Unmarshal(bytes, &o.value); err != nil { + return err + } + o.set = true + } + return nil +} + +func (o Omittable[T]) MarshalGQLContext(ctx context.Context, w io.Writer) { + var value any = o.value + if !o.set { + var zero T + value = zero + } + + switch marshaler := value.(type) { + case ContextMarshaler: + _ = marshaler.MarshalGQLContext(ctx, w) + case Marshaler: + marshaler.MarshalGQL(w) + default: + b, _ := json.Marshal(value) + w.Write(b) + } +} + +func (o *Omittable[T]) UnmarshalGQLContext(ctx context.Context, bytes []byte) error { + switch unmarshaler := any(o.value).(type) { + case ContextUnmarshaler: + if err := unmarshaler.UnmarshalGQLContext(ctx, bytes); err != nil { + return err + } + o.set = true + case Unmarshaler: + if err := unmarshaler.UnmarshalGQL(bytes); err != nil { + return err + } + o.set = true + default: + if err := json.Unmarshal(bytes, &o.value); err != nil { + return err + } + o.set = true + } + return nil +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/recovery.go b/vendor/github.com/99designs/gqlgen/graphql/recovery.go index 9bc0e47e1..4aae69195 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/recovery.go +++ b/vendor/github.com/99designs/gqlgen/graphql/recovery.go @@ -9,9 +9,9 @@ import ( "github.com/vektah/gqlparser/v2/gqlerror" ) -type RecoverFunc func(ctx context.Context, err interface{}) (userMessage error) +type RecoverFunc func(ctx context.Context, err any) (userMessage error) -func DefaultRecover(ctx context.Context, err interface{}) error { +func DefaultRecover(ctx context.Context, err any) error { fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr) debug.PrintStack() diff --git a/vendor/github.com/99designs/gqlgen/graphql/resolve_field.go b/vendor/github.com/99designs/gqlgen/graphql/resolve_field.go new file mode 100644 index 000000000..1f95e461f --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/graphql/resolve_field.go @@ -0,0 +1,137 @@ +package graphql + +import ( + "context" + "io" + + "github.com/vektah/gqlparser/v2/ast" +) + +func ResolveField[T any]( + ctx context.Context, + oc *OperationContext, + field CollectedField, + initializeFieldContext func(ctx context.Context, field CollectedField) (*FieldContext, error), + fieldResolver func(ctx context.Context) (any, error), + middlewareChain func(ctx context.Context, next Resolver) Resolver, + marshal func(ctx context.Context, sel ast.SelectionSet, v T) Marshaler, + recoverFromPanic bool, + nonNull bool, +) Marshaler { + return resolveField[T, Marshaler]( + ctx, + oc, + field, + initializeFieldContext, + fieldResolver, + middlewareChain, + recoverFromPanic, + nonNull, + Null, + func(ctx context.Context, res T) Marshaler { + return marshal(ctx, field.Selections, res) + }, + ) +} + +func ResolveFieldStream[T any]( + ctx context.Context, + oc *OperationContext, + field CollectedField, + initializeFieldContext func(ctx context.Context, field CollectedField) (*FieldContext, error), + fieldResolver func(context.Context) (any, error), + middlewareChain func(ctx context.Context, next Resolver) Resolver, + marshal func(ctx context.Context, sel ast.SelectionSet, v T) Marshaler, + recoverFromPanic bool, + nonNull bool, +) func(context.Context) Marshaler { + return resolveField( + ctx, + oc, + field, + initializeFieldContext, + fieldResolver, + middlewareChain, + recoverFromPanic, + nonNull, + nil, + func(ctx context.Context, res <-chan T) func(context.Context) Marshaler { + return func(ctx context.Context) Marshaler { + select { + case v, ok := <-res: + if !ok { + return nil + } + return WriterFunc(func(w io.Writer) { + w.Write([]byte{'{'}) + MarshalString(field.Alias).MarshalGQL(w) + w.Write([]byte{':'}) + marshal(ctx, field.Selections, v).MarshalGQL(w) + w.Write([]byte{'}'}) + }) + case <-ctx.Done(): + return nil + } + } + }, + ) +} + +func resolveField[T, R any]( + ctx context.Context, + oc *OperationContext, + field CollectedField, + initializeFieldContext func(ctx context.Context, field CollectedField) (*FieldContext, error), + fieldResolver func(ctx context.Context) (any, error), + middlewareChain func(ctx context.Context, next Resolver) Resolver, + recoverFromPanic bool, + nonNull bool, + defaultResult R, + result func(ctx context.Context, res T) R, +) (ret R) { + fc, err := initializeFieldContext(ctx, field) + if err != nil { + return defaultResult + } + ctx = WithFieldContext(ctx, fc) + + if recoverFromPanic { + defer func() { + if r := recover(); r != nil { + oc.Error(ctx, oc.Recover(ctx, r)) + ret = defaultResult + } + }() + } + + next := func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return fieldResolver(rctx) + } + + if middlewareChain != nil { + next = middlewareChain(ctx, next) + } + + resTmp, err := oc.ResolverMiddleware(ctx, next) + if err != nil { + oc.Error(ctx, err) + return defaultResult + } + if resTmp == nil { + if nonNull { + if !HasFieldError(ctx, fc) { + oc.Errorf(ctx, "must not be null") + } + } + return defaultResult + } + res, ok := resTmp.(T) + if !ok { + var t T + oc.Errorf(ctx, `unexpected type %T from middleware/directive chain, should be %T`, resTmp, t) + return defaultResult + } + fc.Result = res + return result(ctx, res) +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/response.go b/vendor/github.com/99designs/gqlgen/graphql/response.go index 0d36049a3..e37b5cfc1 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/response.go +++ b/vendor/github.com/99designs/gqlgen/graphql/response.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" + "github.com/vektah/gqlparser/v2/ast" "github.com/vektah/gqlparser/v2/gqlerror" ) @@ -12,12 +13,15 @@ import ( // https://github.com/facebook/graphql/commit/7b40390d48680b15cb93e02d46ac5eb249689876#diff-757cea6edf0288677a9eea4cfc801d87R107 // and https://github.com/facebook/graphql/pull/384 type Response struct { - Errors gqlerror.List `json:"errors,omitempty"` - Data json.RawMessage `json:"data"` - Extensions map[string]interface{} `json:"extensions,omitempty"` + Errors gqlerror.List `json:"errors,omitempty"` + Data json.RawMessage `json:"data"` + Label string `json:"label,omitempty"` + Path ast.Path `json:"path,omitempty"` + HasNext *bool `json:"hasNext,omitempty"` + Extensions map[string]any `json:"extensions,omitempty"` } -func ErrorResponse(ctx context.Context, messagef string, args ...interface{}) *Response { +func ErrorResponse(ctx context.Context, messagef string, args ...any) *Response { return &Response{ Errors: gqlerror.List{{Message: fmt.Sprintf(messagef, args...)}}, } diff --git a/vendor/github.com/99designs/gqlgen/graphql/stats.go b/vendor/github.com/99designs/gqlgen/graphql/stats.go index a52e143eb..1bf2ad9e6 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/stats.go +++ b/vendor/github.com/99designs/gqlgen/graphql/stats.go @@ -12,9 +12,9 @@ type Stats struct { Parsing TraceTiming Validation TraceTiming - // Stats collected by handler extensions. Dont use directly, the extension should provide a type safe way to + // Stats collected by handler extensions. Don't use directly, the extension should provide a type safe way to // access this. - extension map[string]interface{} + extension map[string]any } type TraceTiming struct { @@ -26,7 +26,7 @@ var ctxTraceStart key = "trace_start" // StartOperationTrace captures the current time and stores it in context. This will eventually be added to request // context but we want to grab it as soon as possible. For transports that can only handle a single graphql query -// per http requests you dont need to call this at all, the server will do it for you. For transports that handle +// per http requests you don't need to call this at all, the server will do it for you. For transports that handle // multiple (eg batching, subscriptions) this should be called before decoding each request. func StartOperationTrace(ctx context.Context) context.Context { return context.WithValue(ctx, ctxTraceStart, Now()) @@ -42,14 +42,14 @@ func GetStartTime(ctx context.Context) time.Time { return t } -func (c *Stats) SetExtension(name string, data interface{}) { +func (c *Stats) SetExtension(name string, data any) { if c.extension == nil { - c.extension = map[string]interface{}{} + c.extension = map[string]any{} } c.extension[name] = data } -func (c *Stats) GetExtension(name string) interface{} { +func (c *Stats) GetExtension(name string) any { if c.extension == nil { return nil } diff --git a/vendor/github.com/99designs/gqlgen/graphql/string.go b/vendor/github.com/99designs/gqlgen/graphql/string.go index 742e50cc3..6622734e3 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/string.go +++ b/vendor/github.com/99designs/gqlgen/graphql/string.go @@ -1,6 +1,7 @@ package graphql import ( + "encoding/json" "fmt" "io" "strconv" @@ -46,7 +47,7 @@ func writeQuotedString(w io.Writer, s string) { io.WriteString(w, `"`) } -func UnmarshalString(v interface{}) (string, error) { +func UnmarshalString(v any) (string, error) { switch v := v.(type) { case string: return v, nil @@ -55,15 +56,13 @@ func UnmarshalString(v interface{}) (string, error) { case int64: return strconv.FormatInt(v, 10), nil case float64: - return fmt.Sprintf("%f", v), nil + return strconv.FormatFloat(v, 'f', -1, 64), nil + case json.Number: + return string(v), nil case bool: - if v { - return "true", nil - } else { - return "false", nil - } + return strconv.FormatBool(v), nil case nil: - return "null", nil + return "", nil default: return "", fmt.Errorf("%T is not a string", v) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/time.go b/vendor/github.com/99designs/gqlgen/graphql/time.go index ef3d17da3..a5fe90301 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/time.go +++ b/vendor/github.com/99designs/gqlgen/graphql/time.go @@ -17,7 +17,7 @@ func MarshalTime(t time.Time) Marshaler { }) } -func UnmarshalTime(v interface{}) (time.Time, error) { +func UnmarshalTime(v any) (time.Time, error) { if tmpStr, ok := v.(string); ok { return time.Parse(time.RFC3339Nano, tmpStr) } diff --git a/vendor/github.com/99designs/gqlgen/graphql/uint.go b/vendor/github.com/99designs/gqlgen/graphql/uint.go index 9349c2f4d..8a6c1c756 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/uint.go +++ b/vendor/github.com/99designs/gqlgen/graphql/uint.go @@ -2,8 +2,11 @@ package graphql import ( "encoding/json" + "errors" "fmt" "io" + "math" + "reflect" "strconv" ) @@ -13,42 +16,28 @@ func MarshalUint(i uint) Marshaler { }) } -func UnmarshalUint(v interface{}) (uint, error) { - switch v := v.(type) { - case string: - u64, err := strconv.ParseUint(v, 10, 64) - return uint(u64), err - case int: - return uint(v), nil - case int64: - return uint(v), nil - case json.Number: - u64, err := strconv.ParseUint(string(v), 10, 64) - return uint(u64), err - default: - return 0, fmt.Errorf("%T is not an uint", v) - } +func UnmarshalUint(v any) (uint, error) { + return interfaceToUnsignedNumber[uint](v) } -func MarshalUint64(i uint64) Marshaler { +func MarshalUint8(i uint8) Marshaler { return WriterFunc(func(w io.Writer) { - _, _ = io.WriteString(w, strconv.FormatUint(i, 10)) + _, _ = io.WriteString(w, strconv.FormatUint(uint64(i), 10)) }) } -func UnmarshalUint64(v interface{}) (uint64, error) { - switch v := v.(type) { - case string: - return strconv.ParseUint(v, 10, 64) - case int: - return uint64(v), nil - case int64: - return uint64(v), nil - case json.Number: - return strconv.ParseUint(string(v), 10, 64) - default: - return 0, fmt.Errorf("%T is not an uint", v) - } +func UnmarshalUint8(v any) (uint8, error) { + return interfaceToUnsignedNumber[uint8](v) +} + +func MarshalUint16(i uint16) Marshaler { + return WriterFunc(func(w io.Writer) { + _, _ = io.WriteString(w, strconv.FormatUint(uint64(i), 10)) + }) +} + +func UnmarshalUint16(v any) (uint16, error) { + return interfaceToUnsignedNumber[uint16](v) } func MarshalUint32(i uint32) Marshaler { @@ -57,25 +46,105 @@ func MarshalUint32(i uint32) Marshaler { }) } -func UnmarshalUint32(v interface{}) (uint32, error) { +func UnmarshalUint32(v any) (uint32, error) { + return interfaceToUnsignedNumber[uint32](v) +} + +func MarshalUint64(i uint64) Marshaler { + return WriterFunc(func(w io.Writer) { + _, _ = io.WriteString(w, strconv.FormatUint(i, 10)) + }) +} + +func UnmarshalUint64(v any) (uint64, error) { + return interfaceToUnsignedNumber[uint64](v) +} + +func interfaceToUnsignedNumber[N number](v any) (N, error) { switch v := v.(type) { + case int, int64: + if reflect.ValueOf(v).Int() < 0 { + return 0, newUintSignError(strconv.FormatInt(reflect.ValueOf(v).Int(), 10)) + } + return safeCastUnsignedNumber[N](uint64(reflect.ValueOf(v).Int())) + case uint, uint8, uint16, uint32, uint64: + return safeCastUnsignedNumber[N](reflect.ValueOf(v).Uint()) case string: - iv, err := strconv.ParseInt(v, 10, 32) + uv, err := strconv.ParseUint(v, 10, 64) if err != nil { + var strconvErr *strconv.NumError + if errors.As(err, &strconvErr) && isSignedInteger(v) { + return 0, newUintSignError(v) + } return 0, err } - return uint32(iv), nil - case int: - return uint32(v), nil - case int64: - return uint32(v), nil + return safeCastUnsignedNumber[N](uv) case json.Number: - iv, err := strconv.ParseUint(string(v), 10, 32) + uv, err := strconv.ParseUint(string(v), 10, 64) if err != nil { + var strconvErr *strconv.NumError + if errors.As(err, &strconvErr) && isSignedInteger(string(v)) { + return 0, newUintSignError(string(v)) + } return 0, err } - return uint32(iv), nil + return safeCastUnsignedNumber[N](uv) + case nil: + return 0, nil default: - return 0, fmt.Errorf("%T is not an uint", v) + return 0, fmt.Errorf("%T is not an %T", v, N(0)) + } +} + +type UintSignError struct { + *IntegerError +} + +func newUintSignError(v string) *UintSignError { + return &UintSignError{ + IntegerError: &IntegerError{ + Message: fmt.Sprintf("%v is an invalid unsigned integer: includes sign", v), + }, + } +} + +func (e *UintSignError) Unwrap() error { + return e.IntegerError +} + +// safeCastUnsignedNumber converts an uint64 to a number of type N. +func safeCastUnsignedNumber[N number](val uint64) (N, error) { + var zero N + switch any(zero).(type) { + case uint8: + if val > math.MaxUint8 { + return 0, newNumberOverflowError[uint64](val, 8) + } + case uint16: + if val > math.MaxUint16 { + return 0, newNumberOverflowError[uint64](val, 16) + } + case uint32: + if val > math.MaxUint32 { + return 0, newNumberOverflowError[uint64](val, 32) + } + case uint64, uint, int: + default: + return 0, fmt.Errorf("invalid type %T", zero) + } + + return N(val), nil +} + +func isSignedInteger(v string) bool { + if v == "" { + return false + } + if v[0] != '-' && v[0] != '+' { + return false + } + if _, err := strconv.ParseUint(v[1:], 10, 64); err == nil { + return true } + return false } diff --git a/vendor/github.com/99designs/gqlgen/graphql/upload.go b/vendor/github.com/99designs/gqlgen/graphql/upload.go index dafbde650..b603ab04c 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/upload.go +++ b/vendor/github.com/99designs/gqlgen/graphql/upload.go @@ -18,7 +18,7 @@ func MarshalUpload(f Upload) Marshaler { }) } -func UnmarshalUpload(v interface{}) (Upload, error) { +func UnmarshalUpload(v any) (Upload, error) { upload, ok := v.(Upload) if !ok { return Upload{}, fmt.Errorf("%T is not an Upload", v) diff --git a/vendor/github.com/99designs/gqlgen/graphql/uuid.go b/vendor/github.com/99designs/gqlgen/graphql/uuid.go new file mode 100644 index 000000000..e9f22dccd --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/graphql/uuid.go @@ -0,0 +1,25 @@ +package graphql + +import ( + "fmt" + + "github.com/google/uuid" +) + +func MarshalUUID(id uuid.UUID) Marshaler { + if id == uuid.Nil { + return Null + } + return MarshalString(id.String()) +} + +func UnmarshalUUID(v any) (uuid.UUID, error) { + switch v := v.(type) { + case string: + return uuid.Parse(v) + case []byte: + return uuid.ParseBytes(v) + default: + return uuid.Nil, fmt.Errorf("%T is not a uuid", v) + } +} diff --git a/vendor/github.com/99designs/gqlgen/graphql/version.go b/vendor/github.com/99designs/gqlgen/graphql/version.go index c0c06f659..059bccfb4 100644 --- a/vendor/github.com/99designs/gqlgen/graphql/version.go +++ b/vendor/github.com/99designs/gqlgen/graphql/version.go @@ -1,3 +1,3 @@ package graphql -const Version = "v0.17.20" +const Version = "v0.17.81" diff --git a/vendor/github.com/99designs/gqlgen/internal/code/alias.go b/vendor/github.com/99designs/gqlgen/internal/code/alias.go new file mode 100644 index 000000000..d8d461555 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/internal/code/alias.go @@ -0,0 +1,56 @@ +package code + +import ( + "go/types" + "strings" +) + +// Unalias unwraps an alias type +func Unalias(t types.Type) types.Type { + if alias, ok := t.(*types.Alias); ok { + // If the type is an alias type, it must first check if the non-alias + // type is in an internal package. Only the last type in the alias + // chain is provided as the RHS. + if isAliasInternal(t.String(), unalias(t).String()) { + return types.NewNamed(alias.Obj(), alias.Underlying(), nil) + } + } + return unalias(t) +} + +func unalias(t types.Type) types.Type { + if p, ok := t.(*types.Pointer); ok { + // If the type come from auto-binding, + // it will be a pointer to an alias type. + // (e.g: `type Cursor = entgql.Cursor[int]`) + // *ent.Cursor is the type we got from auto-binding. + return types.NewPointer(Unalias(p.Elem())) + } + return types.Unalias(t) +} + +// isAliasInternal checks if an alias type path is declared for a type within +// an internal package. A best-effort attempt is made to mirror the Go internal +// visibility rules by finding the root for the rhs, and checking to ensure +// that the types both share the same root. +func isAliasInternal(lhs, rhs string) bool { + idx := strings.LastIndex(lhs, "internal") + if idx != -1 { + // If the alias type contains an internal package, there is no reason + // to continue. + return false + } + idx = strings.LastIndex(rhs, "internal") + if idx < 0 { + return false + } + root := rhs[:idx] + switch { + // The alias type path is checked against the root of the non-alias type to + // ensure the types being aliased share the same root. + case strings.HasPrefix(lhs, root): + return true + default: + return false + } +} diff --git a/vendor/github.com/99designs/gqlgen/internal/code/compare.go b/vendor/github.com/99designs/gqlgen/internal/code/compare.go index 1150a24e4..05fad22d4 100644 --- a/vendor/github.com/99designs/gqlgen/internal/code/compare.go +++ b/vendor/github.com/99designs/gqlgen/internal/code/compare.go @@ -1,12 +1,15 @@ package code import ( + "errors" "fmt" "go/types" ) // CompatibleTypes isnt a strict comparison, it allows for pointer differences -func CompatibleTypes(expected types.Type, actual types.Type) error { +func CompatibleTypes(expected, actual types.Type) error { + // Unwrap any aliases + expected, actual = Unalias(expected), Unalias(actual) // Special case to deal with pointer mismatches { expectedPtr, expectedIsPtr := expected.(*types.Pointer) @@ -32,7 +35,7 @@ func CompatibleTypes(expected types.Type, actual types.Type) error { case *types.Array: if actual, ok := actual.(*types.Array); ok { if expected.Len() != actual.Len() { - return fmt.Errorf("array length differs") + return errors.New("array length differs") } return CompatibleTypes(expected.Elem(), actual.Elem()) @@ -50,7 +53,7 @@ func CompatibleTypes(expected types.Type, actual types.Type) error { case *types.Struct: if actual, ok := actual.(*types.Struct); ok { if expected.NumFields() != actual.NumFields() { - return fmt.Errorf("number of struct fields differ") + return errors.New("number of struct fields differ") } for i := 0; i < expected.NumFields(); i++ { @@ -84,11 +87,8 @@ func CompatibleTypes(expected types.Type, actual types.Type) error { if err := CompatibleTypes(expected.Params(), actual.Params()); err != nil { return err } - if err := CompatibleTypes(expected.Results(), actual.Results()); err != nil { - return err - } - - return nil + err := CompatibleTypes(expected.Results(), actual.Results()) + return err } case *types.Interface: if actual, ok := actual.(*types.Interface); ok { @@ -114,11 +114,8 @@ func CompatibleTypes(expected types.Type, actual types.Type) error { return err } - if err := CompatibleTypes(expected.Elem(), actual.Elem()); err != nil { - return err - } - - return nil + err := CompatibleTypes(expected.Elem(), actual.Elem()) + return err } case *types.Chan: diff --git a/vendor/github.com/99designs/gqlgen/internal/code/imports.go b/vendor/github.com/99designs/gqlgen/internal/code/imports.go index 0e499a171..e950f1d5a 100644 --- a/vendor/github.com/99designs/gqlgen/internal/code/imports.go +++ b/vendor/github.com/99designs/gqlgen/internal/code/imports.go @@ -102,21 +102,21 @@ func goModuleRoot(dir string) (string, bool) { // go.mod is not found in the tree, so the same sentinel value fits all the directories in a tree goModuleRootCache[d] = result } else { - if relPath, err := filepath.Rel(result.goModPath, d); err != nil { + relPath, err := filepath.Rel(result.goModPath, d) + if err != nil { panic(err) - } else { - path := result.moduleName - relPath := filepath.ToSlash(relPath) - if !strings.HasSuffix(relPath, "/") { - path += "/" - } - path += relPath - - goModuleRootCache[d] = goModuleSearchResult{ - path: path, - goModPath: result.goModPath, - moduleName: result.moduleName, - } + } + path := result.moduleName + relPath = filepath.ToSlash(relPath) + if !strings.HasSuffix(relPath, "/") { + path += "/" + } + path += relPath + + goModuleRootCache[d] = goModuleSearchResult{ + path: path, + goModPath: result.goModPath, + moduleName: result.moduleName, } } } @@ -138,7 +138,7 @@ func extractModuleName(content []byte) string { break } s := strings.Trim(string(tkn), " \t") - if len(s) != 0 && !strings.HasPrefix(s, "//") { + if s != "" && !strings.HasPrefix(s, "//") { break } if advance <= len(content) { @@ -171,4 +171,4 @@ func ImportPathForDir(dir string) (res string) { return "" } -var modregex = regexp.MustCompile(`module ([^\s]*)`) +var modregex = regexp.MustCompile(`module (\S*)`) diff --git a/vendor/github.com/99designs/gqlgen/internal/code/packages.go b/vendor/github.com/99designs/gqlgen/internal/code/packages.go index c800d3d84..93e84fe42 100644 --- a/vendor/github.com/99designs/gqlgen/internal/code/packages.go +++ b/vendor/github.com/99designs/gqlgen/internal/code/packages.go @@ -7,44 +7,108 @@ import ( "os" "os/exec" "path/filepath" + "strings" "golang.org/x/tools/go/packages" ) var mode = packages.NeedName | packages.NeedFiles | - packages.NeedImports | packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo | - packages.NeedModule | - packages.NeedDeps + packages.NeedModule + +type ( + // Packages is a wrapper around x/tools/go/packages that maintains a (hopefully prewarmed) cache of packages + // that can be invalidated as writes are made and packages are known to change. + Packages struct { + packages map[string]*packages.Package + importToName map[string]string + loadErrors []error + buildFlags []string + packagesToCachePrefix string + + numLoadCalls int // stupid test steam. ignore. + numNameCalls int // stupid test steam. ignore. + } + // Option is a function that can be passed to NewPackages to configure the package loader + Option func(p *Packages) +) -// Packages is a wrapper around x/tools/go/packages that maintains a (hopefully prewarmed) cache of packages -// that can be invalidated as writes are made and packages are known to change. -type Packages struct { - packages map[string]*packages.Package - importToName map[string]string - loadErrors []error +// WithBuildTags option for NewPackages adds build tags to the packages.Load call +func WithBuildTags(tags ...string) func(p *Packages) { + return func(p *Packages) { + p.buildFlags = append(p.buildFlags, "-tags", strings.Join(tags, ",")) + } +} - numLoadCalls int // stupid test steam. ignore. - numNameCalls int // stupid test steam. ignore. +func WithPreloadNames(importPaths ...string) func(p *Packages) { + return func(p *Packages) { + p.LoadAllNames(importPaths...) + } } -// ReloadAll will call LoadAll after clearing the package cache, so we can reload -// packages in the case that the packages have changed -func (p *Packages) ReloadAll(importPaths ...string) []*packages.Package { - p.packages = nil - return p.LoadAll(importPaths...) +// PackagePrefixToCache option for NewPackages +// will not reset gqlgen packages in packages.Load call +func PackagePrefixToCache(prefixPath string) func(p *Packages) { + return func(p *Packages) { + p.packagesToCachePrefix = prefixPath + } +} + +// NewPackages creates a new packages cache +// It will load all packages in the current module, and any packages that are passed to Load or LoadAll +func NewPackages(opts ...Option) *Packages { + p := &Packages{} + for _, opt := range opts { + opt(p) + } + return p +} + +func dedupPackages(packages []string) []string { + packageMap := make(map[string]struct{}) + dedupedPackages := make([]string, 0, len(packageMap)) + for _, p := range packages { + if _, ok := packageMap[p]; ok { + continue + } + packageMap[p] = struct{}{} + dedupedPackages = append(dedupedPackages, p) + } + + return dedupedPackages } -func (p *Packages) checkModuleLoaded(pkgs []*packages.Package) bool { - for i := range pkgs { - if pkgs[i] == nil || pkgs[i].Module == nil { - return false +func (p *Packages) CleanupUserPackages() { + if p.packagesToCachePrefix == "" { + // Cleanup all packages if we don't know which ones to keep + p.packages = nil + } else { + // Don't clean up github.com/99designs/gqlgen prefixed packages, + // they haven't changed and do not need to be reloaded + // if you are using a fork, then you need to have customized + // the prefix using PackagePrefixToCache + var toRemove []string + for k := range p.packages { + if !strings.HasPrefix(k, p.packagesToCachePrefix) { + toRemove = append(toRemove, k) + } + } + for _, k := range toRemove { + delete(p.packages, k) } } - return true +} + +// ReloadAll will call LoadAll after clearing the package cache, so we can reload +// packages in the case that the packages have changed +func (p *Packages) ReloadAll(importPaths ...string) []*packages.Package { + if p.packages != nil { + p.CleanupUserPackages() + } + return p.LoadAll(importPaths...) } // LoadAll will call packages.Load and return the package data for the given packages, @@ -64,14 +128,10 @@ func (p *Packages) LoadAll(importPaths ...string) []*packages.Package { if len(missing) > 0 { p.numLoadCalls++ - pkgs, err := packages.Load(&packages.Config{Mode: mode}, missing...) - - // Sometimes packages.Load not loaded the module info. Call it again to reload it. - if !p.checkModuleLoaded(pkgs) { - fmt.Println("reloading module info") - pkgs, err = packages.Load(&packages.Config{Mode: mode}, missing...) - } - + pkgs, err := packages.Load(&packages.Config{ + Mode: mode, + BuildFlags: p.buildFlags, + }, missing...) if err != nil { p.loadErrors = append(p.loadErrors, err) } @@ -91,11 +151,6 @@ func (p *Packages) LoadAll(importPaths ...string) []*packages.Package { func (p *Packages) addToCache(pkg *packages.Package) { imp := NormalizeVendor(pkg.PkgPath) p.packages[imp] = pkg - for _, imp := range pkg.Imports { - if _, found := p.packages[NormalizeVendor(imp.PkgPath)]; !found { - p.addToCache(imp) - } - } } // Load works the same as LoadAll, except a single package at a time. @@ -120,7 +175,10 @@ func (p *Packages) LoadWithTypes(importPath string) *packages.Package { pkg := p.Load(importPath) if pkg == nil || pkg.TypesInfo == nil { p.numLoadCalls++ - pkgs, err := packages.Load(&packages.Config{Mode: mode}, importPath) + pkgs, err := packages.Load(&packages.Config{ + Mode: mode, + BuildFlags: p.buildFlags, + }, importPath) if err != nil { p.loadErrors = append(p.loadErrors, err) return nil @@ -131,57 +189,72 @@ func (p *Packages) LoadWithTypes(importPath string) *packages.Package { return pkg } -// NameForPackage looks up the package name from the package stanza in the go files at the given import path. -func (p *Packages) NameForPackage(importPath string) string { - if importPath == "" { - panic(errors.New("import path can not be empty")) - } - if p.importToName == nil { - p.importToName = map[string]string{} - } +// LoadAllNames will call packages.Load with the NeedName mode only and will store the package name in a cache. +// it does not return any package data, but after calling this you can call NameForPackage to get the package name without loading the full package data. +func (p *Packages) LoadAllNames(importPaths ...string) { + importPaths = dedupPackages(importPaths) + missing := make([]string, 0, len(importPaths)) + for _, importPath := range importPaths { + if importPath == "" { + panic(errors.New("import path can not be empty")) + } - importPath = NormalizeVendor(importPath) + if p.importToName == nil { + p.importToName = map[string]string{} + } - // if its in the name cache use it - if name := p.importToName[importPath]; name != "" { - return name + importPath = NormalizeVendor(importPath) + + // if it's in the name cache use it + if name := p.importToName[importPath]; name != "" { + continue + } + + // otherwise we might have already loaded the full package data for it cached + pkg := p.packages[importPath] + if pkg != nil { + if _, ok := p.importToName[importPath]; !ok { + p.importToName[importPath] = pkg.Name + } + + continue + } + + missing = append(missing, importPath) } - // otherwise we might have already loaded the full package data for it cached - pkg := p.packages[importPath] + if len(missing) > 0 { + pkgs, err := packages.Load(&packages.Config{ + Mode: packages.NeedName, + BuildFlags: p.buildFlags, + }, missing...) - if pkg == nil { - // otherwise do a name only lookup for it but dont put it in the package cache. - p.numNameCalls++ - pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName}, importPath) if err != nil { p.loadErrors = append(p.loadErrors, err) - } else { - pkg = pkgs[0] } - } - if pkg == nil || pkg.Name == "" { - return SanitizePackageName(filepath.Base(importPath)) + for _, pkg := range pkgs { + if pkg.Name == "" { + pkg.Name = SanitizePackageName(filepath.Base(pkg.PkgPath)) + } + + p.importToName[pkg.PkgPath] = pkg.Name + } } +} - p.importToName[importPath] = pkg.Name +// NameForPackage looks up the package name from the package stanza in the go files at the given import path. +func (p *Packages) NameForPackage(importPath string) string { + p.numNameCalls++ + p.LoadAllNames(importPath) - return pkg.Name + importPath = NormalizeVendor(importPath) + return p.importToName[importPath] } -// Evict removes a given package import path from the cache, along with any packages that depend on it. Further calls -// to Load will fetch it from disk. +// Evict removes a given package import path from the cache. Further calls to Load will fetch it from disk. func (p *Packages) Evict(importPath string) { delete(p.packages, importPath) - - for _, pkg := range p.packages { - for _, imported := range pkg.Imports { - if imported.PkgPath == importPath { - p.Evict(pkg.PkgPath) - } - } - } } func (p *Packages) ModTidy() error { @@ -197,8 +270,7 @@ func (p *Packages) ModTidy() error { // Errors returns any errors that were returned by Load, either from the call itself or any of the loaded packages. func (p *Packages) Errors() PkgErrors { - var res []error //nolint:prealloc - res = append(res, p.loadErrors...) + res := append([]error{}, p.loadErrors...) for _, pkg := range p.packages { for _, err := range pkg.Errors { res = append(res, err) diff --git a/vendor/github.com/99designs/gqlgen/internal/code/util.go b/vendor/github.com/99designs/gqlgen/internal/code/util.go index cbe40858e..96c6e03ff 100644 --- a/vendor/github.com/99designs/gqlgen/internal/code/util.go +++ b/vendor/github.com/99designs/gqlgen/internal/code/util.go @@ -54,7 +54,7 @@ func QualifyPackagePath(importPath string) string { return pkg.ImportPath } -var invalidPackageNameChar = regexp.MustCompile(`[^\w]`) +var invalidPackageNameChar = regexp.MustCompile(`\W`) func SanitizePackageName(pkg string) string { return invalidPackageNameChar.ReplaceAllLiteralString(filepath.Base(pkg), "_") diff --git a/vendor/github.com/99designs/gqlgen/internal/imports/prune.go b/vendor/github.com/99designs/gqlgen/internal/imports/prune.go index d42a41579..f5fc71c69 100644 --- a/vendor/github.com/99designs/gqlgen/internal/imports/prune.go +++ b/vendor/github.com/99designs/gqlgen/internal/imports/prune.go @@ -10,10 +10,10 @@ import ( "go/token" "strings" - "github.com/99designs/gqlgen/internal/code" - "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/imports" + + "github.com/99designs/gqlgen/internal/code" ) type visitFn func(node ast.Node) diff --git a/vendor/github.com/99designs/gqlgen/internal/rewrite/rewriter.go b/vendor/github.com/99designs/gqlgen/internal/rewrite/rewriter.go index a8a6485cf..909cfe71b 100644 --- a/vendor/github.com/99designs/gqlgen/internal/rewrite/rewriter.go +++ b/vendor/github.com/99designs/gqlgen/internal/rewrite/rewriter.go @@ -10,8 +10,9 @@ import ( "strconv" "strings" - "github.com/99designs/gqlgen/internal/code" "golang.org/x/tools/go/packages" + + "github.com/99designs/gqlgen/internal/code" ) type Rewriter struct { @@ -62,13 +63,12 @@ func (r *Rewriter) getFile(filename string) string { } r.files[filename] = string(b) - } return r.files[filename] } -func (r *Rewriter) GetMethodComment(structname string, methodname string) string { +func (r *Rewriter) GetPrevDecl(structname, methodname string) *ast.FuncDecl { for _, f := range r.pkg.Syntax { for _, d := range f.Decls { d, isFunc := d.(*ast.FuncDecl) @@ -89,48 +89,29 @@ func (r *Rewriter) GetMethodComment(structname string, methodname string) string if !ok { continue } - if ident.Name != structname { continue } - return d.Doc.Text() + r.copied[d] = true + return d } } + return nil +} +func (r *Rewriter) GetMethodComment(structname, methodname string) string { + d := r.GetPrevDecl(structname, methodname) + if d != nil { + return d.Doc.Text() + } return "" } -func (r *Rewriter) GetMethodBody(structname string, methodname string) string { - for _, f := range r.pkg.Syntax { - for _, d := range f.Decls { - d, isFunc := d.(*ast.FuncDecl) - if !isFunc { - continue - } - if d.Name.Name != methodname { - continue - } - if d.Recv == nil || len(d.Recv.List) == 0 { - continue - } - recv := d.Recv.List[0].Type - if star, isStar := recv.(*ast.StarExpr); isStar { - recv = star.X - } - ident, ok := recv.(*ast.Ident) - if !ok { - continue - } - - if ident.Name != structname { - continue - } - r.copied[d] = true - - return r.getSource(d.Body.Pos()+1, d.Body.End()-1) - } +func (r *Rewriter) GetMethodBody(structname, methodname string) string { + d := r.GetPrevDecl(structname, methodname) + if d != nil { + return r.getSource(d.Body.Pos()+1, d.Body.End()-1) } - return "" } diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/constants.go b/vendor/github.com/99designs/gqlgen/plugin/federation/constants.go new file mode 100644 index 000000000..2427b22c8 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/plugin/federation/constants.go @@ -0,0 +1,186 @@ +package federation + +import ( + "github.com/vektah/gqlparser/v2/ast" + + "github.com/99designs/gqlgen/codegen/config" +) + +// The name of the field argument that is injected into the resolver to support @requires. +const fieldArgRequires = "_federationRequires" + +// The name of the scalar type used in the injected field argument to support @requires. +const mapTypeName = "_RequiresMap" + +// The @key directive that defines the key fields for an entity. +const dirNameKey = "key" + +// The @requires directive that defines the required fields for an entity to be resolved. +const dirNameRequires = "requires" + +// The @entityResolver directive allows users to specify entity resolvers as batch lookups +const dirNameEntityResolver = "entityResolver" + +const dirNamePopulateFromRepresentations = "populateFromRepresentations" + +var populateFromRepresentationsImplementation = `func(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) { + fc := graphql.GetFieldContext(ctx) + + // We get the Federation representations argument from the _entities resolver + representations, ok := fc.Parent.Parent.Args["representations"].([]map[string]any) + if !ok { + return nil, errors.New("must be called from within _entities") + } + + // Get the index of the current entity in the representations list. This is + // set by the execution context after the _entities resolver is called. + index := fc.Parent.Index + if index == nil { + return nil, errors.New("couldn't find input index for entity") + } + + if len(representations) < *index { + return nil, errors.New("representation not found") + } + + return representations[*index], nil +}` + +const DirNameEntityReference = "entityReference" + +// The fields arguments must be provided to both key and requires directives. +const DirArgFields = "fields" + +// Tells the code generator what type the directive is referencing +const DirArgType = "type" + +// The file name for Federation directives +const dirGraphQLQFile = "federation/directives.graphql" + +// The file name for Federation entities +const entityGraphQLQFile = "federation/entity.graphql" + +const federationVersion1Schema = ` + directive @key(fields: _FieldSet!) repeatable on OBJECT | INTERFACE + directive @requires(fields: _FieldSet!) on FIELD_DEFINITION + directive @provides(fields: _FieldSet!) on FIELD_DEFINITION + directive @extends on OBJECT | INTERFACE + directive @external on FIELD_DEFINITION + scalar _Any + scalar _FieldSet +` + +const federationVersion2Schema = ` + directive @authenticated on FIELD_DEFINITION | OBJECT | INTERFACE | SCALAR | ENUM + directive @composeDirective(name: String!) repeatable on SCHEMA + directive @extends on OBJECT | INTERFACE + directive @external on OBJECT | FIELD_DEFINITION + directive @key(fields: FieldSet!, resolvable: Boolean = true) repeatable on OBJECT | INTERFACE + directive @inaccessible on + | ARGUMENT_DEFINITION + | ENUM + | ENUM_VALUE + | FIELD_DEFINITION + | INPUT_FIELD_DEFINITION + | INPUT_OBJECT + | INTERFACE + | OBJECT + | SCALAR + | UNION + directive @interfaceObject on OBJECT + directive @link(import: [String!], url: String!) repeatable on SCHEMA + directive @override(from: String!, label: String) on FIELD_DEFINITION + directive @policy(policies: [[federation__Policy!]!]!) on + | FIELD_DEFINITION + | OBJECT + | INTERFACE + | SCALAR + | ENUM + directive @provides(fields: FieldSet!) on FIELD_DEFINITION + directive @requires(fields: FieldSet!) on FIELD_DEFINITION + directive @requiresScopes(scopes: [[federation__Scope!]!]!) on + | FIELD_DEFINITION + | OBJECT + | INTERFACE + | SCALAR + | ENUM + directive @shareable repeatable on FIELD_DEFINITION | OBJECT + directive @tag(name: String!) repeatable on + | ARGUMENT_DEFINITION + | ENUM + | ENUM_VALUE + | FIELD_DEFINITION + | INPUT_FIELD_DEFINITION + | INPUT_OBJECT + | INTERFACE + | OBJECT + | SCALAR + | UNION + scalar _Any + scalar FieldSet + scalar federation__Policy + scalar federation__Scope +` + +var builtins = config.TypeMap{ + "_Service": { + Model: config.StringList{ + "github.com/99designs/gqlgen/plugin/federation/fedruntime.Service", + }, + }, + "_Entity": { + Model: config.StringList{ + "github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity", + }, + }, + "Entity": { + Model: config.StringList{ + "github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity", + }, + }, + "_Any": { + Model: config.StringList{"github.com/99designs/gqlgen/graphql.Map"}, + }, + "federation__Scope": { + Model: config.StringList{"github.com/99designs/gqlgen/graphql.String"}, + }, + "federation__Policy": { + Model: config.StringList{"github.com/99designs/gqlgen/graphql.String"}, + }, +} + +var dirPopulateFromRepresentations = &ast.DirectiveDefinition{ + Name: dirNamePopulateFromRepresentations, + IsRepeatable: false, + Description: `This is a runtime directive used to implement @requires. It's automatically placed +on the generated _federationRequires argument, and the implementation of it extracts the +correct value from the input representations list.`, + Locations: []ast.DirectiveLocation{ast.LocationArgumentDefinition}, + Position: &ast.Position{Src: &ast.Source{ + Name: dirGraphQLQFile, + }}, +} + +var dirEntityReference = &ast.DirectiveDefinition{ + Name: DirNameEntityReference, + IsRepeatable: false, + Description: `This is a compile-time directive used to implement @requires. +It tells the code generator how to generate the model for the scalar.`, + Locations: []ast.DirectiveLocation{ast.LocationScalar}, + Arguments: ast.ArgumentDefinitionList{ + { + Name: DirArgType, + Type: ast.NonNullNamedType("String", nil), + Description: `The name of the entity that the fields selection +set should be validated against.`, + }, + { + Name: DirArgFields, + Type: ast.NonNullNamedType("FieldSet", nil), + Description: "The selection that the scalar should generate into.", + }, + }, + Position: &ast.Position{Src: &ast.Source{ + Name: dirGraphQLQFile, + }}, +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/entity.go b/vendor/github.com/99designs/gqlgen/plugin/federation/entity.go new file mode 100644 index 000000000..562d86c54 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/plugin/federation/entity.go @@ -0,0 +1,126 @@ +package federation + +import ( + "go/types" + + "github.com/vektah/gqlparser/v2/ast" + + "github.com/99designs/gqlgen/codegen/config" + "github.com/99designs/gqlgen/codegen/templates" + "github.com/99designs/gqlgen/plugin/federation/fieldset" +) + +// Entity represents a federated type +// that was declared in the GQL schema. +type Entity struct { + Name string // The same name as the type declaration + Def *ast.Definition + Resolvers []*EntityResolver + Requires []*Requires + Multi bool + Type types.Type +} + +type EntityResolver struct { + ResolverName string // The resolver name, such as FindUserByID + KeyFields []*KeyField // The fields declared in @key. + InputType types.Type // The Go generated input type for multi entity resolvers + InputTypeName string + ReturnType types.Type // The Go generated return type for the entity + ReturnTypeName string +} + +func (e *EntityResolver) LookupInputType() string { + return templates.CurrentImports.LookupType(e.InputType) +} + +type KeyField struct { + Definition *ast.FieldDefinition + Field fieldset.Field // len > 1 for nested fields + Type *config.TypeReference // The Go representation of that field type +} + +// Requires represents an @requires clause +type Requires struct { + Name string // the name of the field + Field fieldset.Field // source Field, len > 1 for nested fields + Type *config.TypeReference // The Go representation of that field type +} + +func (e *Entity) allFieldsAreExternal(federationVersion int) bool { + for _, field := range e.Def.Fields { + if !e.isFieldImplicitlyExternal(field, federationVersion) && field.Directives.ForName("external") == nil { + return false + } + } + return true +} + +// In federation v2, key fields are implicitly external. +func (e *Entity) isFieldImplicitlyExternal(field *ast.FieldDefinition, federationVersion int) bool { + // Key fields are only implicitly external in Federation 2 + if federationVersion != 2 { + return false + } + // TODO: From the spec, it seems like if an entity is not resolvable then it should not only not have a resolver, but should not appear in the _Entity union. + // The current implementation is a less drastic departure from the previous behavior, but should probably be reviewed. + // See https://www.apollographql.com/docs/federation/subgraph-spec/ + if e.isResolvable() { + return false + } + // If the field is a key field, it is implicitly external + if e.isKeyField(field) { + return true + } + + return false +} + +// Determine if the entity is resolvable. +func (e *Entity) isResolvable() bool { + key := e.Def.Directives.ForName(dirNameKey) + if key == nil { + // If there is no key directive, the entity is resolvable. + return true + } + resolvable := key.Arguments.ForName("resolvable") + if resolvable == nil { + // If there is no resolvable argument, the entity is resolvable. + return true + } + // only if resolvable: false has been set on the @key directive do we consider the entity non-resolvable. + return resolvable.Value.Raw != "false" +} + +// Determine if a field is part of the entities key. +func (e *Entity) isKeyField(field *ast.FieldDefinition) bool { + for _, keyField := range e.keyFields() { + if keyField == field.Name { + return true + } + } + return false +} + +// Get the key fields for this entity. +func (e *Entity) keyFields() []string { + key := e.Def.Directives.ForName(dirNameKey) + if key == nil { + return []string{} + } + fields := key.Arguments.ForName(DirArgFields) + if fields == nil { + return []string{} + } + fieldSet := fieldset.New(fields.Value.Raw, nil) + keyFields := make([]string, len(fieldSet)) + for i, field := range fieldSet { + keyFields[i] = field[0] + } + return keyFields +} + +// GetTypeInfo - get the imported package & type name combo. package.TypeName +func (e Entity) GetTypeInfo() string { + return templates.CurrentImports.LookupType(e.Type) +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.go b/vendor/github.com/99designs/gqlgen/plugin/federation/federation.go index cd60acee2..b82ad70e6 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.go +++ b/vendor/github.com/99designs/gqlgen/plugin/federation/federation.go @@ -2,6 +2,7 @@ package federation import ( _ "embed" + "errors" "fmt" "sort" "strings" @@ -11,56 +12,127 @@ import ( "github.com/99designs/gqlgen/codegen" "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/codegen/templates" - "github.com/99designs/gqlgen/plugin" + "github.com/99designs/gqlgen/internal/rewrite" "github.com/99designs/gqlgen/plugin/federation/fieldset" ) //go:embed federation.gotpl var federationTemplate string -type federation struct { - Entities []*Entity - Version int +//go:embed requires.gotpl +var explicitRequiresTemplate string + +type Federation struct { + Entities []*Entity + RequiresEntities map[string]*Entity + PackageOptions PackageOptions + + version int + + // true if @requires is used in the schema + usesRequires bool +} + +type PackageOptions struct { + // ExplicitRequires will generate a function in the execution context + // to populate fields using the @required directive into the entity. + // + // You can only set one of ExplicitRequires or ComputedRequires to true. + ExplicitRequires bool + // ComputedRequires generates resolver functions to compute values for + // fields using the @required directive. + ComputedRequires bool + // EntityResolverMulti is default engine for entityResolver generation. + // This can be overriding by @entityResolver(multi: Boolean) directive. + // false by default. + EntityResolverMulti bool } // New returns a federation plugin that injects // federated directives and types into the schema -func New(version int) plugin.Plugin { +func New(version int, cfg *config.Config) (*Federation, error) { if version == 0 { version = 1 } - return &federation{Version: version} + options, err := buildPackageOptions(cfg) + if err != nil { + return nil, fmt.Errorf("invalid federation package options: %w", err) + } + return &Federation{ + version: version, + PackageOptions: options, + }, nil +} + +func buildPackageOptions(cfg *config.Config) (PackageOptions, error) { + packageOptions := cfg.Federation.Options + + const ( + optionExplicitRequires = "explicit_requires" + optionComputedRequires = "computed_requires" + optionEntityResolverMulti = "entity_resolver_multi" + ) + + var explicitRequires, + computedRequires, + entityResolverMulti bool + + for k, v := range packageOptions { + switch k { + case optionExplicitRequires: + explicitRequires = v + case optionComputedRequires: + computedRequires = v + case optionEntityResolverMulti: + entityResolverMulti = v + default: + return PackageOptions{}, fmt.Errorf("unknown package option: %s", k) + } + } + + if explicitRequires && computedRequires { + return PackageOptions{}, fmt.Errorf( + "only one of %s or %s can be set to true", + optionExplicitRequires, + optionComputedRequires, + ) + } + + if computedRequires { + if cfg.Federation.Version != 2 { + return PackageOptions{}, fmt.Errorf( + "when using federation.options.%s you must be using Federation 2", + optionComputedRequires, + ) + } + + // We rely on injecting a null argument with a directives for fields with @requires, so we need to ensure + // our directive is always called. + if !cfg.CallArgumentDirectivesWithNull { + return PackageOptions{}, fmt.Errorf( + "when using federation.options.%s, call_argument_directives_with_null must be set to true", + optionComputedRequires, + ) + } + } + + // We rely on injecting a null argument with a directives for fields with @requires, so we need to ensure + // our directive is always called. + return PackageOptions{ + ExplicitRequires: explicitRequires, + ComputedRequires: computedRequires, + EntityResolverMulti: entityResolverMulti, + }, nil } // Name returns the plugin name -func (f *federation) Name() string { +func (f *Federation) Name() string { return "federation" } // MutateConfig mutates the configuration -func (f *federation) MutateConfig(cfg *config.Config) error { - builtins := config.TypeMap{ - "_Service": { - Model: config.StringList{ - "github.com/99designs/gqlgen/plugin/federation/fedruntime.Service", - }, - }, - "_Entity": { - Model: config.StringList{ - "github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity", - }, - }, - "Entity": { - Model: config.StringList{ - "github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity", - }, - }, - "_Any": { - Model: config.StringList{"github.com/99designs/gqlgen/graphql.Map"}, - }, - } - +func (f *Federation) MutateConfig(cfg *config.Config) error { for typeName, entry := range builtins { if cfg.Models.Exists(typeName) { return fmt.Errorf("%v already exists which must be reserved when Federation is enabled", typeName) @@ -68,106 +140,103 @@ func (f *federation) MutateConfig(cfg *config.Config) error { cfg.Models[typeName] = entry } cfg.Directives["external"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["requires"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives[dirNameRequires] = config.DirectiveConfig{SkipRuntime: true} cfg.Directives["provides"] = config.DirectiveConfig{SkipRuntime: true} - cfg.Directives["key"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives[dirNameKey] = config.DirectiveConfig{SkipRuntime: true} cfg.Directives["extends"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives[dirNameEntityResolver] = config.DirectiveConfig{SkipRuntime: true} // Federation 2 specific directives - if f.Version == 2 { + if f.version == 2 { cfg.Directives["shareable"] = config.DirectiveConfig{SkipRuntime: true} cfg.Directives["link"] = config.DirectiveConfig{SkipRuntime: true} cfg.Directives["tag"] = config.DirectiveConfig{SkipRuntime: true} cfg.Directives["override"] = config.DirectiveConfig{SkipRuntime: true} cfg.Directives["inaccessible"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives["authenticated"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives["requiresScopes"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives["policy"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives["interfaceObject"] = config.DirectiveConfig{SkipRuntime: true} + cfg.Directives["composeDirective"] = config.DirectiveConfig{SkipRuntime: true} + } + + if f.usesRequires && f.PackageOptions.ComputedRequires { + cfg.Schema.Directives[dirPopulateFromRepresentations.Name] = dirPopulateFromRepresentations + cfg.Directives[dirPopulateFromRepresentations.Name] = config.DirectiveConfig{Implementation: &populateFromRepresentationsImplementation} + + cfg.Schema.Directives[dirEntityReference.Name] = dirEntityReference + cfg.Directives[dirEntityReference.Name] = config.DirectiveConfig{SkipRuntime: true} + + f.addMapType(cfg) + f.mutateSchemaForRequires(cfg.Schema, cfg) } return nil } -func (f *federation) InjectSourceEarly() *ast.Source { - input := ` - scalar _Any - scalar _FieldSet +func (f *Federation) InjectSourcesEarly() ([]*ast.Source, error) { + input := `` - directive @external on FIELD_DEFINITION - directive @requires(fields: _FieldSet!) on FIELD_DEFINITION - directive @provides(fields: _FieldSet!) on FIELD_DEFINITION - directive @extends on OBJECT | INTERFACE -` // add version-specific changes on key directive, as well as adding the new directives for federation 2 - if f.Version == 1 { - input += ` - directive @key(fields: _FieldSet!) repeatable on OBJECT | INTERFACE -` - } else if f.Version == 2 { - input += ` - directive @key(fields: _FieldSet!, resolvable: Boolean = true) repeatable on OBJECT | INTERFACE - directive @link(import: [String!], url: String!) repeatable on SCHEMA - directive @shareable on OBJECT | FIELD_DEFINITION - directive @tag(name: String!) repeatable on FIELD_DEFINITION | INTERFACE | OBJECT | UNION | ARGUMENT_DEFINITION | SCALAR | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION - directive @override(from: String!) on FIELD_DEFINITION - directive @inaccessible on SCALAR | OBJECT | FIELD_DEFINITION | ARGUMENT_DEFINITION | INTERFACE | UNION | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION -` + switch f.version { + case 1: + input += federationVersion1Schema + case 2: + input += federationVersion2Schema } - return &ast.Source{ - Name: "federation/directives.graphql", + + return []*ast.Source{{ + Name: dirGraphQLQFile, Input: input, BuiltIn: true, - } + }}, nil } -// InjectSources creates a GraphQL Entity type with all +// InjectSourcesLate creates a GraphQL Entity type with all // the fields that had the @key directive -func (f *federation) InjectSourceLate(schema *ast.Schema) *ast.Source { - f.setEntities(schema) - - var entities, resolvers, entityResolverInputDefinitions string - for i, e := range f.Entities { - if i != 0 { - entities += " | " +func (f *Federation) InjectSourcesLate(schema *ast.Schema) ([]*ast.Source, error) { + f.Entities = f.buildEntities(schema, f.version) + + entities := make([]string, 0) + resolvers := make([]string, 0) + entityResolverInputDefinitions := make([]string, 0) + for _, e := range f.Entities { + if e.Def.Kind != ast.Interface { + entities = append(entities, e.Name) + } else if len(schema.GetPossibleTypes(e.Def)) == 0 { + fmt.Println( + "skipping @key field on interface " + e.Def.Name + " as no types implement it", + ) } - entities += e.Name for _, r := range e.Resolvers { - if e.Multi { - if entityResolverInputDefinitions != "" { - entityResolverInputDefinitions += "\n\n" - } - entityResolverInputDefinitions += "input " + r.InputType + " {\n" - for _, keyField := range r.KeyFields { - entityResolverInputDefinitions += fmt.Sprintf("\t%s: %s\n", keyField.Field.ToGo(), keyField.Definition.Type.String()) - } - entityResolverInputDefinitions += "}" - resolvers += fmt.Sprintf("\t%s(reps: [%s!]!): [%s]\n", r.ResolverName, r.InputType, e.Name) - } else { - resolverArgs := "" - for _, keyField := range r.KeyFields { - resolverArgs += fmt.Sprintf("%s: %s,", keyField.Field.ToGoPrivate(), keyField.Definition.Type.String()) - } - resolvers += fmt.Sprintf("\t%s(%s): %s!\n", r.ResolverName, resolverArgs, e.Name) + resolverSDL, entityResolverInputSDL := buildResolverSDL(r, e.Multi) + resolvers = append(resolvers, resolverSDL) + if entityResolverInputSDL != "" { + entityResolverInputDefinitions = append(entityResolverInputDefinitions, entityResolverInputSDL) } } } var blocks []string - if entities != "" { - entities = `# a union of all types that use the @key directive -union _Entity = ` + entities - blocks = append(blocks, entities) + if len(entities) > 0 { + entitiesSDL := `# a union of all types that use the @key directive +union _Entity = ` + strings.Join(entities, " | ") + blocks = append(blocks, entitiesSDL) } // resolvers can be empty if a service defines only "empty // extend" types. This should be rare. - if resolvers != "" { - if entityResolverInputDefinitions != "" { - blocks = append(blocks, entityResolverInputDefinitions) + if len(resolvers) > 0 { + if len(entityResolverInputDefinitions) > 0 { + inputSDL := strings.Join(entityResolverInputDefinitions, "\n\n") + blocks = append(blocks, inputSDL) } - resolvers = `# fake type to build resolver interfaces for users to implement + resolversSDL := `# fake type to build resolver interfaces for users to implement type Entity { - ` + resolvers + ` +` + strings.Join(resolvers, "\n") + ` }` - blocks = append(blocks, resolvers) + blocks = append(blocks, resolversSDL) } _serviceTypeDef := `type _Service { @@ -191,52 +260,28 @@ type Entity { }` blocks = append(blocks, extendTypeQueryDef) - return &ast.Source{ - Name: "federation/entity.graphql", + return []*ast.Source{{ + Name: entityGraphQLQFile, BuiltIn: true, Input: "\n" + strings.Join(blocks, "\n\n") + "\n", - } -} - -// Entity represents a federated type -// that was declared in the GQL schema. -type Entity struct { - Name string // The same name as the type declaration - Def *ast.Definition - Resolvers []*EntityResolver - Requires []*Requires - Multi bool + }}, nil } -type EntityResolver struct { - ResolverName string // The resolver name, such as FindUserByID - KeyFields []*KeyField // The fields declared in @key. - InputType string // The Go generated input type for multi entity resolvers -} +func (f *Federation) GenerateCode(data *codegen.Data) error { + // requires imports + requiresImports := make(map[string]bool, 0) + requiresImports["context"] = true + requiresImports["fmt"] = true -type KeyField struct { - Definition *ast.FieldDefinition - Field fieldset.Field // len > 1 for nested fields - Type *config.TypeReference // The Go representation of that field type -} + requiresEntities := make(map[string]*Entity, 0) -// Requires represents an @requires clause -type Requires struct { - Name string // the name of the field - Field fieldset.Field // source Field, len > 1 for nested fields - Type *config.TypeReference // The Go representation of that field type -} - -func (e *Entity) allFieldsAreExternal() bool { - for _, field := range e.Def.Fields { - if field.Directives.ForName("external") == nil { - return false - } + // Save package options on f for template use + packageOptions, err := buildPackageOptions(data.Config) + if err != nil { + return fmt.Errorf("invalid federation package options: %w", err) } - return true -} + f.PackageOptions = packageOptions -func (f *federation) GenerateCode(data *codegen.Data) error { if len(f.Entities) > 0 { if data.Objects.ByName("Entity") != nil { data.Objects.ByName("Entity").Root = true @@ -244,19 +289,18 @@ func (f *federation) GenerateCode(data *codegen.Data) error { for _, e := range f.Entities { obj := data.Objects.ByName(e.Def.Name) - for _, r := range e.Resolvers { - // fill in types for key fields - // - for _, keyField := range r.KeyFields { - if len(keyField.Field) == 0 { - fmt.Println( - "skipping @key field " + keyField.Definition.Name + " in " + r.ResolverName + " in " + e.Def.Name, - ) - continue - } - cgField := keyField.Field.TypeReference(obj, data.Objects) - keyField.Type = cgField.TypeReference + if e.Def.Kind == ast.Interface { + if len(data.Interfaces[e.Def.Name].Implementors) == 0 { + fmt.Println( + "skipping @key field on interface " + e.Def.Name + " as no types implement it", + ) + continue } + obj = data.Objects.ByName(data.Interfaces[e.Def.Name].Implementors[0].Name) + } + + for _, r := range e.Resolvers { + populateKeyFieldTypes(r, obj, data.Objects, e.Def.Name) } // fill in types for requires fields @@ -266,150 +310,305 @@ func (f *federation) GenerateCode(data *codegen.Data) error { fmt.Println("skipping @requires field " + reqField.Name + " in " + e.Def.Name) continue } + // keep track of which entities have requires + requiresEntities[e.Def.Name] = e + // make a proper import path + typeString := strings.Split(obj.Type.String(), ".") + requiresImports[strings.Join(typeString[:len(typeString)-1], ".")] = true + + if containsUnionField(reqField) { + continue + } + cgField := reqField.Field.TypeReference(obj, data.Objects) reqField.Type = cgField.TypeReference } + // add type info to entity + e.Type = obj.Type + } + } + + // fill in types for resolver inputs + // + for _, entity := range f.Entities { + if !entity.Multi { + continue + } + + for _, resolver := range entity.Resolvers { + obj := data.Inputs.ByName(resolver.InputTypeName) + if obj == nil { + return fmt.Errorf("input object %s not found", resolver.InputTypeName) + } + + resolver.InputType = obj.Type } } + if f.PackageOptions.ExplicitRequires && len(requiresEntities) > 0 { + err := f.generateExplicitRequires( + data, + requiresEntities, + requiresImports, + ) + if err != nil { + return err + } + } + + f.RequiresEntities = requiresEntities + return templates.Render(templates.Options{ - PackageName: data.Config.Federation.Package, - Filename: data.Config.Federation.Filename, - Data: f, + PackageName: data.Config.Federation.Package, + Filename: data.Config.Federation.Filename, + Data: struct { + Federation + UsePointers bool + UseFunctionSyntaxForExecutionContext bool + }{*f, data.Config.ResolversAlwaysReturnPointers, data.Config.UseFunctionSyntaxForExecutionContext}, GeneratedHeader: true, Packages: data.Config.Packages, Template: federationTemplate, }) } -func (f *federation) setEntities(schema *ast.Schema) { - for _, schemaType := range schema.Types { - keys, ok := isFederatedEntity(schemaType) - if !ok { +func containsUnionField(reqField *Requires) bool { + for _, requireFields := range reqField.Field { + if strings.HasPrefix(requireFields, "... on") { + return true + } + } + return false +} + +// Fill in types for key fields +func populateKeyFieldTypes( + resolver *EntityResolver, + obj *codegen.Object, + allObjects codegen.Objects, + name string, +) { + for _, keyField := range resolver.KeyFields { + if len(keyField.Field) == 0 { + fmt.Println( + "skipping @key field " + keyField.Definition.Name + " in " + resolver.ResolverName + " in " + name, + ) continue } - e := &Entity{ - Name: schemaType.Name, - Def: schemaType, - Resolvers: nil, - Requires: nil, + cgField := keyField.Field.TypeReference(obj, allObjects) + keyField.Type = cgField.TypeReference + } +} + +func (f *Federation) buildEntities(schema *ast.Schema, version int) []*Entity { + entities := make([]*Entity, 0) + for _, schemaType := range schema.Types { + entity := f.buildEntity(schemaType, schema, version) + if entity != nil { + entities = append(entities, entity) } + } - // Let's process custom entity resolver settings. - dir := schemaType.Directives.ForName("entityResolver") - if dir != nil { - if dirArg := dir.Arguments.ForName("multi"); dirArg != nil { - if dirVal, err := dirArg.Value.Value(nil); err == nil { - e.Multi = dirVal.(bool) - } + // make sure order remains stable across multiple builds + sort.Slice(entities, func(i, j int) bool { + return entities[i].Name < entities[j].Name + }) + + return entities +} + +func (f *Federation) buildEntity( + schemaType *ast.Definition, + schema *ast.Schema, + version int, +) *Entity { + keys, ok := isFederatedEntity(schemaType) + if !ok { + return nil + } + + if (schemaType.Kind == ast.Interface) && (len(schema.GetPossibleTypes(schemaType)) == 0) { + fmt.Printf("@key directive found on unused \"interface %s\". Will be ignored.\n", schemaType.Name) + return nil + } + + entity := &Entity{ + Name: schemaType.Name, + Def: schemaType, + Resolvers: nil, + Requires: nil, + Multi: f.isMultiEntity(schemaType), + } + + // If our schema has a field with a type defined in + // another service, then we need to define an "empty + // extend" of that type in this service, so this service + // knows what the type is like. But the graphql-server + // will never ask us to actually resolve this "empty + // extend", so we don't require a resolver function for + // it. (Well, it will never ask in practice; it's + // unclear whether the spec guarantees this. See + // https://github.com/apollographql/apollo-server/issues/3852 + // ). Example: + // type MyType { + // myvar: TypeDefinedInOtherService + // } + // // Federation needs this type, but + // // it doesn't need a resolver for it! + // extend TypeDefinedInOtherService @key(fields: "id") { + // id: ID @external + // } + if entity.allFieldsAreExternal(version) { + return entity + } + + entity.Resolvers = buildResolvers(schemaType, schema, keys, entity.Multi) + entity.Requires = buildRequires(schemaType) + if len(entity.Requires) > 0 { + f.usesRequires = true + } + + return entity +} + +// isMultiEntity returns @entityResolver(multi) value, if directive is not defined, +// then global configuration parameter will be used. +func (f *Federation) isMultiEntity(schemaType *ast.Definition) bool { + dir := schemaType.Directives.ForName(dirNameEntityResolver) + if dir == nil { + return f.PackageOptions.EntityResolverMulti + } + + if dirArg := dir.Arguments.ForName("multi"); dirArg != nil { + if dirVal, err := dirArg.Value.Value(nil); err == nil { + return dirVal.(bool) + } + } + + return f.PackageOptions.EntityResolverMulti +} + +func buildResolvers( + schemaType *ast.Definition, + schema *ast.Schema, + keys []*ast.Directive, + multi bool, +) []*EntityResolver { + resolvers := make([]*EntityResolver, 0) + for _, dir := range keys { + if len(dir.Arguments) > 2 { + panic("More than two arguments provided for @key declaration.") + } + keyFields, resolverFields := buildKeyFields( + schemaType, + schema, + dir, + ) + + resolverFieldsToGo := schemaType.Name + "By" + strings.Join(resolverFields, "And") + var resolverName string + if multi { + resolverFieldsToGo += "s" // Pluralize for better API readability + resolverName = fmt.Sprintf("findMany%s", resolverFieldsToGo) + } else { + resolverName = fmt.Sprintf("find%s", resolverFieldsToGo) + } + + resolvers = append(resolvers, &EntityResolver{ + ResolverName: resolverName, + KeyFields: keyFields, + InputTypeName: resolverFieldsToGo + "Input", + ReturnTypeName: schemaType.Name, + }) + } + + return resolvers +} + +func extractFields( + dir *ast.Directive, +) (string, error) { + var arg *ast.Argument + + // since directives are able to now have multiple arguments, we need to check both possible for a possible @key(fields="" fields="") + for _, a := range dir.Arguments { + if a.Name == DirArgFields { + if arg != nil { + return "", errors.New("more than one \"fields\" argument provided for declaration") } + arg = a } + } - // If our schema has a field with a type defined in - // another service, then we need to define an "empty - // extend" of that type in this service, so this service - // knows what the type is like. But the graphql-server - // will never ask us to actually resolve this "empty - // extend", so we don't require a resolver function for - // it. (Well, it will never ask in practice; it's - // unclear whether the spec guarantees this. See - // https://github.com/apollographql/apollo-server/issues/3852 - // ). Example: - // type MyType { - // myvar: TypeDefinedInOtherService - // } - // // Federation needs this type, but - // // it doesn't need a resolver for it! - // extend TypeDefinedInOtherService @key(fields: "id") { - // id: ID @external - // } - if !e.allFieldsAreExternal() { - for _, dir := range keys { - if len(dir.Arguments) > 2 { - panic("More than two arguments provided for @key declaration.") - } - var arg *ast.Argument - - // since keys are able to now have multiple arguments, we need to check both possible for a possible @key(fields="" fields="") - for _, a := range dir.Arguments { - if a.Name == "fields" { - if arg != nil { - panic("More than one `fields` provided for @key declaration.") - } - arg = a - } - } + return arg.Value.Raw, nil +} - keyFieldSet := fieldset.New(arg.Value.Raw, nil) +func buildKeyFields( + schemaType *ast.Definition, + schema *ast.Schema, + dir *ast.Directive, +) ([]*KeyField, []string) { + fieldsRaw, err := extractFields(dir) + if err != nil { + panic("More than one `fields` argument provided for declaration.") + } - keyFields := make([]*KeyField, len(keyFieldSet)) - resolverFields := []string{} - for i, field := range keyFieldSet { - def := field.FieldDefinition(schemaType, schema) + keyFieldSet := fieldset.New(fieldsRaw, nil) - if def == nil { - panic(fmt.Sprintf("no field for %v", field)) - } + keyFields := make([]*KeyField, len(keyFieldSet)) + resolverFields := []string{} + for i, field := range keyFieldSet { + def := field.FieldDefinition(schemaType, schema) - keyFields[i] = &KeyField{Definition: def, Field: field} - resolverFields = append(resolverFields, keyFields[i].Field.ToGo()) - } + if def == nil { + panic(fmt.Sprintf("no field for %v", field)) + } - resolverFieldsToGo := schemaType.Name + "By" + strings.Join(resolverFields, "And") - var resolverName string - if e.Multi { - resolverFieldsToGo += "s" // Pluralize for better API readability - resolverName = fmt.Sprintf("findMany%s", resolverFieldsToGo) - } else { - resolverName = fmt.Sprintf("find%s", resolverFieldsToGo) - } + keyFields[i] = &KeyField{Definition: def, Field: field} + resolverFields = append(resolverFields, keyFields[i].Field.ToGo()) + } - e.Resolvers = append(e.Resolvers, &EntityResolver{ - ResolverName: resolverName, - KeyFields: keyFields, - InputType: resolverFieldsToGo + "Input", - }) - } + return keyFields, resolverFields +} - e.Requires = []*Requires{} - for _, f := range schemaType.Fields { - dir := f.Directives.ForName("requires") - if dir == nil { - continue - } - if len(dir.Arguments) != 1 || dir.Arguments[0].Name != "fields" { - panic("Exactly one `fields` argument needed for @requires declaration.") - } - requiresFieldSet := fieldset.New(dir.Arguments[0].Value.Raw, nil) - for _, field := range requiresFieldSet { - e.Requires = append(e.Requires, &Requires{ - Name: field.ToGoPrivate(), - Field: field, - }) - } - } +func buildRequires(schemaType *ast.Definition) []*Requires { + requires := make([]*Requires, 0) + for _, f := range schemaType.Fields { + dir := f.Directives.ForName(dirNameRequires) + if dir == nil { + continue + } + + fieldsRaw, err := extractFields(dir) + if err != nil { + panic("Exactly one `fields` argument needed for @requires declaration.") + } + requiresFieldSet := fieldset.New(fieldsRaw, nil) + for _, field := range requiresFieldSet { + requires = append(requires, &Requires{ + Name: field.ToGoPrivate(), + Field: field, + }) } - f.Entities = append(f.Entities, e) } - // make sure order remains stable across multiple builds - sort.Slice(f.Entities, func(i, j int) bool { - return f.Entities[i].Name < f.Entities[j].Name - }) + return requires } func isFederatedEntity(schemaType *ast.Definition) ([]*ast.Directive, bool) { switch schemaType.Kind { case ast.Object: - keys := schemaType.Directives.ForNames("key") + keys := schemaType.Directives.ForNames(dirNameKey) if len(keys) > 0 { return keys, true } case ast.Interface: - // TODO: support @key and @extends for interfaces - if dir := schemaType.Directives.ForName("key"); dir != nil { - fmt.Printf("@key directive found on \"interface %s\". Will be ignored.\n", schemaType.Name) + keys := schemaType.Directives.ForNames(dirNameKey) + if len(keys) > 0 { + return keys, true } + + // TODO: support @extends for interfaces if dir := schemaType.Directives.ForName("extends"); dir != nil { panic( fmt.Sprintf( @@ -422,3 +621,146 @@ func isFederatedEntity(schemaType *ast.Definition) ([]*ast.Directive, bool) { } return nil, false } + +func (f *Federation) generateExplicitRequires( + data *codegen.Data, + requiresEntities map[string]*Entity, + requiresImports map[string]bool, +) error { + // check for existing requires functions + type Populator struct { + FuncName string + Exists bool + Comment string + Implementation string + Entity *Entity + } + populators := make([]Populator, 0) + + rewriter, err := rewrite.New(data.Config.Federation.Dir()) + if err != nil { + return err + } + + for name, entity := range requiresEntities { + populator := Populator{ + FuncName: fmt.Sprintf("Populate%sRequires", name), + Entity: entity, + } + + populator.Comment = strings.TrimSpace(strings.TrimLeft(rewriter.GetMethodComment("executionContext", populator.FuncName), `\`)) + populator.Implementation = strings.TrimSpace(rewriter.GetMethodBody("executionContext", populator.FuncName)) + + if populator.Implementation == "" { + populator.Exists = false + populator.Implementation = fmt.Sprintf("panic(fmt.Errorf(\"not implemented: %v\"))", populator.FuncName) + } + populators = append(populators, populator) + } + + sort.Slice(populators, func(i, j int) bool { + return populators[i].FuncName < populators[j].FuncName + }) + + requiresFile := data.Config.Federation.Dir() + "/federation.requires.go" + existingImports := rewriter.ExistingImports(requiresFile) + for _, imp := range existingImports { + if imp.Alias == "" { + // import exists in both places, remove + delete(requiresImports, imp.ImportPath) + } + } + + for k := range requiresImports { + existingImports = append(existingImports, rewrite.Import{ImportPath: k}) + } + + // render requires populators + return templates.Render(templates.Options{ + PackageName: data.Config.Federation.Package, + Filename: requiresFile, + Data: struct { + Federation + ExistingImports []rewrite.Import + Populators []Populator + OriginalSource string + }{*f, existingImports, populators, ""}, + GeneratedHeader: false, + Packages: data.Config.Packages, + Template: explicitRequiresTemplate, + }) +} + +func buildResolverSDL( + resolver *EntityResolver, + multi bool, +) (resolverSDL, entityResolverInputSDL string) { + if multi { + entityResolverInputSDL = buildEntityResolverInputDefinitionSDL(resolver) + resolverSDL := fmt.Sprintf("\t%s(reps: [%s]!): [%s]", resolver.ResolverName, resolver.InputTypeName, resolver.ReturnTypeName) + return resolverSDL, entityResolverInputSDL + } + + resolverArgs := "" + for _, keyField := range resolver.KeyFields { + resolverArgs += fmt.Sprintf("%s: %s,", keyField.Field.ToGoPrivate(), keyField.Definition.Type.String()) + } + resolverSDL = fmt.Sprintf("\t%s(%s): %s!", resolver.ResolverName, resolverArgs, resolver.ReturnTypeName) + return resolverSDL, "" +} + +func buildEntityResolverInputDefinitionSDL(resolver *EntityResolver) string { + entityResolverInputDefinition := "input " + resolver.InputTypeName + " {\n" + for _, keyField := range resolver.KeyFields { + entityResolverInputDefinition += fmt.Sprintf( + "\t%s: %s\n", + keyField.Field.ToGo(), + keyField.Definition.Type.String(), + ) + } + return entityResolverInputDefinition + "}" +} + +func (f *Federation) addMapType(cfg *config.Config) { + cfg.Models[mapTypeName] = config.TypeMapEntry{ + Model: config.StringList{"github.com/99designs/gqlgen/graphql.Map"}, + } + cfg.Schema.Types[mapTypeName] = &ast.Definition{ + Kind: ast.Scalar, + Name: mapTypeName, + Description: "Maps an arbitrary GraphQL value to a map[string]any Go type.", + } +} + +func (f *Federation) mutateSchemaForRequires( + schema *ast.Schema, + cfg *config.Config, +) { + for _, schemaType := range schema.Types { + for _, field := range schemaType.Fields { + if dir := field.Directives.ForName(dirNameRequires); dir != nil { + // ensure we always generate a resolver for any @requires field + model := cfg.Models[schemaType.Name] + fieldConfig := model.Fields[field.Name] + fieldConfig.Resolver = true + if model.Fields == nil { + model.Fields = make(map[string]config.TypeMapField) + } + model.Fields[field.Name] = fieldConfig + cfg.Models[schemaType.Name] = model + + requiresArgument := &ast.ArgumentDefinition{ + Name: fieldArgRequires, + Type: ast.NamedType(mapTypeName, nil), + Directives: ast.DirectiveList{ + { + Name: dirNamePopulateFromRepresentations, + Definition: dirPopulateFromRepresentations, + }, + }, + } + field.Arguments = append(field.Arguments, requiresArgument) + } + } + } +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.gotpl b/vendor/github.com/99designs/gqlgen/plugin/federation/federation.gotpl index 4a30b6c97..65e687eab 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/federation.gotpl +++ b/vendor/github.com/99designs/gqlgen/plugin/federation/federation.gotpl @@ -5,6 +5,10 @@ {{ reserveImport "sync" }} {{ reserveImport "github.com/99designs/gqlgen/plugin/federation/fedruntime" }} +{{ $options := .PackageOptions }} +{{ $usePointers := .UsePointers }} + +{{ $useFunctionSyntaxForExecutionContext := .UseFunctionSyntaxForExecutionContext }} var ( ErrUnknownType = errors.New("unknown type") @@ -31,18 +35,53 @@ func (ec *executionContext) __resolve__service(ctx context.Context) (fedruntime. } {{if .Entities}} -func (ec *executionContext) __resolve_entities(ctx context.Context, representations []map[string]interface{}) []fedruntime.Entity { +func (ec *executionContext) __resolve_entities(ctx context.Context, representations []map[string]any) []fedruntime.Entity { list := make([]fedruntime.Entity, len(representations)) - repsMap := map[string]struct { - i []int - r []map[string]interface{} - }{} + repsMap := ec.buildRepresentationGroups(ctx, representations) + + switch len(repsMap) { + case 0: + return list + case 1: + for typeName, reps := range repsMap { + ec.resolveEntityGroup(ctx, typeName, reps, list) + } + return list + default: + var g sync.WaitGroup + g.Add(len(repsMap)) + for typeName, reps := range repsMap { + go func(typeName string, reps []EntityWithIndex) { + ec.resolveEntityGroup(ctx, typeName, reps, list) + g.Done() + }(typeName, reps) + } + g.Wait() + return list + } +} + +type EntityWithIndex struct { + // The index in the original representation array + index int + entity EntityRepresentation +} + +// EntityRepresentation is the JSON representation of an entity sent by the Router +// used as the inputs for us to resolve. +// +// We make it a map because we know the top level JSON is always an object. +type EntityRepresentation map[string]any // We group entities by typename so that we can parallelize their resolution. // This is particularly helpful when there are entity groups in multi mode. - buildRepresentationGroups := func(reps []map[string]interface{}) { - for i, rep := range reps { +func (ec *executionContext) buildRepresentationGroups( + ctx context.Context, + representations []map[string]any, +) map[string][]EntityWithIndex { + repsMap := make(map[string][]EntityWithIndex) + for i, rep := range representations { typeName, ok := rep["__typename"].(string) if !ok { // If there is no __typename, we just skip the representation; @@ -51,14 +90,48 @@ func (ec *executionContext) __resolve_entities(ctx context.Context, representati continue } - _r := repsMap[typeName] - _r.i = append(_r.i, i) - _r.r = append(_r.r, rep) - repsMap[typeName] = _r + repsMap[typeName] = append(repsMap[typeName], EntityWithIndex{ + index: i, + entity: rep, + }) + } + + return repsMap +} + +func (ec *executionContext) resolveEntityGroup( + ctx context.Context, + typeName string, + reps []EntityWithIndex, + list []fedruntime.Entity, +) { + if isMulti(typeName) { + err := ec.resolveManyEntities(ctx, typeName, reps, list) + if err != nil { + ec.Error(ctx, err) } + } else { + // if there are multiple entities to resolve, parallelize (similar to + // graphql.FieldSet.Dispatch) + var e sync.WaitGroup + e.Add(len(reps)) + for i, rep := range reps { + i, rep := i, rep + go func(i int, rep EntityWithIndex) { + entity, err := ec.resolveEntity(ctx, typeName, rep.entity) + if err != nil { + ec.Error(ctx, err) + } else { + list[rep.index] = entity + } + e.Done() + }(i, rep) + } + e.Wait() } +} - isMulti := func(typeName string) bool { +func isMulti(typeName string) bool { switch typeName { {{- range .Entities -}} {{- if .Resolvers -}} @@ -73,7 +146,11 @@ func (ec *executionContext) __resolve_entities(ctx context.Context, representati } } - resolveEntity := func(ctx context.Context, typeName string, rep map[string]interface{}, idx []int, i int) (err error) { +func (ec *executionContext) resolveEntity( + ctx context.Context, + typeName string, + rep EntityRepresentation, +) (e fedruntime.Entity, err error) { // we need to do our own panic handling, because we may be called in a // goroutine, where the usual panic handling can't catch us defer func () { @@ -88,38 +165,59 @@ func (ec *executionContext) __resolve_entities(ctx context.Context, representati case "{{.Def.Name}}": resolverName, err := entityResolverNameFor{{.Def.Name}}(ctx, rep) if err != nil { - return fmt.Errorf(`finding resolver for Entity "{{.Def.Name}}": %w`, err) + return nil, fmt.Errorf(`finding resolver for Entity "{{.Def.Name}}": %w`, err) } switch resolverName { {{ range $i, $resolver := .Resolvers }} case "{{.ResolverName}}": {{- range $j, $keyField := .KeyFields }} - id{{$j}}, err := ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]interface{})["`}}"]) + {{ if $useFunctionSyntaxForExecutionContext -}} + id{{$j}}, err := {{.Type.UnmarshalFunc}}(ctx, ec, rep["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- else -}} + id{{$j}}, err := ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- end }} if err != nil { - return fmt.Errorf(`unmarshalling param {{$j}} for {{$resolver.ResolverName}}(): %w`, err) + return nil, fmt.Errorf(`unmarshalling param {{$j}} for {{$resolver.ResolverName}}(): %w`, err) } {{- end}} entity, err := ec.resolvers.Entity().{{.ResolverName | go}}(ctx, {{- range $j, $_ := .KeyFields -}} id{{$j}}, {{end}}) if err != nil { - return fmt.Errorf(`resolving Entity "{{$entity.Def.Name}}": %w`, err) + return nil, fmt.Errorf(`resolving Entity "{{$entity.Def.Name}}": %w`, err) } - {{ range $entity.Requires }} - entity.{{.Field.JoinGo `.`}}, err = ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]interface{})["`}}"]) + {{- if $options.ComputedRequires }} + {{/* We don't do anything in this case, computed requires are handled by standard resolvers */}} + {{- else if and $options.ExplicitRequires $entity.Requires }} + err = ec.Populate{{$entity.Def.Name}}Requires(ctx, {{- if (not $usePointers) -}}&{{- end -}}entity, rep) if err != nil { - return err + return nil, fmt.Errorf(`populating requires for Entity "{{$entity.Def.Name}}": %w`, err) } + {{- else }} + {{ range $entity.Requires }} + {{ if $useFunctionSyntaxForExecutionContext -}} + entity.{{.Field.JoinGo `.`}}, err = {{.Type.UnmarshalFunc}}(ctx, ec, rep["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- else -}} + entity.{{.Field.JoinGo `.`}}, err = ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- end }} + if err != nil { + return nil, err + } + {{- end }} {{- end }} - list[idx[i]] = entity - return nil + return entity, nil {{- end }} } {{ end }} {{- end }} } - return fmt.Errorf("%w: %s", ErrUnknownType, typeName) + return nil, fmt.Errorf("%w: %s", ErrUnknownType, typeName) } - resolveManyEntities := func(ctx context.Context, typeName string, reps []map[string]interface{}, idx []int) (err error) { +func (ec *executionContext) resolveManyEntities( + ctx context.Context, + typeName string, + reps []EntityWithIndex, + list []fedruntime.Entity, +) (err error) { // we need to do our own panic handling, because we may be called in a // goroutine, where the usual panic handling can't catch us defer func () { @@ -132,92 +230,73 @@ func (ec *executionContext) __resolve_entities(ctx context.Context, representati {{ range $_, $entity := .Entities }} {{ if and .Resolvers .Multi -}} case "{{.Def.Name}}": - {{range $i, $_ := .Resolvers -}} - _reps := make([]*{{.InputType}}, len(reps)) + resolverName, err := entityResolverNameFor{{.Def.Name}}(ctx, reps[0].entity) + if err != nil { + return fmt.Errorf(`finding resolver for Entity "{{.Def.Name}}": %w`, err) + } + switch resolverName { + {{ range $i, $resolver := .Resolvers }} + case "{{.ResolverName}}": + typedReps := make([]*{{.LookupInputType}}, len(reps)) for i, rep := range reps { {{ range $i, $keyField := .KeyFields -}} - id{{$i}}, err := ec.{{.Type.UnmarshalFunc}}(ctx, rep["{{.Field.Join `"].(map[string]interface{})["`}}"]) + {{ if $useFunctionSyntaxForExecutionContext -}} + id{{$i}}, err := {{.Type.UnmarshalFunc}}(ctx, ec, rep.entity["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- else -}} + id{{$i}}, err := ec.{{.Type.UnmarshalFunc}}(ctx, rep.entity["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- end }} if err != nil { return errors.New(fmt.Sprintf("Field %s undefined in schema.", "{{.Definition.Name}}")) } {{end}} - _reps[i] = &{{.InputType}} { + typedReps[i] = &{{.LookupInputType}} { {{ range $i, $keyField := .KeyFields -}} {{$keyField.Field.ToGo}}: id{{$i}}, {{end}} } } - entities, err := ec.resolvers.Entity().{{.ResolverName | go}}(ctx, _reps) + entities, err := ec.resolvers.Entity().{{.ResolverName | go}}(ctx, typedReps) if err != nil { return err } for i, entity := range entities { + {{- if and $.PackageOptions.ExplicitRequires (index $.RequiresEntities $entity.Def.Name) }} + err = ec.Populate{{$entity.Def.Name}}Requires(ctx, {{- if not $usePointers -}}&{{- end -}}entity, reps[i].entity) + if err != nil { + return fmt.Errorf(`populating requires for Entity "{{$entity.Def.Name}}": %w`, err) + } + {{- end }} {{- range $entity.Requires }} - entity.{{.Field.JoinGo `.`}}, err = ec.{{.Type.UnmarshalFunc}}(ctx, reps[i]["{{.Field.Join `"].(map[string]interface{})["`}}"]) + {{- if $options.ComputedRequires }} + {{/* We don't do anything in this case, computed requires are handled by standard resolvers */}} + {{- else if $.PackageOptions.ExplicitRequires }} + {{/* already handled above */}} + {{- else }} + {{ if $useFunctionSyntaxForExecutionContext -}} + entity.{{.Field.JoinGo `.`}}, err = {{.Type.UnmarshalFunc}}(ctx, ec, reps[i].entity["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- else -}} + entity.{{.Field.JoinGo `.`}}, err = ec.{{.Type.UnmarshalFunc}}(ctx, reps[i].entity["{{.Field.Join `"].(map[string]any)["`}}"]) + {{- end }} if err != nil { return err } + {{- end}} {{- end}} - list[idx[i]] = entity + list[reps[i].index] = entity } return nil {{ end }} + default: + return fmt.Errorf("unknown resolver: %s", resolverName) + } {{ end }} {{- end }} default: return errors.New("unknown type: "+typeName) - } - } - - resolveEntityGroup := func(typeName string, reps []map[string]interface{}, idx []int) { - if isMulti(typeName) { - err := resolveManyEntities(ctx, typeName, reps, idx) - if err != nil { - ec.Error(ctx, err) - } - } else { - // if there are multiple entities to resolve, parallelize (similar to - // graphql.FieldSet.Dispatch) - var e sync.WaitGroup - e.Add(len(reps)) - for i, rep := range reps { - i, rep := i, rep - go func(i int, rep map[string]interface{}) { - err := resolveEntity(ctx, typeName, rep, idx, i) - if err != nil { - ec.Error(ctx, err) - } - e.Done() - }(i, rep) - } - e.Wait() - } - } - buildRepresentationGroups(representations) - - switch len(repsMap) { - case 0: - return list - case 1: - for typeName, reps := range repsMap { - resolveEntityGroup(typeName, reps.r, reps.i) - } - return list - default: - var g sync.WaitGroup - g.Add(len(repsMap)) - for typeName, reps := range repsMap { - go func(typeName string, reps []map[string]interface{}, idx []int) { - resolveEntityGroup(typeName, reps, idx) - g.Done() - }(typeName, reps.r, reps.i) - } - g.Wait() - return list } } @@ -226,32 +305,54 @@ func (ec *executionContext) __resolve_entities(ctx context.Context, representati {{ range $_, $entity := .Entities }} {{- if .Resolvers }} - func entityResolverNameFor{{$entity.Name}}(ctx context.Context, rep map[string]interface{}) (string, error) { + func entityResolverNameFor{{$entity.Name}}(ctx context.Context, rep EntityRepresentation) (string, error) { + // we collect errors because a later entity resolver may work fine + // when an entity has multiple keys + entityResolverErrs := []error{} {{- range .Resolvers }} for { var ( - m map[string]interface{} - val interface{} - ok bool + m EntityRepresentation + val any + ok bool ) _ = val + // if all of the KeyFields values for this resolver are null, + // we shouldn't use use it + allNull := true {{- range $_, $keyField := .KeyFields }} m = rep {{- range $i, $field := .Field }} - if {{ if (ne $i $keyField.Field.LastIndex ) -}}val{{- else -}}_{{- end -}}, ok = m["{{.}}"]; !ok { + val, ok = m["{{.}}"] + if !ok { + entityResolverErrs = append(entityResolverErrs, + fmt.Errorf("%w due to missing Key Field \"{{.}}\" for {{$entity.Name}}", ErrTypeNotFound)) break } {{- if (ne $i $keyField.Field.LastIndex ) }} - if m, ok = val.(map[string]interface{}); !ok { + if m, ok = val.(map[string]any); !ok { + // nested field value is not a map[string]interface so don't use it + entityResolverErrs = append(entityResolverErrs, + fmt.Errorf("%w due to nested Key Field \"{{.}}\" value not matching map[string]any for {{$entity.Name}}", ErrTypeNotFound)) break } + {{- else}} + if allNull { + allNull = val == nil + } {{- end}} {{- end}} {{- end }} + if allNull { + entityResolverErrs = append(entityResolverErrs, + fmt.Errorf("%w due to all null value KeyFields for {{$entity.Name}}", ErrTypeNotFound)) + break + } return "{{.ResolverName}}", nil } {{- end }} - return "", fmt.Errorf("%w for {{$entity.Name}}", ErrTypeNotFound) + return "", fmt.Errorf("%w for {{$entity.Name}} due to %v", ErrTypeNotFound, + errors.Join(entityResolverErrs...).Error()) } {{- end }} {{- end }} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/fieldset/fieldset.go b/vendor/github.com/99designs/gqlgen/plugin/federation/fieldset/fieldset.go index 059a3c832..65b32eae2 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/fieldset/fieldset.go +++ b/vendor/github.com/99designs/gqlgen/plugin/federation/fieldset/fieldset.go @@ -4,9 +4,10 @@ import ( "fmt" "strings" + "github.com/vektah/gqlparser/v2/ast" + "github.com/99designs/gqlgen/codegen" "github.com/99designs/gqlgen/codegen/templates" - "github.com/vektah/gqlparser/v2/ast" ) // Set represents a FieldSet that is used in federation directives @key and @requires. @@ -99,6 +100,7 @@ func (f Field) ToGoPrivate() string { for i, field := range f { if i == 0 { + field = trimArgumentFromFieldName(field) ret += templates.ToGoPrivate(field) continue } @@ -131,9 +133,23 @@ func (f Field) LastIndex() int { // parseUnnestedKeyFieldSet // handles simple case where none of the fields are nested. func parseUnnestedKeyFieldSet(raw string, prefix []string) Set { ret := Set{} + unionField := false for _, s := range strings.Fields(raw) { - next := append(prefix[:], s) //nolint:gocritic // slicing out on purpose + if s == "..." { + continue + } + if s == "on" { + unionField = true + continue + } + + if unionField { + s = "... on " + s + unionField = false + } + + next := append(prefix[0:len(prefix):len(prefix)], s) //nolint:gocritic // set cap=len in order to force slice reallocation ret = append(ret, next) } return ret @@ -147,7 +163,7 @@ func extractSubs(str string) (string, string, string) { if start < 0 || end < 0 { panic("invalid key fieldSet: " + str) } - return strings.TrimSpace(str[:start]), strings.TrimSpace(str[start+1 : end]), strings.TrimSpace(str[end+1:]) + return trimArgumentFromFieldName(strings.TrimSpace(str[:start])), strings.TrimSpace(str[start+1 : end]), strings.TrimSpace(str[end+1:]) } // matchingBracketIndex returns the index of the closing bracket, assuming an open bracket at start. @@ -173,9 +189,16 @@ func matchingBracketIndex(str string, start int) int { func fieldByName(obj *codegen.Object, name string) *codegen.Field { for _, field := range obj.Fields { + field.Name = trimArgumentFromFieldName(field.Name) if field.Name == name { return field } } return nil } + +// trimArgumentFromFieldName removes any arguments from the field name. +// It removes any suffixes from the raw string, starting from the argument-open character `(` +func trimArgumentFromFieldName(raw string) string { + return strings.Split(raw, "(")[0] +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/readme.md b/vendor/github.com/99designs/gqlgen/plugin/federation/readme.md index 4333ed479..e8888c1ce 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/federation/readme.md +++ b/vendor/github.com/99designs/gqlgen/plugin/federation/readme.md @@ -18,7 +18,7 @@ TODO(miguel): add details. # Entity resolvers - GetMany entities -The federation plugin implements `GetMany` semantics in which entity resolvers get the entire list of representations that need to be resolved. This functionality is currently optin tho, and to enable it you need to specify the directive `@entityResolver` in the federated entity you want this feature for. E.g. +The federation plugin implements `GetMany` semantics in which entity resolvers get the entire list of representations that need to be resolved. This functionality is currently option tho, and to enable it you need to specify the directive `@entityResolver` in the federated entity you want this feature for. E.g. ``` directive @entityResolver(multi: Boolean) on OBJECT @@ -37,3 +37,6 @@ func (r *entityResolver) FindManyMultiHellosByName(ctx context.Context, reps []* /// } ``` + +**Note:** +If you are using `omit_slice_element_pointers: true` option in your config yaml, your `GetMany` resolver will still generate in the example above the same signature `FindManyMultiHellosByName(ctx context.Context, reps []*generated.ManyMultiHellosByNameInput) ([]*generated.MultiHello, error)`. But all other instances will continue to honor `omit_slice_element_pointers: true` diff --git a/vendor/github.com/99designs/gqlgen/plugin/federation/requires.gotpl b/vendor/github.com/99designs/gqlgen/plugin/federation/requires.gotpl new file mode 100644 index 000000000..64d8b7960 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/plugin/federation/requires.gotpl @@ -0,0 +1,20 @@ +{{ range .ExistingImports }} +{{ if ne .Alias "" }} +{{ reserveImport .ImportPath .Alias }} +{{ else }} +{{ reserveImport .ImportPath }} +{{ end }} +{{ end }} + +{{ range .Populators -}} +{{ if .Comment -}} +// {{.Comment}} +{{- else -}} +// {{.FuncName}} is the requires populator for the {{.Entity.Def.Name}} entity. +{{- end }} +func (ec *executionContext) {{.FuncName}}(ctx context.Context, entity *{{.Entity.GetTypeInfo}}, reps map[string]any) error { + {{.Implementation}} +} +{{ end }} + +{{ .OriginalSource }} diff --git a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.go b/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.go index 45c32715c..f5af21ad4 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.go +++ b/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.go @@ -4,29 +4,33 @@ import ( _ "embed" "fmt" "go/types" + "os" "sort" "strings" "text/template" + "github.com/vektah/gqlparser/v2/ast" + "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/codegen/templates" "github.com/99designs/gqlgen/plugin" - "github.com/vektah/gqlparser/v2/ast" ) //go:embed models.gotpl var modelTemplate string -type BuildMutateHook = func(b *ModelBuild) *ModelBuild - -type FieldMutateHook = func(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) +type ( + BuildMutateHook = func(b *ModelBuild) *ModelBuild + FieldMutateHook = func(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) +) -// defaultFieldMutateHook is the default hook for the Plugin which applies the GoTagFieldHook. -func defaultFieldMutateHook(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) { +// DefaultFieldMutateHook is the default hook for the Plugin which applies the GoFieldHook and GoTagFieldHook. +func DefaultFieldMutateHook(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) { return GoTagFieldHook(td, fd, f) } -func defaultBuildMutateHook(b *ModelBuild) *ModelBuild { +// DefaultBuildMutateHook is the default hook for the Plugin which mutate ModelBuild. +func DefaultBuildMutateHook(b *ModelBuild) *ModelBuild { return b } @@ -43,6 +47,8 @@ type Interface struct { Name string Fields []*Field Implements []string + OmitCheck bool + Models []*Object } type Object struct { @@ -57,9 +63,11 @@ type Field struct { // Name is the field's name as it appears in the schema Name string // GoName is the field's name as it appears in the generated Go code - GoName string - Type types.Type - Tag string + GoName string + Type types.Type + Tag string + IsResolver bool + Omittable bool } type Enum struct { @@ -75,8 +83,8 @@ type EnumValue struct { func New() plugin.Plugin { return &Plugin{ - MutateHook: defaultBuildMutateHook, - FieldHook: defaultFieldMutateHook, + MutateHook: DefaultBuildMutateHook, + FieldHook: DefaultFieldMutateHook, } } @@ -92,7 +100,6 @@ func (m *Plugin) Name() string { } func (m *Plugin) MutateConfig(cfg *config.Config) error { - b := &ModelBuild{ PackageName: cfg.Model.Package, } @@ -117,11 +124,23 @@ func (m *Plugin) MutateConfig(cfg *config.Config) error { Name: schemaType.Name, Implements: schemaType.Interfaces, Fields: fields, + OmitCheck: cfg.OmitInterfaceChecks, + } + + // if the interface has a key directive as an entity interface, allow it to implement _Entity + if schemaType.Directives.ForName("key") != nil { + it.Implements = append(it.Implements, "_Entity") } b.Interfaces = append(b.Interfaces, it) case ast.Object, ast.InputObject: - if schemaType == cfg.Schema.Query || schemaType == cfg.Schema.Mutation || schemaType == cfg.Schema.Subscription { + if cfg.IsRoot(schemaType) { + if !cfg.OmitRootModels { + b.Models = append(b.Models, &Object{ + Description: schemaType.Description, + Name: schemaType.Name, + }) + } continue } @@ -190,6 +209,18 @@ func (m *Plugin) MutateConfig(cfg *config.Config) error { cfg.Models.Add(it.Name, cfg.Model.ImportPath()+"."+templates.ToGo(it.Name)) } for _, it := range b.Interfaces { + // On a given interface we want to keep a reference to all the models that implement it + for _, model := range b.Models { + for _, impl := range model.Implements { + if impl == it.Name { + // check if this isn't an implementation of an entity interface + if impl != "_Entity" { + // If this model has an implementation, add it to the Interface's Models + it.Models = append(it.Models, model) + } + } + } + } cfg.Models.Add(it.Name, cfg.Model.ImportPath()+"."+templates.ToGo(it.Name)) } for _, it := range b.Scalars { @@ -256,23 +287,26 @@ func (m *Plugin) MutateConfig(cfg *config.Config) error { getter += "\treturn interfaceSlice\n" getter += "}" return getter - } else { - getter := fmt.Sprintf("func (this %s) Get%s() %s { return ", templates.ToGo(model.Name), field.GoName, goType) - - if interfaceFieldTypeIsPointer && !structFieldTypeIsPointer { - getter += "&" - } else if !interfaceFieldTypeIsPointer && structFieldTypeIsPointer { - getter += "*" - } + } + getter := fmt.Sprintf("func (this %s) Get%s() %s { return ", templates.ToGo(model.Name), field.GoName, goType) - getter += fmt.Sprintf("this.%s }", field.GoName) - return getter + if interfaceFieldTypeIsPointer && !structFieldTypeIsPointer { + getter += "&" + } else if !interfaceFieldTypeIsPointer && structFieldTypeIsPointer { + getter += "*" } + + getter += fmt.Sprintf("this.%s }", field.GoName) + return getter } funcMap := template.FuncMap{ "getInterfaceByName": getInterfaceByName, "generateGetter": generateGetter, } + newModelTemplate := modelTemplate + if cfg.Model.ModelTemplate != "" { + newModelTemplate = readModelTemplate(cfg.Model.ModelTemplate) + } err := templates.Render(templates.Options{ PackageName: cfg.Model.Package, @@ -280,7 +314,7 @@ func (m *Plugin) MutateConfig(cfg *config.Config) error { Data: b, GeneratedHeader: true, Packages: cfg.Packages, - Template: modelTemplate, + Template: newModelTemplate, Funcs: funcMap, }) if err != nil { @@ -299,91 +333,224 @@ func (m *Plugin) generateFields(cfg *config.Config, schemaType *ast.Definition) fields := make([]*Field, 0) for _, field := range schemaType.Fields { - var typ types.Type - fieldDef := cfg.Schema.Types[field.Type.Name()] + f, err := m.generateField(cfg, binder, schemaType, field) + if err != nil { + return nil, err + } - if cfg.Models.UserDefined(field.Type.Name()) { - var err error - typ, err = binder.FindTypeFromName(cfg.Models[field.Type.Name()].Model[0]) - if err != nil { - return nil, err - } - } else { - switch fieldDef.Kind { - case ast.Scalar: - // no user defined model, referencing a default scalar - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), "string", nil), - nil, - nil, - ) - - case ast.Interface, ast.Union: - // no user defined model, referencing a generated interface type - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), - types.NewInterfaceType([]*types.Func{}, []types.Type{}), - nil, - ) - - case ast.Enum: - // no user defined model, must reference a generated enum - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), - nil, - nil, - ) - - case ast.Object, ast.InputObject: - // no user defined model, must reference a generated struct - typ = types.NewNamed( - types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), - types.NewStruct(nil, nil), - nil, - ) - - default: - panic(fmt.Errorf("unknown ast type %s", fieldDef.Kind)) - } + if f == nil { + continue + } + + fields = append(fields, f) + } + + fields = append(fields, getExtraFields(cfg, schemaType.Name)...) + + return fields, nil +} + +func (m *Plugin) generateField( + cfg *config.Config, + binder *config.Binder, + schemaType *ast.Definition, + field *ast.FieldDefinition, +) (*Field, error) { + var typ types.Type + fieldDef := cfg.Schema.Types[field.Type.Name()] + + if cfg.Models.UserDefined(field.Type.Name()) { + var err error + typ, err = binder.FindTypeFromName(cfg.Models[field.Type.Name()].Model[0]) + if err != nil { + return nil, err } + } else { + switch fieldDef.Kind { + case ast.Scalar: + // no user defined model, referencing a default scalar + typ = types.NewNamed( + types.NewTypeName(0, cfg.Model.Pkg(), "string", nil), + nil, + nil, + ) + + case ast.Interface, ast.Union: + // no user defined model, referencing a generated interface type + typ = types.NewNamed( + types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), + types.NewInterfaceType([]*types.Func{}, []types.Type{}), + nil, + ) + + case ast.Enum: + // no user defined model, must reference a generated enum + typ = types.NewNamed( + types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), + nil, + nil, + ) - name := templates.ToGo(field.Name) - if nameOveride := cfg.Models[schemaType.Name].Fields[field.Name].FieldName; nameOveride != "" { - name = nameOveride + case ast.Object, ast.InputObject: + // no user defined model, must reference a generated struct + typ = types.NewNamed( + types.NewTypeName(0, cfg.Model.Pkg(), templates.ToGo(field.Type.Name()), nil), + types.NewStruct(nil, nil), + nil, + ) + + default: + panic(fmt.Errorf("unknown ast type %s", fieldDef.Kind)) } + } - typ = binder.CopyModifiersFromAst(field.Type, typ) + name := templates.ToGo(field.Name) + if nameOverride := cfg.Models[schemaType.Name].Fields[field.Name].FieldName; nameOverride != "" { + name = nameOverride + } - if cfg.StructFieldsAlwaysPointers { - if isStruct(typ) && (fieldDef.Kind == ast.Object || fieldDef.Kind == ast.InputObject) { - typ = types.NewPointer(typ) - } + typ = binder.CopyModifiersFromAst(field.Type, typ) + + if cfg.StructFieldsAlwaysPointers { + if isStruct(typ) && (fieldDef.Kind == ast.Object || fieldDef.Kind == ast.InputObject) { + typ = types.NewPointer(typ) + } + } + + // Replace to user-defined field type if provided. + if userDefinedType := cfg.Models[schemaType.Name].Fields[field.Name].Type; userDefinedType != "" { + typ = buildType(userDefinedType) + } + + f := &Field{ + Name: field.Name, + GoName: name, + Type: typ, + Description: field.Description, + Tag: getStructTagFromField(cfg, field), + Omittable: cfg.NullableInputOmittable && schemaType.Kind == ast.InputObject && !field.Type.NonNull, + IsResolver: cfg.Models[schemaType.Name].Fields[field.Name].Resolver, + } + + if omittable := cfg.Models[schemaType.Name].Fields[field.Name].Omittable; omittable != nil { + f.Omittable = *omittable + } + + if m.FieldHook != nil { + mf, err := m.FieldHook(schemaType, field, f) + if err != nil { + return nil, fmt.Errorf("generror: field %v.%v: %w", schemaType.Name, field.Name, err) } - f := &Field{ - Name: field.Name, - GoName: name, - Type: typ, - Description: field.Description, - Tag: `json:"` + field.Name + `"`, + if mf == nil { + // the field hook wants to omit the field + return nil, nil } - if m.FieldHook != nil { - mf, err := m.FieldHook(schemaType, field, f) - if err != nil { - return nil, fmt.Errorf("generror: field %v.%v: %w", schemaType.Name, field.Name, err) - } - f = mf + f = mf + } + + if f.IsResolver && cfg.OmitResolverFields { + return nil, nil + } + + if f.Omittable { + if schemaType.Kind != ast.InputObject || field.Type.NonNull { + return nil, fmt.Errorf("generror: field %v.%v: omittable is only applicable to nullable input fields", schemaType.Name, field.Name) } - fields = append(fields, f) + omittableType, err := binder.FindTypeFromName("github.com/99designs/gqlgen/graphql.Omittable") + if err != nil { + return nil, err + } + + f.Type, err = binder.InstantiateType(omittableType, []types.Type{f.Type}) + if err != nil { + return nil, fmt.Errorf("generror: field %v.%v: %w", schemaType.Name, field.Name, err) + } } - return fields, nil + return f, nil } -// GoTagFieldHook applies the goTag directive to the generated Field f. When applying the Tag to the field, the field -// name is used when no value argument is present. +func getExtraFields(cfg *config.Config, modelName string) []*Field { + modelcfg := cfg.Models[modelName] + + extraFieldsCount := len(modelcfg.ExtraFields) + len(modelcfg.EmbedExtraFields) + if extraFieldsCount == 0 { + return nil + } + + extraFields := make([]*Field, 0, extraFieldsCount) + + makeExtraField := func(fname string, fspec config.ModelExtraField) *Field { + ftype := buildType(fspec.Type) + + tag := `json:"-"` + if fspec.OverrideTags != "" { + tag = fspec.OverrideTags + } + + return &Field{ + Name: fname, + GoName: fname, + Type: ftype, + Description: fspec.Description, + Tag: tag, + } + } + + if len(modelcfg.ExtraFields) > 0 { + for fname, fspec := range modelcfg.ExtraFields { + extraFields = append(extraFields, makeExtraField(fname, fspec)) + } + } + + if len(modelcfg.EmbedExtraFields) > 0 { + for _, fspec := range modelcfg.EmbedExtraFields { + extraFields = append(extraFields, makeExtraField("", fspec)) + } + } + + sort.Slice(extraFields, func(i, j int) bool { + if extraFields[i].Name == "" && extraFields[j].Name == "" { + return extraFields[i].Type.String() < extraFields[j].Type.String() + } + + if extraFields[i].Name == "" { + return false + } + + if extraFields[j].Name == "" { + return true + } + + return extraFields[i].Name < extraFields[j].Name + }) + + return extraFields +} + +func getStructTagFromField(cfg *config.Config, field *ast.FieldDefinition) string { + var tags []string + + if !field.Type.NonNull && (cfg.EnableModelJsonOmitemptyTag == nil || *cfg.EnableModelJsonOmitemptyTag) { + tags = append(tags, "omitempty") + } + + if !field.Type.NonNull && (cfg.EnableModelJsonOmitzeroTag == nil || *cfg.EnableModelJsonOmitzeroTag) { + tags = append(tags, "omitzero") + } + + if len(tags) > 0 { + return `json:"` + field.Name + `,` + strings.Join(tags, ",") + `"` + } + return `json:"` + field.Name + `"` +} + +// GoTagFieldHook prepends the goTag directive to the generated Field f. +// When applying the Tag to the field, the field +// name is used if no value argument is present. func GoTagFieldHook(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) { args := make([]string, 0) for _, goTag := range fd.Directives.ForNames("goTag") { @@ -406,9 +573,105 @@ func GoTagFieldHook(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Fie } if len(args) > 0 { - f.Tag = f.Tag + " " + strings.Join(args, " ") + f.Tag = removeDuplicateTags(f.Tag + " " + strings.Join(args, " ")) + } + + return f, nil +} + +// splitTagsBySpace split tags by space, except when space is inside quotes +func splitTagsBySpace(tagsString string) []string { + var tags []string + var currentTag string + inQuotes := false + + for _, c := range tagsString { + if c == '"' { + inQuotes = !inQuotes + } + if c == ' ' && !inQuotes { + tags = append(tags, currentTag) + currentTag = "" + } else { + currentTag += string(c) + } + } + tags = append(tags, currentTag) + + return tags +} + +// containsInvalidSpace checks if the tagsString contains invalid space +func containsInvalidSpace(valuesString string) bool { + // get rid of quotes + valuesString = strings.ReplaceAll(valuesString, "\"", "") + if strings.Contains(valuesString, ",") { + // split by comma, + values := strings.Split(valuesString, ",") + for _, value := range values { + if strings.TrimSpace(value) != value { + return true + } + } + return false + } + if strings.Contains(valuesString, ";") { + // split by semicolon, which is common in gorm + values := strings.Split(valuesString, ";") + for _, value := range values { + if strings.TrimSpace(value) != value { + return true + } + } + return false + } + // single value + if strings.TrimSpace(valuesString) != valuesString { + return true } + return false +} + +func removeDuplicateTags(t string) string { + processed := make(map[string]bool) + tt := splitTagsBySpace(t) + returnTags := "" + + // iterate backwards through tags so appended goTag directives are prioritized + for i := len(tt) - 1; i >= 0; i-- { + ti := tt[i] + // check if ti contains ":", and not contains any empty space. if not, tag is in wrong format + // correct example: json:"name" + if !strings.Contains(ti, ":") { + panic(fmt.Errorf("wrong format of tags: %s. goTag directive should be in format: @goTag(key: \"something\", value:\"value\"), ", t)) + } + + kv := strings.Split(ti, ":") + if len(kv) == 0 || processed[kv[0]] { + continue + } + + key := kv[0] + value := strings.Join(kv[1:], ":") + processed[key] = true + if returnTags != "" { + returnTags = " " + returnTags + } + + isContained := containsInvalidSpace(value) + if isContained { + panic(fmt.Errorf("tag value should not contain any leading or trailing spaces: %s", value)) + } + + returnTags = key + ":" + value + returnTags + } + + return returnTags +} +// GoFieldHook is a noop +// TODO: This will be removed in the next breaking release +func GoFieldHook(td *ast.Definition, fd *ast.FieldDefinition, f *Field) (*Field, error) { return f, nil } @@ -468,3 +731,11 @@ func findAndHandleCyclicalRelationships(b *ModelBuild) { } } } + +func readModelTemplate(customModelTemplate string) string { + contentBytes, err := os.ReadFile(customModelTemplate) + if err != nil { + panic(err) + } + return string(contentBytes) +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.gotpl b/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.gotpl index 7ad43bef1..5ce295d41 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.gotpl +++ b/vendor/github.com/99designs/gqlgen/plugin/modelgen/models.gotpl @@ -15,10 +15,12 @@ {{- range $model := .Interfaces }} {{ with .Description }} {{.|prefixLines "// "}} {{ end }} type {{ goModelName .Name }} interface { - {{- range $impl := .Implements }} - Is{{ goModelName $impl }}() + {{- if not .OmitCheck }} + {{- range $impl := .Implements }} + Is{{ goModelName $impl }}() + {{- end }} + Is{{ goModelName .Name }}() {{- end }} - Is{{ goModelName .Name }}() {{- range $field := .Fields }} {{- with .Description }} {{.|prefixLines "// "}} @@ -82,7 +84,7 @@ return string(e) } - func (e *{{ goModelName .Name }}) UnmarshalGQL(v interface{}) error { + func (e *{{ goModelName .Name }}) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") @@ -99,4 +101,18 @@ fmt.Fprint(w, strconv.Quote(e.String())) } + func (e *{{ goModelName .Name }})UnmarshalJSON(b []byte) error { + s, err := strconv.Unquote(string(b)) + if err != nil { + return err + } + return e.UnmarshalGQL(s) + } + + func (e {{ goModelName .Name }}) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + e.MarshalGQL(&buf) + return buf.Bytes(), nil + } + {{- end }} diff --git a/vendor/github.com/99designs/gqlgen/plugin/modelgen/types.go b/vendor/github.com/99designs/gqlgen/plugin/modelgen/types.go new file mode 100644 index 000000000..329269340 --- /dev/null +++ b/vendor/github.com/99designs/gqlgen/plugin/modelgen/types.go @@ -0,0 +1,47 @@ +package modelgen + +import ( + "go/types" + "strings" +) + +// buildType constructs a types.Type for the given string (using the syntax +// from the extra field config Type field). +func buildType(typeString string) types.Type { + switch { + case typeString[0] == '*': + return types.NewPointer(buildType(typeString[1:])) + case strings.HasPrefix(typeString, "[]"): + return types.NewSlice(buildType(typeString[2:])) + default: + return buildNamedType(typeString) + } +} + +// buildNamedType returns the specified named or builtin type. +// +// Note that we don't look up the full types.Type object from the appropriate +// package -- gqlgen doesn't give us the package-map we'd need to do so. +// Instead we construct a placeholder type that has all the fields gqlgen +// wants. This is roughly what gqlgen itself does, anyway: +// https://github.com/99designs/gqlgen/blob/master/plugin/modelgen/models.go#L119 +func buildNamedType(fullName string) types.Type { + dotIndex := strings.LastIndex(fullName, ".") + if dotIndex == -1 { // builtinType + return types.Universe.Lookup(fullName).Type() + } + + // type is pkg.Name + pkgPath := fullName[:dotIndex] + typeName := fullName[dotIndex+1:] + + pkgName := pkgPath + slashIndex := strings.LastIndex(pkgPath, "/") + if slashIndex != -1 { + pkgName = pkgPath[slashIndex+1:] + } + + pkg := types.NewPackage(pkgPath, pkgName) + // gqlgen doesn't use some of the fields, so we leave them 0/nil + return types.NewNamed(types.NewTypeName(0, pkg, typeName, nil), nil, nil) +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/plugin.go b/vendor/github.com/99designs/gqlgen/plugin/plugin.go index 7de36bd8c..f127e75ec 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/plugin.go +++ b/vendor/github.com/99designs/gqlgen/plugin/plugin.go @@ -3,15 +3,23 @@ package plugin import ( + "github.com/vektah/gqlparser/v2/ast" + "github.com/99designs/gqlgen/codegen" "github.com/99designs/gqlgen/codegen/config" - "github.com/vektah/gqlparser/v2/ast" ) type Plugin interface { Name() string } +// SchemaMutator is used to modify the schema before it is used to generate code +// Similarly to [ConfigMutator] that is also triggered before code generation, SchemaMutator +// can be used to modify the schema even before the models are generated. +type SchemaMutator interface { + MutateSchema(schema *ast.Schema) error +} + type ConfigMutator interface { MutateConfig(cfg *config.Config) error } @@ -21,11 +29,28 @@ type CodeGenerator interface { } // EarlySourceInjector is used to inject things that are required for user schema files to compile. +// Deprecated: Use EarlySourcesInjector instead type EarlySourceInjector interface { InjectSourceEarly() *ast.Source } +// EarlySourcesInjector is used to inject things that are required for user schema files to compile. +type EarlySourcesInjector interface { + InjectSourcesEarly() ([]*ast.Source, error) +} + // LateSourceInjector is used to inject more sources, after we have loaded the users schema. +// Deprecated: Use LateSourcesInjector instead type LateSourceInjector interface { InjectSourceLate(schema *ast.Schema) *ast.Source } + +// ResolverImplementer is used to generate code inside resolvers +type ResolverImplementer interface { + Implement(prevImplementation string, field *codegen.Field) string +} + +// LateSourcesInjector is used to inject more sources, after we have loaded the users schema. +type LateSourcesInjector interface { + InjectSourcesLate(schema *ast.Schema) ([]*ast.Source, error) +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.go b/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.go index aa3be7273..4aec30719 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.go +++ b/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.go @@ -4,18 +4,20 @@ import ( _ "embed" "errors" "fmt" - "io/fs" + "go/ast" "os" "path/filepath" "strings" + "golang.org/x/text/cases" + "golang.org/x/text/language" + "github.com/99designs/gqlgen/codegen" "github.com/99designs/gqlgen/codegen/config" "github.com/99designs/gqlgen/codegen/templates" + "github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/internal/rewrite" "github.com/99designs/gqlgen/plugin" - "golang.org/x/text/cases" - "golang.org/x/text/language" ) //go:embed resolver.gotpl @@ -42,6 +44,7 @@ func (m *Plugin) GenerateCode(data *codegen.Data) error { case config.LayoutSingleFile: return m.generateSingleFile(data) case config.LayoutFollowSchema: + return m.generatePerSchema(data) } @@ -51,39 +54,76 @@ func (m *Plugin) GenerateCode(data *codegen.Data) error { func (m *Plugin) generateSingleFile(data *codegen.Data) error { file := File{} - if _, err := os.Stat(data.Config.Resolver.Filename); err == nil { - // file already exists and we dont support updating resolvers with layout = single so just return + if fileExists(data.Config.Resolver.Filename) && + data.Config.Resolver.PreserveResolver { + // file already exists and config says not to update resolver + // so just return return nil } + rewriter, err := rewrite.New(data.Config.Resolver.Dir()) + if err != nil { + return err + } + for _, o := range data.Objects { if o.HasResolvers() { + caser := cases.Title(language.English, cases.NoLower) + rewriter.MarkStructCopied(templates.LcFirst(o.Name) + templates.UcFirst(data.Config.Resolver.Type)) + rewriter.GetMethodBody(data.Config.Resolver.Type, caser.String(o.Name)) + file.Objects = append(file.Objects, o) } + for _, f := range o.Fields { if !f.IsResolver { continue } - resolver := Resolver{o, f, "// foo", `panic("not implemented")`} - file.Resolvers = append(file.Resolvers, &resolver) + structName := templates.LcFirst(o.Name) + templates.UcFirst(data.Config.Resolver.Type) + comment := strings.TrimSpace(strings.TrimLeft(rewriter.GetMethodComment(structName, f.GoFieldName), `\`)) + implementation := strings.TrimSpace(rewriter.GetMethodBody(structName, f.GoFieldName)) + if implementation != "" { + resolver := Resolver{o, f, rewriter.GetPrevDecl(structName, f.GoFieldName), comment, implementation, nil} + file.Resolvers = append(file.Resolvers, &resolver) + } else { + resolver := Resolver{o, f, nil, "", `panic("not implemented")`, nil} + file.Resolvers = append(file.Resolvers, &resolver) + } } } + if fileExists(data.Config.Resolver.Filename) { + file.name = data.Config.Resolver.Filename + file.imports = rewriter.ExistingImports(file.name) + file.RemainingSource = rewriter.RemainingSource(file.name) + } + resolverBuild := &ResolverBuild{ - File: &file, - PackageName: data.Config.Resolver.Package, - ResolverType: data.Config.Resolver.Type, - HasRoot: true, + File: &file, + PackageName: data.Config.Resolver.Package, + ResolverType: data.Config.Resolver.Type, + HasRoot: true, + OmitTemplateComment: data.Config.Resolver.OmitTemplateComment, + } + + newResolverTemplate := resolverTemplate + if data.Config.Resolver.ResolverTemplate != "" { + newResolverTemplate = readResolverTemplate(data.Config.Resolver.ResolverTemplate) + } + + fileNotice := `// THIS CODE WILL BE UPDATED WITH SCHEMA CHANGES. PREVIOUS IMPLEMENTATION FOR SCHEMA CHANGES WILL BE KEPT IN THE COMMENT SECTION. IMPLEMENTATION FOR UNCHANGED SCHEMA WILL BE KEPT.` + if data.Config.Resolver.PreserveResolver { + fileNotice = `// THIS CODE IS A STARTING POINT ONLY. IT WILL NOT BE UPDATED WITH SCHEMA CHANGES.` } return templates.Render(templates.Options{ PackageName: data.Config.Resolver.Package, - FileNotice: `// THIS CODE IS A STARTING POINT ONLY. IT WILL NOT BE UPDATED WITH SCHEMA CHANGES.`, + FileNotice: fileNotice, Filename: data.Config.Resolver.Filename, Data: resolverBuild, Packages: data.Config.Packages, - Template: resolverTemplate, + Template: newResolverTemplate, }) } @@ -101,9 +141,12 @@ func (m *Plugin) generatePerSchema(data *codegen.Data) error { for _, o := range objects { if o.HasResolvers() { - fn := gqlToResolverName(data.Config.Resolver.Dir(), o.Position.Src.Name, data.Config.Resolver.FilenameTemplate) + fnCase := gqlToResolverName(data.Config.Resolver.Dir(), o.Position.Src.Name, data.Config.Resolver.FilenameTemplate) + fn := strings.ToLower(fnCase) if files[fn] == nil { - files[fn] = &File{} + files[fn] = &File{ + name: fnCase, + } } caser := cases.Title(language.English, cases.NoLower) @@ -115,55 +158,91 @@ func (m *Plugin) generatePerSchema(data *codegen.Data) error { if !f.IsResolver { continue } - structName := templates.LcFirst(o.Name) + templates.UcFirst(data.Config.Resolver.Type) - implementation := strings.TrimSpace(rewriter.GetMethodBody(structName, f.GoFieldName)) + // TODO(steve): Why do we need to trimLeft "\" here? Some bazel thing? comment := strings.TrimSpace(strings.TrimLeft(rewriter.GetMethodComment(structName, f.GoFieldName), `\`)) - if implementation == "" { - implementation = fmt.Sprintf("panic(fmt.Errorf(\"not implemented: %v - %v\"))", f.GoFieldName, f.Name) - } - if comment == "" { - comment = fmt.Sprintf("%v is the resolver for the %v field.", f.GoFieldName, f.Name) + implementation := strings.TrimSpace(rewriter.GetMethodBody(structName, f.GoFieldName)) + resolver := Resolver{o, f, rewriter.GetPrevDecl(structName, f.GoFieldName), comment, implementation, nil} + var implExists bool + for _, p := range data.Plugins { + rImpl, ok := p.(plugin.ResolverImplementer) + if !ok { + continue + } + if implExists { + return errors.New("multiple plugins implement ResolverImplementer") + } + implExists = true + resolver.ImplementationRender = rImpl.Implement } - - resolver := Resolver{o, f, comment, implementation} - fn := gqlToResolverName(data.Config.Resolver.Dir(), f.Position.Src.Name, data.Config.Resolver.FilenameTemplate) + fnCase := gqlToResolverName(data.Config.Resolver.Dir(), f.Position.Src.Name, data.Config.Resolver.FilenameTemplate) + fn := strings.ToLower(fnCase) if files[fn] == nil { - files[fn] = &File{} + files[fn] = &File{ + name: fnCase, + } } files[fn].Resolvers = append(files[fn].Resolvers, &resolver) } } - for filename, file := range files { - file.imports = rewriter.ExistingImports(filename) - file.RemainingSource = rewriter.RemainingSource(filename) + var allImports []string + for _, file := range files { + file.imports = rewriter.ExistingImports(file.name) + file.RemainingSource = rewriter.RemainingSource(file.name) + + for _, i := range file.imports { + allImports = append(allImports, i.ImportPath) + } } + data.Config.Packages.LoadAllNames(allImports...) // Preload all names in one Load call for performance reasons - for filename, file := range files { + newResolverTemplate := resolverTemplate + if data.Config.Resolver.ResolverTemplate != "" { + newResolverTemplate = readResolverTemplate(data.Config.Resolver.ResolverTemplate) + } + + for _, file := range files { + if fileExists(file.name) && + data.Config.Resolver.PreserveResolver { + // file already exists and config says not to update resolver + continue + } resolverBuild := &ResolverBuild{ - File: file, - PackageName: data.Config.Resolver.Package, - ResolverType: data.Config.Resolver.Type, + File: file, + PackageName: data.Config.Resolver.Package, + ResolverType: data.Config.Resolver.Type, + OmitTemplateComment: data.Config.Resolver.OmitTemplateComment, + } + + var fileNotice strings.Builder + if !data.Config.OmitGQLGenFileNotice { + fileNotice.WriteString(` + // This file will be automatically regenerated based on the schema, any resolver implementations + // will be copied through when generating and any unknown code will be moved to the end. + // Code generated by github.com/99designs/gqlgen`, + ) + if !data.Config.OmitGQLGenVersionInFileNotice { + fileNotice.WriteString(` version `) + fileNotice.WriteString(graphql.Version) + } } err := templates.Render(templates.Options{ PackageName: data.Config.Resolver.Package, - FileNotice: ` - // This file will be automatically regenerated based on the schema, any resolver implementations - // will be copied through when generating and any unknown code will be moved to the end.`, - Filename: filename, - Data: resolverBuild, - Packages: data.Config.Packages, - Template: resolverTemplate, + FileNotice: fileNotice.String(), + Filename: file.name, + Data: resolverBuild, + Packages: data.Config.Packages, + Template: newResolverTemplate, }) if err != nil { return err } } - if _, err := os.Stat(data.Config.Resolver.Filename); errors.Is(err, fs.ErrNotExist) { + if !fileExists(data.Config.Resolver.Filename) { err := templates.Render(templates.Options{ PackageName: data.Config.Resolver.Package, FileNotice: ` @@ -184,12 +263,14 @@ func (m *Plugin) generatePerSchema(data *codegen.Data) error { type ResolverBuild struct { *File - HasRoot bool - PackageName string - ResolverType string + HasRoot bool + PackageName string + ResolverType string + OmitTemplateComment bool } type File struct { + name string // These are separated because the type definition of the resolver object may live in a different file from the // resolver method implementations, for example when extending a type in a different graphql schema file Objects []*codegen.Object @@ -210,13 +291,29 @@ func (f *File) Imports() string { } type Resolver struct { - Object *codegen.Object - Field *codegen.Field - Comment string - Implementation string + Object *codegen.Object + Field *codegen.Field + PrevDecl *ast.FuncDecl + Comment string + ImplementationStr string + ImplementationRender func(prevImplementation string, r *codegen.Field) string } -func gqlToResolverName(base string, gqlname, filenameTmpl string) string { +func (r *Resolver) Implementation() string { + if r.ImplementationRender != nil { + // use custom implementation + return r.ImplementationRender(r.ImplementationStr, r.Field) + } + // if not implementation was previously used, use default implementation + if r.ImplementationStr == "" { + // use default implementation, if no implementation was previously used + return fmt.Sprintf("panic(fmt.Errorf(\"not implemented: %v - %v\"))", r.Field.GoFieldName, r.Field.Name) + } + // use previously used implementation + return r.ImplementationStr +} + +func gqlToResolverName(base, gqlname, filenameTmpl string) string { gqlname = filepath.Base(gqlname) ext := filepath.Ext(gqlname) if filenameTmpl == "" { @@ -225,3 +322,18 @@ func gqlToResolverName(base string, gqlname, filenameTmpl string) string { filename := strings.ReplaceAll(filenameTmpl, "{name}", strings.TrimSuffix(gqlname, ext)) return filepath.Join(base, filename) } + +func readResolverTemplate(customResolverTemplate string) string { + contentBytes, err := os.ReadFile(customResolverTemplate) + if err != nil { + panic(err) + } + return string(contentBytes) +} + +func fileExists(fileName string) bool { + if _, err := os.Stat(fileName); err == nil { + return true + } + return false +} diff --git a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.gotpl b/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.gotpl index c5d716ff7..bede575ab 100644 --- a/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.gotpl +++ b/vendor/github.com/99designs/gqlgen/plugin/resolvergen/resolver.gotpl @@ -19,15 +19,21 @@ {{ end }} {{ range $resolver := .Resolvers -}} - // {{ $resolver.Comment }} - func (r *{{lcFirst $resolver.Object.Name}}{{ucFirst $.ResolverType}}) {{$resolver.Field.GoFieldName}}{{ $resolver.Field.ShortResolverDeclaration }} { + {{ if $resolver.Comment -}} + {{with $resolver.Comment}}{{.|prefixLines "// "}}{{end}} + {{- else if not $.OmitTemplateComment -}} + // {{ $resolver.Field.GoFieldName }} is the resolver for the {{ $resolver.Field.Name }} field. + {{- end }} + func (r *{{lcFirst $resolver.Object.Name}}{{ucFirst $.ResolverType}}) {{$resolver.Field.GoFieldName}}{{ with $resolver.PrevDecl }}{{ $resolver.Field.ShortResolverSignature .Type }}{{ else }}{{ $resolver.Field.ShortResolverDeclaration }}{{ end }}{ {{ $resolver.Implementation }} } {{ end }} {{ range $object := .Objects -}} - // {{ucFirst $object.Name}} returns {{ $object.ResolverInterface | ref }} implementation. + {{ if not $.OmitTemplateComment -}} + // {{ucFirst $object.Name}} returns {{ $object.ResolverInterface | ref }} implementation. + {{- end }} func (r *{{$.ResolverType}}) {{ucFirst $object.Name}}() {{ $object.ResolverInterface | ref }} { return &{{lcFirst $object.Name}}{{ucFirst $.ResolverType}}{r} } {{ end }} @@ -42,5 +48,7 @@ // - When renaming or deleting a resolver the old code will be put in here. You can safely delete // it when you're done. // - You have helper methods in this file. Move them out to keep these resolver files clean. + /* {{ .RemainingSource }} + */ {{ end }} diff --git a/vendor/github.com/BurntSushi/toml/.gitignore b/vendor/github.com/BurntSushi/toml/.gitignore new file mode 100644 index 000000000..fe79e3add --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/.gitignore @@ -0,0 +1,2 @@ +/toml.test +/toml-test diff --git a/vendor/github.com/BurntSushi/toml/COPYING b/vendor/github.com/BurntSushi/toml/COPYING new file mode 100644 index 000000000..01b574320 --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/COPYING @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 TOML authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/BurntSushi/toml/README.md b/vendor/github.com/BurntSushi/toml/README.md new file mode 100644 index 000000000..235496eeb --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/README.md @@ -0,0 +1,120 @@ +TOML stands for Tom's Obvious, Minimal Language. This Go package provides a +reflection interface similar to Go's standard library `json` and `xml` packages. + +Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0). + +Documentation: https://pkg.go.dev/github.com/BurntSushi/toml + +See the [releases page](https://github.com/BurntSushi/toml/releases) for a +changelog; this information is also in the git tag annotations (e.g. `git show +v0.4.0`). + +This library requires Go 1.18 or newer; add it to your go.mod with: + + % go get github.com/BurntSushi/toml@latest + +It also comes with a TOML validator CLI tool: + + % go install github.com/BurntSushi/toml/cmd/tomlv@latest + % tomlv some-toml-file.toml + +### Examples +For the simplest example, consider some TOML file as just a list of keys and +values: + +```toml +Age = 25 +Cats = [ "Cauchy", "Plato" ] +Pi = 3.14 +Perfection = [ 6, 28, 496, 8128 ] +DOB = 1987-07-05T05:45:00Z +``` + +Which can be decoded with: + +```go +type Config struct { + Age int + Cats []string + Pi float64 + Perfection []int + DOB time.Time +} + +var conf Config +_, err := toml.Decode(tomlData, &conf) +``` + +You can also use struct tags if your struct field name doesn't map to a TOML key +value directly: + +```toml +some_key_NAME = "wat" +``` + +```go +type TOML struct { + ObscureKey string `toml:"some_key_NAME"` +} +``` + +Beware that like other decoders **only exported fields** are considered when +encoding and decoding; private fields are silently ignored. + +### Using the `Marshaler` and `encoding.TextUnmarshaler` interfaces +Here's an example that automatically parses values in a `mail.Address`: + +```toml +contacts = [ + "Donald Duck ", + "Scrooge McDuck ", +] +``` + +Can be decoded with: + +```go +// Create address type which satisfies the encoding.TextUnmarshaler interface. +type address struct { + *mail.Address +} + +func (a *address) UnmarshalText(text []byte) error { + var err error + a.Address, err = mail.ParseAddress(string(text)) + return err +} + +// Decode it. +func decode() { + blob := ` + contacts = [ + "Donald Duck ", + "Scrooge McDuck ", + ] + ` + + var contacts struct { + Contacts []address + } + + _, err := toml.Decode(blob, &contacts) + if err != nil { + log.Fatal(err) + } + + for _, c := range contacts.Contacts { + fmt.Printf("%#v\n", c.Address) + } + + // Output: + // &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"} + // &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"} +} +``` + +To target TOML specifically you can implement `UnmarshalTOML` TOML interface in +a similar way. + +### More complex usage +See the [`_example/`](/_example) directory for a more complex example. diff --git a/vendor/github.com/BurntSushi/toml/decode.go b/vendor/github.com/BurntSushi/toml/decode.go new file mode 100644 index 000000000..3fa516caa --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/decode.go @@ -0,0 +1,638 @@ +package toml + +import ( + "bytes" + "encoding" + "encoding/json" + "fmt" + "io" + "io/fs" + "math" + "os" + "reflect" + "strconv" + "strings" + "time" +) + +// Unmarshaler is the interface implemented by objects that can unmarshal a +// TOML description of themselves. +type Unmarshaler interface { + UnmarshalTOML(any) error +} + +// Unmarshal decodes the contents of data in TOML format into a pointer v. +// +// See [Decoder] for a description of the decoding process. +func Unmarshal(data []byte, v any) error { + _, err := NewDecoder(bytes.NewReader(data)).Decode(v) + return err +} + +// Decode the TOML data in to the pointer v. +// +// See [Decoder] for a description of the decoding process. +func Decode(data string, v any) (MetaData, error) { + return NewDecoder(strings.NewReader(data)).Decode(v) +} + +// DecodeFile reads the contents of a file and decodes it with [Decode]. +func DecodeFile(path string, v any) (MetaData, error) { + fp, err := os.Open(path) + if err != nil { + return MetaData{}, err + } + defer fp.Close() + return NewDecoder(fp).Decode(v) +} + +// DecodeFS reads the contents of a file from [fs.FS] and decodes it with +// [Decode]. +func DecodeFS(fsys fs.FS, path string, v any) (MetaData, error) { + fp, err := fsys.Open(path) + if err != nil { + return MetaData{}, err + } + defer fp.Close() + return NewDecoder(fp).Decode(v) +} + +// Primitive is a TOML value that hasn't been decoded into a Go value. +// +// This type can be used for any value, which will cause decoding to be delayed. +// You can use [PrimitiveDecode] to "manually" decode these values. +// +// NOTE: The underlying representation of a `Primitive` value is subject to +// change. Do not rely on it. +// +// NOTE: Primitive values are still parsed, so using them will only avoid the +// overhead of reflection. They can be useful when you don't know the exact type +// of TOML data until runtime. +type Primitive struct { + undecoded any + context Key +} + +// The significand precision for float32 and float64 is 24 and 53 bits; this is +// the range a natural number can be stored in a float without loss of data. +const ( + maxSafeFloat32Int = 16777215 // 2^24-1 + maxSafeFloat64Int = int64(9007199254740991) // 2^53-1 +) + +// Decoder decodes TOML data. +// +// TOML tables correspond to Go structs or maps; they can be used +// interchangeably, but structs offer better type safety. +// +// TOML table arrays correspond to either a slice of structs or a slice of maps. +// +// TOML datetimes correspond to [time.Time]. Local datetimes are parsed in the +// local timezone. +// +// [time.Duration] types are treated as nanoseconds if the TOML value is an +// integer, or they're parsed with time.ParseDuration() if they're strings. +// +// All other TOML types (float, string, int, bool and array) correspond to the +// obvious Go types. +// +// An exception to the above rules is if a type implements the TextUnmarshaler +// interface, in which case any primitive TOML value (floats, strings, integers, +// booleans, datetimes) will be converted to a []byte and given to the value's +// UnmarshalText method. See the Unmarshaler example for a demonstration with +// email addresses. +// +// # Key mapping +// +// TOML keys can map to either keys in a Go map or field names in a Go struct. +// The special `toml` struct tag can be used to map TOML keys to struct fields +// that don't match the key name exactly (see the example). A case insensitive +// match to struct names will be tried if an exact match can't be found. +// +// The mapping between TOML values and Go values is loose. That is, there may +// exist TOML values that cannot be placed into your representation, and there +// may be parts of your representation that do not correspond to TOML values. +// This loose mapping can be made stricter by using the IsDefined and/or +// Undecoded methods on the MetaData returned. +// +// This decoder does not handle cyclic types. Decode will not terminate if a +// cyclic type is passed. +type Decoder struct { + r io.Reader +} + +// NewDecoder creates a new Decoder. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{r: r} +} + +var ( + unmarshalToml = reflect.TypeOf((*Unmarshaler)(nil)).Elem() + unmarshalText = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() + primitiveType = reflect.TypeOf((*Primitive)(nil)).Elem() +) + +// Decode TOML data in to the pointer `v`. +func (dec *Decoder) Decode(v any) (MetaData, error) { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Ptr { + s := "%q" + if reflect.TypeOf(v) == nil { + s = "%v" + } + + return MetaData{}, fmt.Errorf("toml: cannot decode to non-pointer "+s, reflect.TypeOf(v)) + } + if rv.IsNil() { + return MetaData{}, fmt.Errorf("toml: cannot decode to nil value of %q", reflect.TypeOf(v)) + } + + // Check if this is a supported type: struct, map, any, or something that + // implements UnmarshalTOML or UnmarshalText. + rv = indirect(rv) + rt := rv.Type() + if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map && + !(rv.Kind() == reflect.Interface && rv.NumMethod() == 0) && + !rt.Implements(unmarshalToml) && !rt.Implements(unmarshalText) { + return MetaData{}, fmt.Errorf("toml: cannot decode to type %s", rt) + } + + // TODO: parser should read from io.Reader? Or at the very least, make it + // read from []byte rather than string + data, err := io.ReadAll(dec.r) + if err != nil { + return MetaData{}, err + } + + p, err := parse(string(data)) + if err != nil { + return MetaData{}, err + } + + md := MetaData{ + mapping: p.mapping, + keyInfo: p.keyInfo, + keys: p.ordered, + decoded: make(map[string]struct{}, len(p.ordered)), + context: nil, + data: data, + } + return md, md.unify(p.mapping, rv) +} + +// PrimitiveDecode is just like the other Decode* functions, except it decodes a +// TOML value that has already been parsed. Valid primitive values can *only* be +// obtained from values filled by the decoder functions, including this method. +// (i.e., v may contain more [Primitive] values.) +// +// Meta data for primitive values is included in the meta data returned by the +// Decode* functions with one exception: keys returned by the Undecoded method +// will only reflect keys that were decoded. Namely, any keys hidden behind a +// Primitive will be considered undecoded. Executing this method will update the +// undecoded keys in the meta data. (See the example.) +func (md *MetaData) PrimitiveDecode(primValue Primitive, v any) error { + md.context = primValue.context + defer func() { md.context = nil }() + return md.unify(primValue.undecoded, rvalue(v)) +} + +// markDecodedRecursive is a helper to mark any key under the given tmap as +// decoded, recursing as needed +func markDecodedRecursive(md *MetaData, tmap map[string]any) { + for key := range tmap { + md.decoded[md.context.add(key).String()] = struct{}{} + if tmap, ok := tmap[key].(map[string]any); ok { + md.context = append(md.context, key) + markDecodedRecursive(md, tmap) + md.context = md.context[0 : len(md.context)-1] + } + } +} + +// unify performs a sort of type unification based on the structure of `rv`, +// which is the client representation. +// +// Any type mismatch produces an error. Finding a type that we don't know +// how to handle produces an unsupported type error. +func (md *MetaData) unify(data any, rv reflect.Value) error { + // Special case. Look for a `Primitive` value. + // TODO: #76 would make this superfluous after implemented. + if rv.Type() == primitiveType { + // Save the undecoded data and the key context into the primitive + // value. + context := make(Key, len(md.context)) + copy(context, md.context) + rv.Set(reflect.ValueOf(Primitive{ + undecoded: data, + context: context, + })) + return nil + } + + rvi := rv.Interface() + if v, ok := rvi.(Unmarshaler); ok { + err := v.UnmarshalTOML(data) + if err != nil { + return md.parseErr(err) + } + // Assume the Unmarshaler decoded everything, so mark all keys under + // this table as decoded. + if tmap, ok := data.(map[string]any); ok { + markDecodedRecursive(md, tmap) + } + if aot, ok := data.([]map[string]any); ok { + for _, tmap := range aot { + markDecodedRecursive(md, tmap) + } + } + return nil + } + if v, ok := rvi.(encoding.TextUnmarshaler); ok { + return md.unifyText(data, v) + } + + // TODO: + // The behavior here is incorrect whenever a Go type satisfies the + // encoding.TextUnmarshaler interface but also corresponds to a TOML hash or + // array. In particular, the unmarshaler should only be applied to primitive + // TOML values. But at this point, it will be applied to all kinds of values + // and produce an incorrect error whenever those values are hashes or arrays + // (including arrays of tables). + + k := rv.Kind() + + if k >= reflect.Int && k <= reflect.Uint64 { + return md.unifyInt(data, rv) + } + switch k { + case reflect.Struct: + return md.unifyStruct(data, rv) + case reflect.Map: + return md.unifyMap(data, rv) + case reflect.Array: + return md.unifyArray(data, rv) + case reflect.Slice: + return md.unifySlice(data, rv) + case reflect.String: + return md.unifyString(data, rv) + case reflect.Bool: + return md.unifyBool(data, rv) + case reflect.Interface: + if rv.NumMethod() > 0 { /// Only empty interfaces are supported. + return md.e("unsupported type %s", rv.Type()) + } + return md.unifyAnything(data, rv) + case reflect.Float32, reflect.Float64: + return md.unifyFloat64(data, rv) + } + return md.e("unsupported type %s", rv.Kind()) +} + +func (md *MetaData) unifyStruct(mapping any, rv reflect.Value) error { + tmap, ok := mapping.(map[string]any) + if !ok { + if mapping == nil { + return nil + } + return md.e("type mismatch for %s: expected table but found %s", rv.Type().String(), fmtType(mapping)) + } + + for key, datum := range tmap { + var f *field + fields := cachedTypeFields(rv.Type()) + for i := range fields { + ff := &fields[i] + if ff.name == key { + f = ff + break + } + if f == nil && strings.EqualFold(ff.name, key) { + f = ff + } + } + if f != nil { + subv := rv + for _, i := range f.index { + subv = indirect(subv.Field(i)) + } + + if isUnifiable(subv) { + md.decoded[md.context.add(key).String()] = struct{}{} + md.context = append(md.context, key) + + err := md.unify(datum, subv) + if err != nil { + return err + } + md.context = md.context[0 : len(md.context)-1] + } else if f.name != "" { + return md.e("cannot write unexported field %s.%s", rv.Type().String(), f.name) + } + } + } + return nil +} + +func (md *MetaData) unifyMap(mapping any, rv reflect.Value) error { + keyType := rv.Type().Key().Kind() + if keyType != reflect.String && keyType != reflect.Interface { + return fmt.Errorf("toml: cannot decode to a map with non-string key type (%s in %q)", + keyType, rv.Type()) + } + + tmap, ok := mapping.(map[string]any) + if !ok { + if tmap == nil { + return nil + } + return md.badtype("map", mapping) + } + if rv.IsNil() { + rv.Set(reflect.MakeMap(rv.Type())) + } + for k, v := range tmap { + md.decoded[md.context.add(k).String()] = struct{}{} + md.context = append(md.context, k) + + rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) + + err := md.unify(v, indirect(rvval)) + if err != nil { + return err + } + md.context = md.context[0 : len(md.context)-1] + + rvkey := indirect(reflect.New(rv.Type().Key())) + + switch keyType { + case reflect.Interface: + rvkey.Set(reflect.ValueOf(k)) + case reflect.String: + rvkey.SetString(k) + } + + rv.SetMapIndex(rvkey, rvval) + } + return nil +} + +func (md *MetaData) unifyArray(data any, rv reflect.Value) error { + datav := reflect.ValueOf(data) + if datav.Kind() != reflect.Slice { + if !datav.IsValid() { + return nil + } + return md.badtype("slice", data) + } + if l := datav.Len(); l != rv.Len() { + return md.e("expected array length %d; got TOML array of length %d", rv.Len(), l) + } + return md.unifySliceArray(datav, rv) +} + +func (md *MetaData) unifySlice(data any, rv reflect.Value) error { + datav := reflect.ValueOf(data) + if datav.Kind() != reflect.Slice { + if !datav.IsValid() { + return nil + } + return md.badtype("slice", data) + } + n := datav.Len() + if rv.IsNil() || rv.Cap() < n { + rv.Set(reflect.MakeSlice(rv.Type(), n, n)) + } + rv.SetLen(n) + return md.unifySliceArray(datav, rv) +} + +func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { + l := data.Len() + for i := 0; i < l; i++ { + err := md.unify(data.Index(i).Interface(), indirect(rv.Index(i))) + if err != nil { + return err + } + } + return nil +} + +func (md *MetaData) unifyString(data any, rv reflect.Value) error { + _, ok := rv.Interface().(json.Number) + if ok { + if i, ok := data.(int64); ok { + rv.SetString(strconv.FormatInt(i, 10)) + } else if f, ok := data.(float64); ok { + rv.SetString(strconv.FormatFloat(f, 'f', -1, 64)) + } else { + return md.badtype("string", data) + } + return nil + } + + if s, ok := data.(string); ok { + rv.SetString(s) + return nil + } + return md.badtype("string", data) +} + +func (md *MetaData) unifyFloat64(data any, rv reflect.Value) error { + rvk := rv.Kind() + + if num, ok := data.(float64); ok { + switch rvk { + case reflect.Float32: + if num < -math.MaxFloat32 || num > math.MaxFloat32 { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) + } + fallthrough + case reflect.Float64: + rv.SetFloat(num) + default: + panic("bug") + } + return nil + } + + if num, ok := data.(int64); ok { + if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) || + (rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) { + return md.parseErr(errUnsafeFloat{i: num, size: rvk.String()}) + } + rv.SetFloat(float64(num)) + return nil + } + + return md.badtype("float", data) +} + +func (md *MetaData) unifyInt(data any, rv reflect.Value) error { + _, ok := rv.Interface().(time.Duration) + if ok { + // Parse as string duration, and fall back to regular integer parsing + // (as nanosecond) if this is not a string. + if s, ok := data.(string); ok { + dur, err := time.ParseDuration(s) + if err != nil { + return md.parseErr(errParseDuration{s}) + } + rv.SetInt(int64(dur)) + return nil + } + } + + num, ok := data.(int64) + if !ok { + return md.badtype("integer", data) + } + + rvk := rv.Kind() + switch { + case rvk >= reflect.Int && rvk <= reflect.Int64: + if (rvk == reflect.Int8 && (num < math.MinInt8 || num > math.MaxInt8)) || + (rvk == reflect.Int16 && (num < math.MinInt16 || num > math.MaxInt16)) || + (rvk == reflect.Int32 && (num < math.MinInt32 || num > math.MaxInt32)) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) + } + rv.SetInt(num) + case rvk >= reflect.Uint && rvk <= reflect.Uint64: + unum := uint64(num) + if rvk == reflect.Uint8 && (num < 0 || unum > math.MaxUint8) || + rvk == reflect.Uint16 && (num < 0 || unum > math.MaxUint16) || + rvk == reflect.Uint32 && (num < 0 || unum > math.MaxUint32) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) + } + rv.SetUint(unum) + default: + panic("unreachable") + } + return nil +} + +func (md *MetaData) unifyBool(data any, rv reflect.Value) error { + if b, ok := data.(bool); ok { + rv.SetBool(b) + return nil + } + return md.badtype("boolean", data) +} + +func (md *MetaData) unifyAnything(data any, rv reflect.Value) error { + rv.Set(reflect.ValueOf(data)) + return nil +} + +func (md *MetaData) unifyText(data any, v encoding.TextUnmarshaler) error { + var s string + switch sdata := data.(type) { + case Marshaler: + text, err := sdata.MarshalTOML() + if err != nil { + return err + } + s = string(text) + case encoding.TextMarshaler: + text, err := sdata.MarshalText() + if err != nil { + return err + } + s = string(text) + case fmt.Stringer: + s = sdata.String() + case string: + s = sdata + case bool: + s = fmt.Sprintf("%v", sdata) + case int64: + s = fmt.Sprintf("%d", sdata) + case float64: + s = fmt.Sprintf("%f", sdata) + default: + return md.badtype("primitive (string-like)", data) + } + if err := v.UnmarshalText([]byte(s)); err != nil { + return md.parseErr(err) + } + return nil +} + +func (md *MetaData) badtype(dst string, data any) error { + return md.e("incompatible types: TOML value has type %s; destination has type %s", fmtType(data), dst) +} + +func (md *MetaData) parseErr(err error) error { + k := md.context.String() + d := string(md.data) + return ParseError{ + Message: err.Error(), + err: err, + LastKey: k, + Position: md.keyInfo[k].pos.withCol(d), + Line: md.keyInfo[k].pos.Line, + input: d, + } +} + +func (md *MetaData) e(format string, args ...any) error { + f := "toml: " + if len(md.context) > 0 { + f = fmt.Sprintf("toml: (last key %q): ", md.context) + p := md.keyInfo[md.context.String()].pos + if p.Line > 0 { + f = fmt.Sprintf("toml: line %d (last key %q): ", p.Line, md.context) + } + } + return fmt.Errorf(f+format, args...) +} + +// rvalue returns a reflect.Value of `v`. All pointers are resolved. +func rvalue(v any) reflect.Value { + return indirect(reflect.ValueOf(v)) +} + +// indirect returns the value pointed to by a pointer. +// +// Pointers are followed until the value is not a pointer. New values are +// allocated for each nil pointer. +// +// An exception to this rule is if the value satisfies an interface of interest +// to us (like encoding.TextUnmarshaler). +func indirect(v reflect.Value) reflect.Value { + if v.Kind() != reflect.Ptr { + if v.CanSet() { + pv := v.Addr() + pvi := pv.Interface() + if _, ok := pvi.(encoding.TextUnmarshaler); ok { + return pv + } + if _, ok := pvi.(Unmarshaler); ok { + return pv + } + } + return v + } + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + return indirect(reflect.Indirect(v)) +} + +func isUnifiable(rv reflect.Value) bool { + if rv.CanSet() { + return true + } + rvi := rv.Interface() + if _, ok := rvi.(encoding.TextUnmarshaler); ok { + return true + } + if _, ok := rvi.(Unmarshaler); ok { + return true + } + return false +} + +// fmt %T with "interface {}" replaced with "any", which is far more readable. +func fmtType(t any) string { + return strings.ReplaceAll(fmt.Sprintf("%T", t), "interface {}", "any") +} diff --git a/vendor/github.com/BurntSushi/toml/deprecated.go b/vendor/github.com/BurntSushi/toml/deprecated.go new file mode 100644 index 000000000..155709a80 --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/deprecated.go @@ -0,0 +1,29 @@ +package toml + +import ( + "encoding" + "io" +) + +// TextMarshaler is an alias for encoding.TextMarshaler. +// +// Deprecated: use encoding.TextMarshaler +type TextMarshaler encoding.TextMarshaler + +// TextUnmarshaler is an alias for encoding.TextUnmarshaler. +// +// Deprecated: use encoding.TextUnmarshaler +type TextUnmarshaler encoding.TextUnmarshaler + +// DecodeReader is an alias for NewDecoder(r).Decode(v). +// +// Deprecated: use NewDecoder(reader).Decode(&value). +func DecodeReader(r io.Reader, v any) (MetaData, error) { return NewDecoder(r).Decode(v) } + +// PrimitiveDecode is an alias for MetaData.PrimitiveDecode(). +// +// Deprecated: use MetaData.PrimitiveDecode. +func PrimitiveDecode(primValue Primitive, v any) error { + md := MetaData{decoded: make(map[string]struct{})} + return md.unify(primValue.undecoded, rvalue(v)) +} diff --git a/vendor/github.com/BurntSushi/toml/doc.go b/vendor/github.com/BurntSushi/toml/doc.go new file mode 100644 index 000000000..82c90a905 --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/doc.go @@ -0,0 +1,8 @@ +// Package toml implements decoding and encoding of TOML files. +// +// This package supports TOML v1.0.0, as specified at https://toml.io +// +// The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator, +// and can be used to verify if TOML document is valid. It can also be used to +// print the type of each key. +package toml diff --git a/vendor/github.com/BurntSushi/toml/encode.go b/vendor/github.com/BurntSushi/toml/encode.go new file mode 100644 index 000000000..ac196e7df --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/encode.go @@ -0,0 +1,776 @@ +package toml + +import ( + "bufio" + "bytes" + "encoding" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "reflect" + "sort" + "strconv" + "strings" + "time" + + "github.com/BurntSushi/toml/internal" +) + +type tomlEncodeError struct{ error } + +var ( + errArrayNilElement = errors.New("toml: cannot encode array with nil element") + errNonString = errors.New("toml: cannot encode a map with non-string key type") + errNoKey = errors.New("toml: top-level values must be Go maps or structs") + errAnything = errors.New("") // used in testing +) + +var dblQuotedReplacer = strings.NewReplacer( + "\"", "\\\"", + "\\", "\\\\", + "\x00", `\u0000`, + "\x01", `\u0001`, + "\x02", `\u0002`, + "\x03", `\u0003`, + "\x04", `\u0004`, + "\x05", `\u0005`, + "\x06", `\u0006`, + "\x07", `\u0007`, + "\b", `\b`, + "\t", `\t`, + "\n", `\n`, + "\x0b", `\u000b`, + "\f", `\f`, + "\r", `\r`, + "\x0e", `\u000e`, + "\x0f", `\u000f`, + "\x10", `\u0010`, + "\x11", `\u0011`, + "\x12", `\u0012`, + "\x13", `\u0013`, + "\x14", `\u0014`, + "\x15", `\u0015`, + "\x16", `\u0016`, + "\x17", `\u0017`, + "\x18", `\u0018`, + "\x19", `\u0019`, + "\x1a", `\u001a`, + "\x1b", `\u001b`, + "\x1c", `\u001c`, + "\x1d", `\u001d`, + "\x1e", `\u001e`, + "\x1f", `\u001f`, + "\x7f", `\u007f`, +) + +var ( + marshalToml = reflect.TypeOf((*Marshaler)(nil)).Elem() + marshalText = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() + timeType = reflect.TypeOf((*time.Time)(nil)).Elem() +) + +// Marshaler is the interface implemented by types that can marshal themselves +// into valid TOML. +type Marshaler interface { + MarshalTOML() ([]byte, error) +} + +// Marshal returns a TOML representation of the Go value. +// +// See [Encoder] for a description of the encoding process. +func Marshal(v any) ([]byte, error) { + buff := new(bytes.Buffer) + if err := NewEncoder(buff).Encode(v); err != nil { + return nil, err + } + return buff.Bytes(), nil +} + +// Encoder encodes a Go to a TOML document. +// +// The mapping between Go values and TOML values should be precisely the same as +// for [Decode]. +// +// time.Time is encoded as a RFC 3339 string, and time.Duration as its string +// representation. +// +// The [Marshaler] and [encoding.TextMarshaler] interfaces are supported to +// encoding the value as custom TOML. +// +// If you want to write arbitrary binary data then you will need to use +// something like base64 since TOML does not have any binary types. +// +// When encoding TOML hashes (Go maps or structs), keys without any sub-hashes +// are encoded first. +// +// Go maps will be sorted alphabetically by key for deterministic output. +// +// The toml struct tag can be used to provide the key name; if omitted the +// struct field name will be used. If the "omitempty" option is present the +// following value will be skipped: +// +// - arrays, slices, maps, and string with len of 0 +// - struct with all zero values +// - bool false +// +// If omitzero is given all int and float types with a value of 0 will be +// skipped. +// +// Encoding Go values without a corresponding TOML representation will return an +// error. Examples of this includes maps with non-string keys, slices with nil +// elements, embedded non-struct types, and nested slices containing maps or +// structs. (e.g. [][]map[string]string is not allowed but []map[string]string +// is okay, as is []map[string][]string). +// +// NOTE: only exported keys are encoded due to the use of reflection. Unexported +// keys are silently discarded. +type Encoder struct { + Indent string // string for a single indentation level; default is two spaces. + hasWritten bool // written any output to w yet? + w *bufio.Writer +} + +// NewEncoder create a new Encoder. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{w: bufio.NewWriter(w), Indent: " "} +} + +// Encode writes a TOML representation of the Go value to the [Encoder]'s writer. +// +// An error is returned if the value given cannot be encoded to a valid TOML +// document. +func (enc *Encoder) Encode(v any) error { + rv := eindirect(reflect.ValueOf(v)) + err := enc.safeEncode(Key([]string{}), rv) + if err != nil { + return err + } + return enc.w.Flush() +} + +func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { + defer func() { + if r := recover(); r != nil { + if terr, ok := r.(tomlEncodeError); ok { + err = terr.error + return + } + panic(r) + } + }() + enc.encode(key, rv) + return nil +} + +func (enc *Encoder) encode(key Key, rv reflect.Value) { + // If we can marshal the type to text, then we use that. This prevents the + // encoder for handling these types as generic structs (or whatever the + // underlying type of a TextMarshaler is). + switch { + case isMarshaler(rv): + enc.writeKeyValue(key, rv, false) + return + case rv.Type() == primitiveType: // TODO: #76 would make this superfluous after implemented. + enc.encode(key, reflect.ValueOf(rv.Interface().(Primitive).undecoded)) + return + } + + k := rv.Kind() + switch k { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, + reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, + reflect.Uint64, + reflect.Float32, reflect.Float64, reflect.String, reflect.Bool: + enc.writeKeyValue(key, rv, false) + case reflect.Array, reflect.Slice: + if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) { + enc.eArrayOfTables(key, rv) + } else { + enc.writeKeyValue(key, rv, false) + } + case reflect.Interface: + if rv.IsNil() { + return + } + enc.encode(key, rv.Elem()) + case reflect.Map: + if rv.IsNil() { + return + } + enc.eTable(key, rv) + case reflect.Ptr: + if rv.IsNil() { + return + } + enc.encode(key, rv.Elem()) + case reflect.Struct: + enc.eTable(key, rv) + default: + encPanic(fmt.Errorf("unsupported type for key '%s': %s", key, k)) + } +} + +// eElement encodes any value that can be an array element. +func (enc *Encoder) eElement(rv reflect.Value) { + switch v := rv.Interface().(type) { + case time.Time: // Using TextMarshaler adds extra quotes, which we don't want. + format := time.RFC3339Nano + switch v.Location() { + case internal.LocalDatetime: + format = "2006-01-02T15:04:05.999999999" + case internal.LocalDate: + format = "2006-01-02" + case internal.LocalTime: + format = "15:04:05.999999999" + } + switch v.Location() { + default: + enc.wf(v.Format(format)) + case internal.LocalDatetime, internal.LocalDate, internal.LocalTime: + enc.wf(v.In(time.UTC).Format(format)) + } + return + case Marshaler: + s, err := v.MarshalTOML() + if err != nil { + encPanic(err) + } + if s == nil { + encPanic(errors.New("MarshalTOML returned nil and no error")) + } + enc.w.Write(s) + return + case encoding.TextMarshaler: + s, err := v.MarshalText() + if err != nil { + encPanic(err) + } + if s == nil { + encPanic(errors.New("MarshalText returned nil and no error")) + } + enc.writeQuoted(string(s)) + return + case time.Duration: + enc.writeQuoted(v.String()) + return + case json.Number: + n, _ := rv.Interface().(json.Number) + + if n == "" { /// Useful zero value. + enc.w.WriteByte('0') + return + } else if v, err := n.Int64(); err == nil { + enc.eElement(reflect.ValueOf(v)) + return + } else if v, err := n.Float64(); err == nil { + enc.eElement(reflect.ValueOf(v)) + return + } + encPanic(fmt.Errorf("unable to convert %q to int64 or float64", n)) + } + + switch rv.Kind() { + case reflect.Ptr: + enc.eElement(rv.Elem()) + return + case reflect.String: + enc.writeQuoted(rv.String()) + case reflect.Bool: + enc.wf(strconv.FormatBool(rv.Bool())) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + enc.wf(strconv.FormatInt(rv.Int(), 10)) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + enc.wf(strconv.FormatUint(rv.Uint(), 10)) + case reflect.Float32: + f := rv.Float() + if math.IsNaN(f) { + if math.Signbit(f) { + enc.wf("-") + } + enc.wf("nan") + } else if math.IsInf(f, 0) { + if math.Signbit(f) { + enc.wf("-") + } + enc.wf("inf") + } else { + enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 32))) + } + case reflect.Float64: + f := rv.Float() + if math.IsNaN(f) { + if math.Signbit(f) { + enc.wf("-") + } + enc.wf("nan") + } else if math.IsInf(f, 0) { + if math.Signbit(f) { + enc.wf("-") + } + enc.wf("inf") + } else { + enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 64))) + } + case reflect.Array, reflect.Slice: + enc.eArrayOrSliceElement(rv) + case reflect.Struct: + enc.eStruct(nil, rv, true) + case reflect.Map: + enc.eMap(nil, rv, true) + case reflect.Interface: + enc.eElement(rv.Elem()) + default: + encPanic(fmt.Errorf("unexpected type: %s", fmtType(rv.Interface()))) + } +} + +// By the TOML spec, all floats must have a decimal with at least one number on +// either side. +func floatAddDecimal(fstr string) string { + if !strings.Contains(fstr, ".") { + return fstr + ".0" + } + return fstr +} + +func (enc *Encoder) writeQuoted(s string) { + enc.wf("\"%s\"", dblQuotedReplacer.Replace(s)) +} + +func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { + length := rv.Len() + enc.wf("[") + for i := 0; i < length; i++ { + elem := eindirect(rv.Index(i)) + enc.eElement(elem) + if i != length-1 { + enc.wf(", ") + } + } + enc.wf("]") +} + +func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { + if len(key) == 0 { + encPanic(errNoKey) + } + for i := 0; i < rv.Len(); i++ { + trv := eindirect(rv.Index(i)) + if isNil(trv) { + continue + } + enc.newline() + enc.wf("%s[[%s]]", enc.indentStr(key), key) + enc.newline() + enc.eMapOrStruct(key, trv, false) + } +} + +func (enc *Encoder) eTable(key Key, rv reflect.Value) { + if len(key) == 1 { + // Output an extra newline between top-level tables. + // (The newline isn't written if nothing else has been written though.) + enc.newline() + } + if len(key) > 0 { + enc.wf("%s[%s]", enc.indentStr(key), key) + enc.newline() + } + enc.eMapOrStruct(key, rv, false) +} + +func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value, inline bool) { + switch rv.Kind() { + case reflect.Map: + enc.eMap(key, rv, inline) + case reflect.Struct: + enc.eStruct(key, rv, inline) + default: + // Should never happen? + panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String()) + } +} + +func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { + rt := rv.Type() + if rt.Key().Kind() != reflect.String { + encPanic(errNonString) + } + + // Sort keys so that we have deterministic output. And write keys directly + // underneath this key first, before writing sub-structs or sub-maps. + var mapKeysDirect, mapKeysSub []reflect.Value + for _, mapKey := range rv.MapKeys() { + if typeIsTable(tomlTypeOfGo(eindirect(rv.MapIndex(mapKey)))) { + mapKeysSub = append(mapKeysSub, mapKey) + } else { + mapKeysDirect = append(mapKeysDirect, mapKey) + } + } + + writeMapKeys := func(mapKeys []reflect.Value, trailC bool) { + sort.Slice(mapKeys, func(i, j int) bool { return mapKeys[i].String() < mapKeys[j].String() }) + for i, mapKey := range mapKeys { + val := eindirect(rv.MapIndex(mapKey)) + if isNil(val) { + continue + } + + if inline { + enc.writeKeyValue(Key{mapKey.String()}, val, true) + if trailC || i != len(mapKeys)-1 { + enc.wf(", ") + } + } else { + enc.encode(key.add(mapKey.String()), val) + } + } + } + + if inline { + enc.wf("{") + } + writeMapKeys(mapKeysDirect, len(mapKeysSub) > 0) + writeMapKeys(mapKeysSub, false) + if inline { + enc.wf("}") + } +} + +func pointerTo(t reflect.Type) reflect.Type { + if t.Kind() == reflect.Ptr { + return pointerTo(t.Elem()) + } + return t +} + +func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { + // Write keys for fields directly under this key first, because if we write + // a field that creates a new table then all keys under it will be in that + // table (not the one we're writing here). + // + // Fields is a [][]int: for fieldsDirect this always has one entry (the + // struct index). For fieldsSub it contains two entries: the parent field + // index from tv, and the field indexes for the fields of the sub. + var ( + rt = rv.Type() + fieldsDirect, fieldsSub [][]int + addFields func(rt reflect.Type, rv reflect.Value, start []int) + ) + addFields = func(rt reflect.Type, rv reflect.Value, start []int) { + for i := 0; i < rt.NumField(); i++ { + f := rt.Field(i) + isEmbed := f.Anonymous && pointerTo(f.Type).Kind() == reflect.Struct + if f.PkgPath != "" && !isEmbed { /// Skip unexported fields. + continue + } + opts := getOptions(f.Tag) + if opts.skip { + continue + } + + frv := eindirect(rv.Field(i)) + + // Need to make a copy because ... ehm, I don't know why... I guess + // allocating a new array can cause it to fail(?) + // + // Done for: https://github.com/BurntSushi/toml/issues/430 + // Previously only on 32bit for: https://github.com/BurntSushi/toml/issues/314 + copyStart := make([]int, len(start)) + copy(copyStart, start) + start = copyStart + + // Treat anonymous struct fields with tag names as though they are + // not anonymous, like encoding/json does. + // + // Non-struct anonymous fields use the normal encoding logic. + if isEmbed { + if getOptions(f.Tag).name == "" && frv.Kind() == reflect.Struct { + addFields(frv.Type(), frv, append(start, f.Index...)) + continue + } + } + + if typeIsTable(tomlTypeOfGo(frv)) { + fieldsSub = append(fieldsSub, append(start, f.Index...)) + } else { + fieldsDirect = append(fieldsDirect, append(start, f.Index...)) + } + } + } + addFields(rt, rv, nil) + + writeFields := func(fields [][]int, totalFields int) { + for _, fieldIndex := range fields { + fieldType := rt.FieldByIndex(fieldIndex) + fieldVal := rv.FieldByIndex(fieldIndex) + + opts := getOptions(fieldType.Tag) + if opts.skip { + continue + } + if opts.omitempty && isEmpty(fieldVal) { + continue + } + + fieldVal = eindirect(fieldVal) + + if isNil(fieldVal) { /// Don't write anything for nil fields. + continue + } + + keyName := fieldType.Name + if opts.name != "" { + keyName = opts.name + } + + if opts.omitzero && isZero(fieldVal) { + continue + } + + if inline { + enc.writeKeyValue(Key{keyName}, fieldVal, true) + if fieldIndex[0] != totalFields-1 { + enc.wf(", ") + } + } else { + enc.encode(key.add(keyName), fieldVal) + } + } + } + + if inline { + enc.wf("{") + } + + l := len(fieldsDirect) + len(fieldsSub) + writeFields(fieldsDirect, l) + writeFields(fieldsSub, l) + if inline { + enc.wf("}") + } +} + +// tomlTypeOfGo returns the TOML type name of the Go value's type. +// +// It is used to determine whether the types of array elements are mixed (which +// is forbidden). If the Go value is nil, then it is illegal for it to be an +// array element, and valueIsNil is returned as true. +// +// The type may be `nil`, which means no concrete TOML type could be found. +func tomlTypeOfGo(rv reflect.Value) tomlType { + if isNil(rv) || !rv.IsValid() { + return nil + } + + if rv.Kind() == reflect.Struct { + if rv.Type() == timeType { + return tomlDatetime + } + if isMarshaler(rv) { + return tomlString + } + return tomlHash + } + + if isMarshaler(rv) { + return tomlString + } + + switch rv.Kind() { + case reflect.Bool: + return tomlBool + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, + reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, + reflect.Uint64: + return tomlInteger + case reflect.Float32, reflect.Float64: + return tomlFloat + case reflect.Array, reflect.Slice: + if isTableArray(rv) { + return tomlArrayHash + } + return tomlArray + case reflect.Ptr, reflect.Interface: + return tomlTypeOfGo(rv.Elem()) + case reflect.String: + return tomlString + case reflect.Map: + return tomlHash + default: + encPanic(errors.New("unsupported type: " + rv.Kind().String())) + panic("unreachable") + } +} + +func isMarshaler(rv reflect.Value) bool { + return rv.Type().Implements(marshalText) || rv.Type().Implements(marshalToml) +} + +// isTableArray reports if all entries in the array or slice are a table. +func isTableArray(arr reflect.Value) bool { + if isNil(arr) || !arr.IsValid() || arr.Len() == 0 { + return false + } + + ret := true + for i := 0; i < arr.Len(); i++ { + tt := tomlTypeOfGo(eindirect(arr.Index(i))) + // Don't allow nil. + if tt == nil { + encPanic(errArrayNilElement) + } + + if ret && !typeEqual(tomlHash, tt) { + ret = false + } + } + return ret +} + +type tagOptions struct { + skip bool // "-" + name string + omitempty bool + omitzero bool +} + +func getOptions(tag reflect.StructTag) tagOptions { + t := tag.Get("toml") + if t == "-" { + return tagOptions{skip: true} + } + var opts tagOptions + parts := strings.Split(t, ",") + opts.name = parts[0] + for _, s := range parts[1:] { + switch s { + case "omitempty": + opts.omitempty = true + case "omitzero": + opts.omitzero = true + } + } + return opts +} + +func isZero(rv reflect.Value) bool { + switch rv.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rv.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return rv.Uint() == 0 + case reflect.Float32, reflect.Float64: + return rv.Float() == 0.0 + } + return false +} + +func isEmpty(rv reflect.Value) bool { + switch rv.Kind() { + case reflect.Array, reflect.Slice, reflect.Map, reflect.String: + return rv.Len() == 0 + case reflect.Struct: + if rv.Type().Comparable() { + return reflect.Zero(rv.Type()).Interface() == rv.Interface() + } + // Need to also check if all the fields are empty, otherwise something + // like this with uncomparable types will always return true: + // + // type a struct{ field b } + // type b struct{ s []string } + // s := a{field: b{s: []string{"AAA"}}} + for i := 0; i < rv.NumField(); i++ { + if !isEmpty(rv.Field(i)) { + return false + } + } + return true + case reflect.Bool: + return !rv.Bool() + case reflect.Ptr: + return rv.IsNil() + } + return false +} + +func (enc *Encoder) newline() { + if enc.hasWritten { + enc.wf("\n") + } +} + +// Write a key/value pair: +// +// key = +// +// This is also used for "k = v" in inline tables; so something like this will +// be written in three calls: +// +// ┌───────────────────┐ +// │ ┌───┐ ┌────┐│ +// v v v v vv +// key = {k = 1, k2 = 2} +func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) { + /// Marshaler used on top-level document; call eElement() to just call + /// Marshal{TOML,Text}. + if len(key) == 0 { + enc.eElement(val) + return + } + enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1)) + enc.eElement(val) + if !inline { + enc.newline() + } +} + +func (enc *Encoder) wf(format string, v ...any) { + _, err := fmt.Fprintf(enc.w, format, v...) + if err != nil { + encPanic(err) + } + enc.hasWritten = true +} + +func (enc *Encoder) indentStr(key Key) string { + return strings.Repeat(enc.Indent, len(key)-1) +} + +func encPanic(err error) { + panic(tomlEncodeError{err}) +} + +// Resolve any level of pointers to the actual value (e.g. **string → string). +func eindirect(v reflect.Value) reflect.Value { + if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { + if isMarshaler(v) { + return v + } + if v.CanAddr() { /// Special case for marshalers; see #358. + if pv := v.Addr(); isMarshaler(pv) { + return pv + } + } + return v + } + + if v.IsNil() { + return v + } + + return eindirect(v.Elem()) +} + +func isNil(rv reflect.Value) bool { + switch rv.Kind() { + case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return rv.IsNil() + default: + return false + } +} diff --git a/vendor/github.com/BurntSushi/toml/error.go b/vendor/github.com/BurntSushi/toml/error.go new file mode 100644 index 000000000..b7077d3ae --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/error.go @@ -0,0 +1,347 @@ +package toml + +import ( + "fmt" + "strings" +) + +// ParseError is returned when there is an error parsing the TOML syntax such as +// invalid syntax, duplicate keys, etc. +// +// In addition to the error message itself, you can also print detailed location +// information with context by using [ErrorWithPosition]: +// +// toml: error: Key 'fruit' was already created and cannot be used as an array. +// +// At line 4, column 2-7: +// +// 2 | fruit = [] +// 3 | +// 4 | [[fruit]] # Not allowed +// ^^^^^ +// +// [ErrorWithUsage] can be used to print the above with some more detailed usage +// guidance: +// +// toml: error: newlines not allowed within inline tables +// +// At line 1, column 18: +// +// 1 | x = [{ key = 42 # +// ^ +// +// Error help: +// +// Inline tables must always be on a single line: +// +// table = {key = 42, second = 43} +// +// It is invalid to split them over multiple lines like so: +// +// # INVALID +// table = { +// key = 42, +// second = 43 +// } +// +// Use regular for this: +// +// [table] +// key = 42 +// second = 43 +type ParseError struct { + Message string // Short technical message. + Usage string // Longer message with usage guidance; may be blank. + Position Position // Position of the error + LastKey string // Last parsed key, may be blank. + + // Line the error occurred. + // + // Deprecated: use [Position]. + Line int + + err error + input string +} + +// Position of an error. +type Position struct { + Line int // Line number, starting at 1. + Col int // Error column, starting at 1. + Start int // Start of error, as byte offset starting at 0. + Len int // Length of the error in bytes. +} + +func (p Position) withCol(tomlFile string) Position { + var ( + pos int + lines = strings.Split(tomlFile, "\n") + ) + for i := range lines { + ll := len(lines[i]) + 1 // +1 for the removed newline + if pos+ll >= p.Start { + p.Col = p.Start - pos + 1 + if p.Col < 1 { // Should never happen, but just in case. + p.Col = 1 + } + break + } + pos += ll + } + return p +} + +func (pe ParseError) Error() string { + if pe.LastKey == "" { + return fmt.Sprintf("toml: line %d: %s", pe.Position.Line, pe.Message) + } + return fmt.Sprintf("toml: line %d (last key %q): %s", + pe.Position.Line, pe.LastKey, pe.Message) +} + +// ErrorWithPosition returns the error with detailed location context. +// +// See the documentation on [ParseError]. +func (pe ParseError) ErrorWithPosition() string { + if pe.input == "" { // Should never happen, but just in case. + return pe.Error() + } + + // TODO: don't show control characters as literals? This may not show up + // well everywhere. + + var ( + lines = strings.Split(pe.input, "\n") + b = new(strings.Builder) + ) + if pe.Position.Len == 1 { + fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d:\n\n", + pe.Message, pe.Position.Line, pe.Position.Col) + } else { + fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d-%d:\n\n", + pe.Message, pe.Position.Line, pe.Position.Col, pe.Position.Col+pe.Position.Len-1) + } + if pe.Position.Line > 2 { + fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, expandTab(lines[pe.Position.Line-3])) + } + if pe.Position.Line > 1 { + fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2])) + } + + /// Expand tabs, so that the ^^^s are at the correct position, but leave + /// "column 10-13" intact. Adjusting this to the visual column would be + /// better, but we don't know the tabsize of the user in their editor, which + /// can be 8, 4, 2, or something else. We can't know. So leaving it as the + /// character index is probably the "most correct". + expanded := expandTab(lines[pe.Position.Line-1]) + diff := len(expanded) - len(lines[pe.Position.Line-1]) + + fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, expanded) + fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", pe.Position.Col-1+diff), strings.Repeat("^", pe.Position.Len)) + return b.String() +} + +// ErrorWithUsage returns the error with detailed location context and usage +// guidance. +// +// See the documentation on [ParseError]. +func (pe ParseError) ErrorWithUsage() string { + m := pe.ErrorWithPosition() + if u, ok := pe.err.(interface{ Usage() string }); ok && u.Usage() != "" { + lines := strings.Split(strings.TrimSpace(u.Usage()), "\n") + for i := range lines { + if lines[i] != "" { + lines[i] = " " + lines[i] + } + } + return m + "Error help:\n\n" + strings.Join(lines, "\n") + "\n" + } + return m +} + +func expandTab(s string) string { + var ( + b strings.Builder + l int + fill = func(n int) string { + b := make([]byte, n) + for i := range b { + b[i] = ' ' + } + return string(b) + } + ) + b.Grow(len(s)) + for _, r := range s { + switch r { + case '\t': + tw := 8 - l%8 + b.WriteString(fill(tw)) + l += tw + default: + b.WriteRune(r) + l += 1 + } + } + return b.String() +} + +type ( + errLexControl struct{ r rune } + errLexEscape struct{ r rune } + errLexUTF8 struct{ b byte } + errParseDate struct{ v string } + errLexInlineTableNL struct{} + errLexStringNL struct{} + errParseRange struct { + i any // int or float + size string // "int64", "uint16", etc. + } + errUnsafeFloat struct { + i interface{} // float32 or float64 + size string // "float32" or "float64" + } + errParseDuration struct{ d string } +) + +func (e errLexControl) Error() string { + return fmt.Sprintf("TOML files cannot contain control characters: '0x%02x'", e.r) +} +func (e errLexControl) Usage() string { return "" } + +func (e errLexEscape) Error() string { return fmt.Sprintf(`invalid escape in string '\%c'`, e.r) } +func (e errLexEscape) Usage() string { return usageEscape } +func (e errLexUTF8) Error() string { return fmt.Sprintf("invalid UTF-8 byte: 0x%02x", e.b) } +func (e errLexUTF8) Usage() string { return "" } +func (e errParseDate) Error() string { return fmt.Sprintf("invalid datetime: %q", e.v) } +func (e errParseDate) Usage() string { return usageDate } +func (e errLexInlineTableNL) Error() string { return "newlines not allowed within inline tables" } +func (e errLexInlineTableNL) Usage() string { return usageInlineNewline } +func (e errLexStringNL) Error() string { return "strings cannot contain newlines" } +func (e errLexStringNL) Usage() string { return usageStringNewline } +func (e errParseRange) Error() string { return fmt.Sprintf("%v is out of range for %s", e.i, e.size) } +func (e errParseRange) Usage() string { return usageIntOverflow } +func (e errUnsafeFloat) Error() string { + return fmt.Sprintf("%v is out of the safe %s range", e.i, e.size) +} +func (e errUnsafeFloat) Usage() string { return usageUnsafeFloat } +func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) } +func (e errParseDuration) Usage() string { return usageDuration } + +const usageEscape = ` +A '\' inside a "-delimited string is interpreted as an escape character. + +The following escape sequences are supported: +\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX + +To prevent a '\' from being recognized as an escape character, use either: + +- a ' or '''-delimited string; escape characters aren't processed in them; or +- write two backslashes to get a single backslash: '\\'. + +If you're trying to add a Windows path (e.g. "C:\Users\martin") then using '/' +instead of '\' will usually also work: "C:/Users/martin". +` + +const usageInlineNewline = ` +Inline tables must always be on a single line: + + table = {key = 42, second = 43} + +It is invalid to split them over multiple lines like so: + + # INVALID + table = { + key = 42, + second = 43 + } + +Use regular for this: + + [table] + key = 42 + second = 43 +` + +const usageStringNewline = ` +Strings must always be on a single line, and cannot span more than one line: + + # INVALID + string = "Hello, + world!" + +Instead use """ or ''' to split strings over multiple lines: + + string = """Hello, + world!""" +` + +const usageIntOverflow = ` +This number is too large; this may be an error in the TOML, but it can also be a +bug in the program that uses too small of an integer. + +The maximum and minimum values are: + + size │ lowest │ highest + ───────┼────────────────┼────────────── + int8 │ -128 │ 127 + int16 │ -32,768 │ 32,767 + int32 │ -2,147,483,648 │ 2,147,483,647 + int64 │ -9.2 × 10¹⁷ │ 9.2 × 10¹⁷ + uint8 │ 0 │ 255 + uint16 │ 0 │ 65,535 + uint32 │ 0 │ 4,294,967,295 + uint64 │ 0 │ 1.8 × 10¹⁸ + +int refers to int32 on 32-bit systems and int64 on 64-bit systems. +` + +const usageUnsafeFloat = ` +This number is outside of the "safe" range for floating point numbers; whole +(non-fractional) numbers outside the below range can not always be represented +accurately in a float, leading to some loss of accuracy. + +Explicitly mark a number as a fractional unit by adding ".0", which will incur +some loss of accuracy; for example: + + f = 2_000_000_000.0 + +Accuracy ranges: + + float32 = 16,777,215 + float64 = 9,007,199,254,740,991 +` + +const usageDuration = ` +A duration must be as "number", without any spaces. Valid units are: + + ns nanoseconds (billionth of a second) + us, µs microseconds (millionth of a second) + ms milliseconds (thousands of a second) + s seconds + m minutes + h hours + +You can combine multiple units; for example "5m10s" for 5 minutes and 10 +seconds. +` + +const usageDate = ` +A TOML datetime must be in one of the following formats: + + 2006-01-02T15:04:05Z07:00 Date and time, with timezone. + 2006-01-02T15:04:05 Date and time, but without timezone. + 2006-01-02 Date without a time or timezone. + 15:04:05 Just a time, without any timezone. + +Seconds may optionally have a fraction, up to nanosecond precision: + + 15:04:05.123 + 15:04:05.856018510 +` + +// TOML 1.1: +// The seconds part in times is optional, and may be omitted: +// 2006-01-02T15:04Z07:00 +// 2006-01-02T15:04 +// 15:04 diff --git a/vendor/github.com/BurntSushi/toml/internal/tz.go b/vendor/github.com/BurntSushi/toml/internal/tz.go new file mode 100644 index 000000000..022f15bc2 --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/internal/tz.go @@ -0,0 +1,36 @@ +package internal + +import "time" + +// Timezones used for local datetime, date, and time TOML types. +// +// The exact way times and dates without a timezone should be interpreted is not +// well-defined in the TOML specification and left to the implementation. These +// defaults to current local timezone offset of the computer, but this can be +// changed by changing these variables before decoding. +// +// TODO: +// Ideally we'd like to offer people the ability to configure the used timezone +// by setting Decoder.Timezone and Encoder.Timezone; however, this is a bit +// tricky: the reason we use three different variables for this is to support +// round-tripping – without these specific TZ names we wouldn't know which +// format to use. +// +// There isn't a good way to encode this right now though, and passing this sort +// of information also ties in to various related issues such as string format +// encoding, encoding of comments, etc. +// +// So, for the time being, just put this in internal until we can write a good +// comprehensive API for doing all of this. +// +// The reason they're exported is because they're referred from in e.g. +// internal/tag. +// +// Note that this behaviour is valid according to the TOML spec as the exact +// behaviour is left up to implementations. +var ( + localOffset = func() int { _, o := time.Now().Zone(); return o }() + LocalDatetime = time.FixedZone("datetime-local", localOffset) + LocalDate = time.FixedZone("date-local", localOffset) + LocalTime = time.FixedZone("time-local", localOffset) +) diff --git a/vendor/github.com/BurntSushi/toml/lex.go b/vendor/github.com/BurntSushi/toml/lex.go new file mode 100644 index 000000000..1c3b47702 --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/lex.go @@ -0,0 +1,1272 @@ +package toml + +import ( + "fmt" + "reflect" + "runtime" + "strings" + "unicode" + "unicode/utf8" +) + +type itemType int + +const ( + itemError itemType = iota + itemNIL // used in the parser to indicate no type + itemEOF + itemText + itemString + itemStringEsc + itemRawString + itemMultilineString + itemRawMultilineString + itemBool + itemInteger + itemFloat + itemDatetime + itemArray // the start of an array + itemArrayEnd + itemTableStart + itemTableEnd + itemArrayTableStart + itemArrayTableEnd + itemKeyStart + itemKeyEnd + itemCommentStart + itemInlineTableStart + itemInlineTableEnd +) + +const eof = 0 + +type stateFn func(lx *lexer) stateFn + +func (p Position) String() string { + return fmt.Sprintf("at line %d; start %d; length %d", p.Line, p.Start, p.Len) +} + +type lexer struct { + input string + start int + pos int + line int + state stateFn + items chan item + tomlNext bool + esc bool + + // Allow for backing up up to 4 runes. This is necessary because TOML + // contains 3-rune tokens (""" and '''). + prevWidths [4]int + nprev int // how many of prevWidths are in use + atEOF bool // If we emit an eof, we can still back up, but it is not OK to call next again. + + // A stack of state functions used to maintain context. + // + // The idea is to reuse parts of the state machine in various places. For + // example, values can appear at the top level or within arbitrarily nested + // arrays. The last state on the stack is used after a value has been lexed. + // Similarly for comments. + stack []stateFn +} + +type item struct { + typ itemType + val string + err error + pos Position +} + +func (lx *lexer) nextItem() item { + for { + select { + case item := <-lx.items: + return item + default: + lx.state = lx.state(lx) + //fmt.Printf(" STATE %-24s current: %-10s stack: %s\n", lx.state, lx.current(), lx.stack) + } + } +} + +func lex(input string, tomlNext bool) *lexer { + lx := &lexer{ + input: input, + state: lexTop, + items: make(chan item, 10), + stack: make([]stateFn, 0, 10), + line: 1, + tomlNext: tomlNext, + } + return lx +} + +func (lx *lexer) push(state stateFn) { + lx.stack = append(lx.stack, state) +} + +func (lx *lexer) pop() stateFn { + if len(lx.stack) == 0 { + return lx.errorf("BUG in lexer: no states to pop") + } + last := lx.stack[len(lx.stack)-1] + lx.stack = lx.stack[0 : len(lx.stack)-1] + return last +} + +func (lx *lexer) current() string { + return lx.input[lx.start:lx.pos] +} + +func (lx lexer) getPos() Position { + p := Position{ + Line: lx.line, + Start: lx.start, + Len: lx.pos - lx.start, + } + if p.Len <= 0 { + p.Len = 1 + } + return p +} + +func (lx *lexer) emit(typ itemType) { + // Needed for multiline strings ending with an incomplete UTF-8 sequence. + if lx.start > lx.pos { + lx.error(errLexUTF8{lx.input[lx.pos]}) + return + } + lx.items <- item{typ: typ, pos: lx.getPos(), val: lx.current()} + lx.start = lx.pos +} + +func (lx *lexer) emitTrim(typ itemType) { + lx.items <- item{typ: typ, pos: lx.getPos(), val: strings.TrimSpace(lx.current())} + lx.start = lx.pos +} + +func (lx *lexer) next() (r rune) { + if lx.atEOF { + panic("BUG in lexer: next called after EOF") + } + if lx.pos >= len(lx.input) { + lx.atEOF = true + return eof + } + + if lx.input[lx.pos] == '\n' { + lx.line++ + } + lx.prevWidths[3] = lx.prevWidths[2] + lx.prevWidths[2] = lx.prevWidths[1] + lx.prevWidths[1] = lx.prevWidths[0] + if lx.nprev < 4 { + lx.nprev++ + } + + r, w := utf8.DecodeRuneInString(lx.input[lx.pos:]) + if r == utf8.RuneError && w == 1 { + lx.error(errLexUTF8{lx.input[lx.pos]}) + return utf8.RuneError + } + + // Note: don't use peek() here, as this calls next(). + if isControl(r) || (r == '\r' && (len(lx.input)-1 == lx.pos || lx.input[lx.pos+1] != '\n')) { + lx.errorControlChar(r) + return utf8.RuneError + } + + lx.prevWidths[0] = w + lx.pos += w + return r +} + +// ignore skips over the pending input before this point. +func (lx *lexer) ignore() { + lx.start = lx.pos +} + +// backup steps back one rune. Can be called 4 times between calls to next. +func (lx *lexer) backup() { + if lx.atEOF { + lx.atEOF = false + return + } + if lx.nprev < 1 { + panic("BUG in lexer: backed up too far") + } + w := lx.prevWidths[0] + lx.prevWidths[0] = lx.prevWidths[1] + lx.prevWidths[1] = lx.prevWidths[2] + lx.prevWidths[2] = lx.prevWidths[3] + lx.nprev-- + + lx.pos -= w + if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { + lx.line-- + } +} + +// accept consumes the next rune if it's equal to `valid`. +func (lx *lexer) accept(valid rune) bool { + if lx.next() == valid { + return true + } + lx.backup() + return false +} + +// peek returns but does not consume the next rune in the input. +func (lx *lexer) peek() rune { + r := lx.next() + lx.backup() + return r +} + +// skip ignores all input that matches the given predicate. +func (lx *lexer) skip(pred func(rune) bool) { + for { + r := lx.next() + if pred(r) { + continue + } + lx.backup() + lx.ignore() + return + } +} + +// error stops all lexing by emitting an error and returning `nil`. +// +// Note that any value that is a character is escaped if it's a special +// character (newlines, tabs, etc.). +func (lx *lexer) error(err error) stateFn { + if lx.atEOF { + return lx.errorPrevLine(err) + } + lx.items <- item{typ: itemError, pos: lx.getPos(), err: err} + return nil +} + +// errorfPrevline is like error(), but sets the position to the last column of +// the previous line. +// +// This is so that unexpected EOF or NL errors don't show on a new blank line. +func (lx *lexer) errorPrevLine(err error) stateFn { + pos := lx.getPos() + pos.Line-- + pos.Len = 1 + pos.Start = lx.pos - 1 + lx.items <- item{typ: itemError, pos: pos, err: err} + return nil +} + +// errorPos is like error(), but allows explicitly setting the position. +func (lx *lexer) errorPos(start, length int, err error) stateFn { + pos := lx.getPos() + pos.Start = start + pos.Len = length + lx.items <- item{typ: itemError, pos: pos, err: err} + return nil +} + +// errorf is like error, and creates a new error. +func (lx *lexer) errorf(format string, values ...any) stateFn { + if lx.atEOF { + pos := lx.getPos() + if lx.pos >= 1 && lx.input[lx.pos-1] == '\n' { + pos.Line-- + } + pos.Len = 1 + pos.Start = lx.pos - 1 + lx.items <- item{typ: itemError, pos: pos, err: fmt.Errorf(format, values...)} + return nil + } + lx.items <- item{typ: itemError, pos: lx.getPos(), err: fmt.Errorf(format, values...)} + return nil +} + +func (lx *lexer) errorControlChar(cc rune) stateFn { + return lx.errorPos(lx.pos-1, 1, errLexControl{cc}) +} + +// lexTop consumes elements at the top level of TOML data. +func lexTop(lx *lexer) stateFn { + r := lx.next() + if isWhitespace(r) || isNL(r) { + return lexSkip(lx, lexTop) + } + switch r { + case '#': + lx.push(lexTop) + return lexCommentStart + case '[': + return lexTableStart + case eof: + if lx.pos > lx.start { + return lx.errorf("unexpected EOF") + } + lx.emit(itemEOF) + return nil + } + + // At this point, the only valid item can be a key, so we back up + // and let the key lexer do the rest. + lx.backup() + lx.push(lexTopEnd) + return lexKeyStart +} + +// lexTopEnd is entered whenever a top-level item has been consumed. (A value +// or a table.) It must see only whitespace, and will turn back to lexTop +// upon a newline. If it sees EOF, it will quit the lexer successfully. +func lexTopEnd(lx *lexer) stateFn { + r := lx.next() + switch { + case r == '#': + // a comment will read to a newline for us. + lx.push(lexTop) + return lexCommentStart + case isWhitespace(r): + return lexTopEnd + case isNL(r): + lx.ignore() + return lexTop + case r == eof: + lx.emit(itemEOF) + return nil + } + return lx.errorf("expected a top-level item to end with a newline, comment, or EOF, but got %q instead", r) +} + +// lexTable lexes the beginning of a table. Namely, it makes sure that +// it starts with a character other than '.' and ']'. +// It assumes that '[' has already been consumed. +// It also handles the case that this is an item in an array of tables. +// e.g., '[[name]]'. +func lexTableStart(lx *lexer) stateFn { + if lx.peek() == '[' { + lx.next() + lx.emit(itemArrayTableStart) + lx.push(lexArrayTableEnd) + } else { + lx.emit(itemTableStart) + lx.push(lexTableEnd) + } + return lexTableNameStart +} + +func lexTableEnd(lx *lexer) stateFn { + lx.emit(itemTableEnd) + return lexTopEnd +} + +func lexArrayTableEnd(lx *lexer) stateFn { + if r := lx.next(); r != ']' { + return lx.errorf("expected end of table array name delimiter ']', but got %q instead", r) + } + lx.emit(itemArrayTableEnd) + return lexTopEnd +} + +func lexTableNameStart(lx *lexer) stateFn { + lx.skip(isWhitespace) + switch r := lx.peek(); { + case r == ']' || r == eof: + return lx.errorf("unexpected end of table name (table names cannot be empty)") + case r == '.': + return lx.errorf("unexpected table separator (table names cannot be empty)") + case r == '"' || r == '\'': + lx.ignore() + lx.push(lexTableNameEnd) + return lexQuotedName + default: + lx.push(lexTableNameEnd) + return lexBareName + } +} + +// lexTableNameEnd reads the end of a piece of a table name, optionally +// consuming whitespace. +func lexTableNameEnd(lx *lexer) stateFn { + lx.skip(isWhitespace) + switch r := lx.next(); { + case isWhitespace(r): + return lexTableNameEnd + case r == '.': + lx.ignore() + return lexTableNameStart + case r == ']': + return lx.pop() + default: + return lx.errorf("expected '.' or ']' to end table name, but got %q instead", r) + } +} + +// lexBareName lexes one part of a key or table. +// +// It assumes that at least one valid character for the table has already been +// read. +// +// Lexes only one part, e.g. only 'a' inside 'a.b'. +func lexBareName(lx *lexer) stateFn { + r := lx.next() + if isBareKeyChar(r, lx.tomlNext) { + return lexBareName + } + lx.backup() + lx.emit(itemText) + return lx.pop() +} + +// lexBareName lexes one part of a key or table. +// +// It assumes that at least one valid character for the table has already been +// read. +// +// Lexes only one part, e.g. only '"a"' inside '"a".b'. +func lexQuotedName(lx *lexer) stateFn { + r := lx.next() + switch { + case isWhitespace(r): + return lexSkip(lx, lexValue) + case r == '"': + lx.ignore() // ignore the '"' + return lexString + case r == '\'': + lx.ignore() // ignore the "'" + return lexRawString + case r == eof: + return lx.errorf("unexpected EOF; expected value") + default: + return lx.errorf("expected value but found %q instead", r) + } +} + +// lexKeyStart consumes all key parts until a '='. +func lexKeyStart(lx *lexer) stateFn { + lx.skip(isWhitespace) + switch r := lx.peek(); { + case r == '=' || r == eof: + return lx.errorf("unexpected '=': key name appears blank") + case r == '.': + return lx.errorf("unexpected '.': keys cannot start with a '.'") + case r == '"' || r == '\'': + lx.ignore() + fallthrough + default: // Bare key + lx.emit(itemKeyStart) + return lexKeyNameStart + } +} + +func lexKeyNameStart(lx *lexer) stateFn { + lx.skip(isWhitespace) + switch r := lx.peek(); { + case r == '=' || r == eof: + return lx.errorf("unexpected '='") + case r == '.': + return lx.errorf("unexpected '.'") + case r == '"' || r == '\'': + lx.ignore() + lx.push(lexKeyEnd) + return lexQuotedName + default: + lx.push(lexKeyEnd) + return lexBareName + } +} + +// lexKeyEnd consumes the end of a key and trims whitespace (up to the key +// separator). +func lexKeyEnd(lx *lexer) stateFn { + lx.skip(isWhitespace) + switch r := lx.next(); { + case isWhitespace(r): + return lexSkip(lx, lexKeyEnd) + case r == eof: + return lx.errorf("unexpected EOF; expected key separator '='") + case r == '.': + lx.ignore() + return lexKeyNameStart + case r == '=': + lx.emit(itemKeyEnd) + return lexSkip(lx, lexValue) + default: + if r == '\n' { + return lx.errorPrevLine(fmt.Errorf("expected '.' or '=', but got %q instead", r)) + } + return lx.errorf("expected '.' or '=', but got %q instead", r) + } +} + +// lexValue starts the consumption of a value anywhere a value is expected. +// lexValue will ignore whitespace. +// After a value is lexed, the last state on the next is popped and returned. +func lexValue(lx *lexer) stateFn { + // We allow whitespace to precede a value, but NOT newlines. + // In array syntax, the array states are responsible for ignoring newlines. + r := lx.next() + switch { + case isWhitespace(r): + return lexSkip(lx, lexValue) + case isDigit(r): + lx.backup() // avoid an extra state and use the same as above + return lexNumberOrDateStart + } + switch r { + case '[': + lx.ignore() + lx.emit(itemArray) + return lexArrayValue + case '{': + lx.ignore() + lx.emit(itemInlineTableStart) + return lexInlineTableValue + case '"': + if lx.accept('"') { + if lx.accept('"') { + lx.ignore() // Ignore """ + return lexMultilineString + } + lx.backup() + } + lx.ignore() // ignore the '"' + return lexString + case '\'': + if lx.accept('\'') { + if lx.accept('\'') { + lx.ignore() // Ignore """ + return lexMultilineRawString + } + lx.backup() + } + lx.ignore() // ignore the "'" + return lexRawString + case '.': // special error case, be kind to users + return lx.errorf("floats must start with a digit, not '.'") + case 'i', 'n': + if (lx.accept('n') && lx.accept('f')) || (lx.accept('a') && lx.accept('n')) { + lx.emit(itemFloat) + return lx.pop() + } + case '-', '+': + return lexDecimalNumberStart + } + if unicode.IsLetter(r) { + // Be permissive here; lexBool will give a nice error if the + // user wrote something like + // x = foo + // (i.e. not 'true' or 'false' but is something else word-like.) + lx.backup() + return lexBool + } + if r == eof { + return lx.errorf("unexpected EOF; expected value") + } + if r == '\n' { + return lx.errorPrevLine(fmt.Errorf("expected value but found %q instead", r)) + } + return lx.errorf("expected value but found %q instead", r) +} + +// lexArrayValue consumes one value in an array. It assumes that '[' or ',' +// have already been consumed. All whitespace and newlines are ignored. +func lexArrayValue(lx *lexer) stateFn { + r := lx.next() + switch { + case isWhitespace(r) || isNL(r): + return lexSkip(lx, lexArrayValue) + case r == '#': + lx.push(lexArrayValue) + return lexCommentStart + case r == ',': + return lx.errorf("unexpected comma") + case r == ']': + return lexArrayEnd + } + + lx.backup() + lx.push(lexArrayValueEnd) + return lexValue +} + +// lexArrayValueEnd consumes everything between the end of an array value and +// the next value (or the end of the array): it ignores whitespace and newlines +// and expects either a ',' or a ']'. +func lexArrayValueEnd(lx *lexer) stateFn { + switch r := lx.next(); { + case isWhitespace(r) || isNL(r): + return lexSkip(lx, lexArrayValueEnd) + case r == '#': + lx.push(lexArrayValueEnd) + return lexCommentStart + case r == ',': + lx.ignore() + return lexArrayValue // move on to the next value + case r == ']': + return lexArrayEnd + default: + return lx.errorf("expected a comma (',') or array terminator (']'), but got %s", runeOrEOF(r)) + } +} + +// lexArrayEnd finishes the lexing of an array. +// It assumes that a ']' has just been consumed. +func lexArrayEnd(lx *lexer) stateFn { + lx.ignore() + lx.emit(itemArrayEnd) + return lx.pop() +} + +// lexInlineTableValue consumes one key/value pair in an inline table. +// It assumes that '{' or ',' have already been consumed. Whitespace is ignored. +func lexInlineTableValue(lx *lexer) stateFn { + r := lx.next() + switch { + case isWhitespace(r): + return lexSkip(lx, lexInlineTableValue) + case isNL(r): + if lx.tomlNext { + return lexSkip(lx, lexInlineTableValue) + } + return lx.errorPrevLine(errLexInlineTableNL{}) + case r == '#': + lx.push(lexInlineTableValue) + return lexCommentStart + case r == ',': + return lx.errorf("unexpected comma") + case r == '}': + return lexInlineTableEnd + } + lx.backup() + lx.push(lexInlineTableValueEnd) + return lexKeyStart +} + +// lexInlineTableValueEnd consumes everything between the end of an inline table +// key/value pair and the next pair (or the end of the table): +// it ignores whitespace and expects either a ',' or a '}'. +func lexInlineTableValueEnd(lx *lexer) stateFn { + switch r := lx.next(); { + case isWhitespace(r): + return lexSkip(lx, lexInlineTableValueEnd) + case isNL(r): + if lx.tomlNext { + return lexSkip(lx, lexInlineTableValueEnd) + } + return lx.errorPrevLine(errLexInlineTableNL{}) + case r == '#': + lx.push(lexInlineTableValueEnd) + return lexCommentStart + case r == ',': + lx.ignore() + lx.skip(isWhitespace) + if lx.peek() == '}' { + if lx.tomlNext { + return lexInlineTableValueEnd + } + return lx.errorf("trailing comma not allowed in inline tables") + } + return lexInlineTableValue + case r == '}': + return lexInlineTableEnd + default: + return lx.errorf("expected a comma or an inline table terminator '}', but got %s instead", runeOrEOF(r)) + } +} + +func runeOrEOF(r rune) string { + if r == eof { + return "end of file" + } + return "'" + string(r) + "'" +} + +// lexInlineTableEnd finishes the lexing of an inline table. +// It assumes that a '}' has just been consumed. +func lexInlineTableEnd(lx *lexer) stateFn { + lx.ignore() + lx.emit(itemInlineTableEnd) + return lx.pop() +} + +// lexString consumes the inner contents of a string. It assumes that the +// beginning '"' has already been consumed and ignored. +func lexString(lx *lexer) stateFn { + r := lx.next() + switch { + case r == eof: + return lx.errorf(`unexpected EOF; expected '"'`) + case isNL(r): + return lx.errorPrevLine(errLexStringNL{}) + case r == '\\': + lx.push(lexString) + return lexStringEscape + case r == '"': + lx.backup() + if lx.esc { + lx.esc = false + lx.emit(itemStringEsc) + } else { + lx.emit(itemString) + } + lx.next() + lx.ignore() + return lx.pop() + } + return lexString +} + +// lexMultilineString consumes the inner contents of a string. It assumes that +// the beginning '"""' has already been consumed and ignored. +func lexMultilineString(lx *lexer) stateFn { + r := lx.next() + switch r { + default: + return lexMultilineString + case eof: + return lx.errorf(`unexpected EOF; expected '"""'`) + case '\\': + return lexMultilineStringEscape + case '"': + /// Found " → try to read two more "". + if lx.accept('"') { + if lx.accept('"') { + /// Peek ahead: the string can contain " and "", including at the + /// end: """str""""" + /// 6 or more at the end, however, is an error. + if lx.peek() == '"' { + /// Check if we already lexed 5 's; if so we have 6 now, and + /// that's just too many man! + /// + /// Second check is for the edge case: + /// + /// two quotes allowed. + /// vv + /// """lol \"""""" + /// ^^ ^^^---- closing three + /// escaped + /// + /// But ugly, but it works + if strings.HasSuffix(lx.current(), `"""""`) && !strings.HasSuffix(lx.current(), `\"""""`) { + return lx.errorf(`unexpected '""""""'`) + } + lx.backup() + lx.backup() + return lexMultilineString + } + + lx.backup() /// backup: don't include the """ in the item. + lx.backup() + lx.backup() + lx.esc = false + lx.emit(itemMultilineString) + lx.next() /// Read over ''' again and discard it. + lx.next() + lx.next() + lx.ignore() + return lx.pop() + } + lx.backup() + } + return lexMultilineString + } +} + +// lexRawString consumes a raw string. Nothing can be escaped in such a string. +// It assumes that the beginning "'" has already been consumed and ignored. +func lexRawString(lx *lexer) stateFn { + r := lx.next() + switch { + default: + return lexRawString + case r == eof: + return lx.errorf(`unexpected EOF; expected "'"`) + case isNL(r): + return lx.errorPrevLine(errLexStringNL{}) + case r == '\'': + lx.backup() + lx.emit(itemRawString) + lx.next() + lx.ignore() + return lx.pop() + } +} + +// lexMultilineRawString consumes a raw string. Nothing can be escaped in such a +// string. It assumes that the beginning triple-' has already been consumed and +// ignored. +func lexMultilineRawString(lx *lexer) stateFn { + r := lx.next() + switch r { + default: + return lexMultilineRawString + case eof: + return lx.errorf(`unexpected EOF; expected "'''"`) + case '\'': + /// Found ' → try to read two more ''. + if lx.accept('\'') { + if lx.accept('\'') { + /// Peek ahead: the string can contain ' and '', including at the + /// end: '''str''''' + /// 6 or more at the end, however, is an error. + if lx.peek() == '\'' { + /// Check if we already lexed 5 's; if so we have 6 now, and + /// that's just too many man! + if strings.HasSuffix(lx.current(), "'''''") { + return lx.errorf(`unexpected "''''''"`) + } + lx.backup() + lx.backup() + return lexMultilineRawString + } + + lx.backup() /// backup: don't include the ''' in the item. + lx.backup() + lx.backup() + lx.emit(itemRawMultilineString) + lx.next() /// Read over ''' again and discard it. + lx.next() + lx.next() + lx.ignore() + return lx.pop() + } + lx.backup() + } + return lexMultilineRawString + } +} + +// lexMultilineStringEscape consumes an escaped character. It assumes that the +// preceding '\\' has already been consumed. +func lexMultilineStringEscape(lx *lexer) stateFn { + if isNL(lx.next()) { /// \ escaping newline. + return lexMultilineString + } + lx.backup() + lx.push(lexMultilineString) + return lexStringEscape(lx) +} + +func lexStringEscape(lx *lexer) stateFn { + lx.esc = true + r := lx.next() + switch r { + case 'e': + if !lx.tomlNext { + return lx.error(errLexEscape{r}) + } + fallthrough + case 'b': + fallthrough + case 't': + fallthrough + case 'n': + fallthrough + case 'f': + fallthrough + case 'r': + fallthrough + case '"': + fallthrough + case ' ', '\t': + // Inside """ .. """ strings you can use \ to escape newlines, and any + // amount of whitespace can be between the \ and \n. + fallthrough + case '\\': + return lx.pop() + case 'x': + if !lx.tomlNext { + return lx.error(errLexEscape{r}) + } + return lexHexEscape + case 'u': + return lexShortUnicodeEscape + case 'U': + return lexLongUnicodeEscape + } + return lx.error(errLexEscape{r}) +} + +func lexHexEscape(lx *lexer) stateFn { + var r rune + for i := 0; i < 2; i++ { + r = lx.next() + if !isHex(r) { + return lx.errorf(`expected two hexadecimal digits after '\x', but got %q instead`, lx.current()) + } + } + return lx.pop() +} + +func lexShortUnicodeEscape(lx *lexer) stateFn { + var r rune + for i := 0; i < 4; i++ { + r = lx.next() + if !isHex(r) { + return lx.errorf(`expected four hexadecimal digits after '\u', but got %q instead`, lx.current()) + } + } + return lx.pop() +} + +func lexLongUnicodeEscape(lx *lexer) stateFn { + var r rune + for i := 0; i < 8; i++ { + r = lx.next() + if !isHex(r) { + return lx.errorf(`expected eight hexadecimal digits after '\U', but got %q instead`, lx.current()) + } + } + return lx.pop() +} + +// lexNumberOrDateStart processes the first character of a value which begins +// with a digit. It exists to catch values starting with '0', so that +// lexBaseNumberOrDate can differentiate base prefixed integers from other +// types. +func lexNumberOrDateStart(lx *lexer) stateFn { + r := lx.next() + switch r { + case '0': + return lexBaseNumberOrDate + } + + if !isDigit(r) { + // The only way to reach this state is if the value starts + // with a digit, so specifically treat anything else as an + // error. + return lx.errorf("expected a digit but got %q", r) + } + + return lexNumberOrDate +} + +// lexNumberOrDate consumes either an integer, float or datetime. +func lexNumberOrDate(lx *lexer) stateFn { + r := lx.next() + if isDigit(r) { + return lexNumberOrDate + } + switch r { + case '-', ':': + return lexDatetime + case '_': + return lexDecimalNumber + case '.', 'e', 'E': + return lexFloat + } + + lx.backup() + lx.emit(itemInteger) + return lx.pop() +} + +// lexDatetime consumes a Datetime, to a first approximation. +// The parser validates that it matches one of the accepted formats. +func lexDatetime(lx *lexer) stateFn { + r := lx.next() + if isDigit(r) { + return lexDatetime + } + switch r { + case '-', ':', 'T', 't', ' ', '.', 'Z', 'z', '+': + return lexDatetime + } + + lx.backup() + lx.emitTrim(itemDatetime) + return lx.pop() +} + +// lexHexInteger consumes a hexadecimal integer after seeing the '0x' prefix. +func lexHexInteger(lx *lexer) stateFn { + r := lx.next() + if isHex(r) { + return lexHexInteger + } + switch r { + case '_': + return lexHexInteger + } + + lx.backup() + lx.emit(itemInteger) + return lx.pop() +} + +// lexOctalInteger consumes an octal integer after seeing the '0o' prefix. +func lexOctalInteger(lx *lexer) stateFn { + r := lx.next() + if isOctal(r) { + return lexOctalInteger + } + switch r { + case '_': + return lexOctalInteger + } + + lx.backup() + lx.emit(itemInteger) + return lx.pop() +} + +// lexBinaryInteger consumes a binary integer after seeing the '0b' prefix. +func lexBinaryInteger(lx *lexer) stateFn { + r := lx.next() + if isBinary(r) { + return lexBinaryInteger + } + switch r { + case '_': + return lexBinaryInteger + } + + lx.backup() + lx.emit(itemInteger) + return lx.pop() +} + +// lexDecimalNumber consumes a decimal float or integer. +func lexDecimalNumber(lx *lexer) stateFn { + r := lx.next() + if isDigit(r) { + return lexDecimalNumber + } + switch r { + case '.', 'e', 'E': + return lexFloat + case '_': + return lexDecimalNumber + } + + lx.backup() + lx.emit(itemInteger) + return lx.pop() +} + +// lexDecimalNumber consumes the first digit of a number beginning with a sign. +// It assumes the sign has already been consumed. Values which start with a sign +// are only allowed to be decimal integers or floats. +// +// The special "nan" and "inf" values are also recognized. +func lexDecimalNumberStart(lx *lexer) stateFn { + r := lx.next() + + // Special error cases to give users better error messages + switch r { + case 'i': + if !lx.accept('n') || !lx.accept('f') { + return lx.errorf("invalid float: '%s'", lx.current()) + } + lx.emit(itemFloat) + return lx.pop() + case 'n': + if !lx.accept('a') || !lx.accept('n') { + return lx.errorf("invalid float: '%s'", lx.current()) + } + lx.emit(itemFloat) + return lx.pop() + case '0': + p := lx.peek() + switch p { + case 'b', 'o', 'x': + return lx.errorf("cannot use sign with non-decimal numbers: '%s%c'", lx.current(), p) + } + case '.': + return lx.errorf("floats must start with a digit, not '.'") + } + + if isDigit(r) { + return lexDecimalNumber + } + + return lx.errorf("expected a digit but got %q", r) +} + +// lexBaseNumberOrDate differentiates between the possible values which +// start with '0'. It assumes that before reaching this state, the initial '0' +// has been consumed. +func lexBaseNumberOrDate(lx *lexer) stateFn { + r := lx.next() + // Note: All datetimes start with at least two digits, so we don't + // handle date characters (':', '-', etc.) here. + if isDigit(r) { + return lexNumberOrDate + } + switch r { + case '_': + // Can only be decimal, because there can't be an underscore + // between the '0' and the base designator, and dates can't + // contain underscores. + return lexDecimalNumber + case '.', 'e', 'E': + return lexFloat + case 'b': + r = lx.peek() + if !isBinary(r) { + lx.errorf("not a binary number: '%s%c'", lx.current(), r) + } + return lexBinaryInteger + case 'o': + r = lx.peek() + if !isOctal(r) { + lx.errorf("not an octal number: '%s%c'", lx.current(), r) + } + return lexOctalInteger + case 'x': + r = lx.peek() + if !isHex(r) { + lx.errorf("not a hexadecimal number: '%s%c'", lx.current(), r) + } + return lexHexInteger + } + + lx.backup() + lx.emit(itemInteger) + return lx.pop() +} + +// lexFloat consumes the elements of a float. It allows any sequence of +// float-like characters, so floats emitted by the lexer are only a first +// approximation and must be validated by the parser. +func lexFloat(lx *lexer) stateFn { + r := lx.next() + if isDigit(r) { + return lexFloat + } + switch r { + case '_', '.', '-', '+', 'e', 'E': + return lexFloat + } + + lx.backup() + lx.emit(itemFloat) + return lx.pop() +} + +// lexBool consumes a bool string: 'true' or 'false. +func lexBool(lx *lexer) stateFn { + var rs []rune + for { + r := lx.next() + if !unicode.IsLetter(r) { + lx.backup() + break + } + rs = append(rs, r) + } + s := string(rs) + switch s { + case "true", "false": + lx.emit(itemBool) + return lx.pop() + } + return lx.errorf("expected value but found %q instead", s) +} + +// lexCommentStart begins the lexing of a comment. It will emit +// itemCommentStart and consume no characters, passing control to lexComment. +func lexCommentStart(lx *lexer) stateFn { + lx.ignore() + lx.emit(itemCommentStart) + return lexComment +} + +// lexComment lexes an entire comment. It assumes that '#' has been consumed. +// It will consume *up to* the first newline character, and pass control +// back to the last state on the stack. +func lexComment(lx *lexer) stateFn { + switch r := lx.next(); { + case isNL(r) || r == eof: + lx.backup() + lx.emit(itemText) + return lx.pop() + default: + return lexComment + } +} + +// lexSkip ignores all slurped input and moves on to the next state. +func lexSkip(lx *lexer, nextState stateFn) stateFn { + lx.ignore() + return nextState +} + +func (s stateFn) String() string { + name := runtime.FuncForPC(reflect.ValueOf(s).Pointer()).Name() + if i := strings.LastIndexByte(name, '.'); i > -1 { + name = name[i+1:] + } + if s == nil { + name = "" + } + return name + "()" +} + +func (itype itemType) String() string { + switch itype { + case itemError: + return "Error" + case itemNIL: + return "NIL" + case itemEOF: + return "EOF" + case itemText: + return "Text" + case itemString, itemStringEsc, itemRawString, itemMultilineString, itemRawMultilineString: + return "String" + case itemBool: + return "Bool" + case itemInteger: + return "Integer" + case itemFloat: + return "Float" + case itemDatetime: + return "DateTime" + case itemTableStart: + return "TableStart" + case itemTableEnd: + return "TableEnd" + case itemKeyStart: + return "KeyStart" + case itemKeyEnd: + return "KeyEnd" + case itemArray: + return "Array" + case itemArrayEnd: + return "ArrayEnd" + case itemCommentStart: + return "CommentStart" + case itemInlineTableStart: + return "InlineTableStart" + case itemInlineTableEnd: + return "InlineTableEnd" + } + panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype))) +} + +func (item item) String() string { + return fmt.Sprintf("(%s, %s)", item.typ, item.val) +} + +func isWhitespace(r rune) bool { return r == '\t' || r == ' ' } +func isNL(r rune) bool { return r == '\n' || r == '\r' } +func isControl(r rune) bool { // Control characters except \t, \r, \n + switch r { + case '\t', '\r', '\n': + return false + default: + return (r >= 0x00 && r <= 0x1f) || r == 0x7f + } +} +func isDigit(r rune) bool { return r >= '0' && r <= '9' } +func isBinary(r rune) bool { return r == '0' || r == '1' } +func isOctal(r rune) bool { return r >= '0' && r <= '7' } +func isHex(r rune) bool { return (r >= '0' && r <= '9') || (r|0x20 >= 'a' && r|0x20 <= 'f') } +func isBareKeyChar(r rune, tomlNext bool) bool { + return (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || + (r >= '0' && r <= '9') || r == '_' || r == '-' +} diff --git a/vendor/github.com/BurntSushi/toml/meta.go b/vendor/github.com/BurntSushi/toml/meta.go new file mode 100644 index 000000000..0d337026c --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/meta.go @@ -0,0 +1,145 @@ +package toml + +import ( + "strings" +) + +// MetaData allows access to meta information about TOML data that's not +// accessible otherwise. +// +// It allows checking if a key is defined in the TOML data, whether any keys +// were undecoded, and the TOML type of a key. +type MetaData struct { + context Key // Used only during decoding. + + keyInfo map[string]keyInfo + mapping map[string]any + keys []Key + decoded map[string]struct{} + data []byte // Input file; for errors. +} + +// IsDefined reports if the key exists in the TOML data. +// +// The key should be specified hierarchically, for example to access the TOML +// key "a.b.c" you would use IsDefined("a", "b", "c"). Keys are case sensitive. +// +// Returns false for an empty key. +func (md *MetaData) IsDefined(key ...string) bool { + if len(key) == 0 { + return false + } + + var ( + hash map[string]any + ok bool + hashOrVal any = md.mapping + ) + for _, k := range key { + if hash, ok = hashOrVal.(map[string]any); !ok { + return false + } + if hashOrVal, ok = hash[k]; !ok { + return false + } + } + return true +} + +// Type returns a string representation of the type of the key specified. +// +// Type will return the empty string if given an empty key or a key that does +// not exist. Keys are case sensitive. +func (md *MetaData) Type(key ...string) string { + if ki, ok := md.keyInfo[Key(key).String()]; ok { + return ki.tomlType.typeString() + } + return "" +} + +// Keys returns a slice of every key in the TOML data, including key groups. +// +// Each key is itself a slice, where the first element is the top of the +// hierarchy and the last is the most specific. The list will have the same +// order as the keys appeared in the TOML data. +// +// All keys returned are non-empty. +func (md *MetaData) Keys() []Key { + return md.keys +} + +// Undecoded returns all keys that have not been decoded in the order in which +// they appear in the original TOML document. +// +// This includes keys that haven't been decoded because of a [Primitive] value. +// Once the Primitive value is decoded, the keys will be considered decoded. +// +// Also note that decoding into an empty interface will result in no decoding, +// and so no keys will be considered decoded. +// +// In this sense, the Undecoded keys correspond to keys in the TOML document +// that do not have a concrete type in your representation. +func (md *MetaData) Undecoded() []Key { + undecoded := make([]Key, 0, len(md.keys)) + for _, key := range md.keys { + if _, ok := md.decoded[key.String()]; !ok { + undecoded = append(undecoded, key) + } + } + return undecoded +} + +// Key represents any TOML key, including key groups. Use [MetaData.Keys] to get +// values of this type. +type Key []string + +func (k Key) String() string { + // This is called quite often, so it's a bit funky to make it faster. + var b strings.Builder + b.Grow(len(k) * 25) +outer: + for i, kk := range k { + if i > 0 { + b.WriteByte('.') + } + if kk == "" { + b.WriteString(`""`) + } else { + for _, r := range kk { + // "Inline" isBareKeyChar + if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-') { + b.WriteByte('"') + b.WriteString(dblQuotedReplacer.Replace(kk)) + b.WriteByte('"') + continue outer + } + } + b.WriteString(kk) + } + } + return b.String() +} + +func (k Key) maybeQuoted(i int) string { + if k[i] == "" { + return `""` + } + for _, r := range k[i] { + if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' { + continue + } + return `"` + dblQuotedReplacer.Replace(k[i]) + `"` + } + return k[i] +} + +// Like append(), but only increase the cap by 1. +func (k Key) add(piece string) Key { + newKey := make(Key, len(k)+1) + copy(newKey, k) + newKey[len(k)] = piece + return newKey +} + +func (k Key) parent() Key { return k[:len(k)-1] } // all except the last piece. +func (k Key) last() string { return k[len(k)-1] } // last piece of this key. diff --git a/vendor/github.com/BurntSushi/toml/parse.go b/vendor/github.com/BurntSushi/toml/parse.go new file mode 100644 index 000000000..e3ea8a9a2 --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/parse.go @@ -0,0 +1,845 @@ +package toml + +import ( + "fmt" + "math" + "os" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/BurntSushi/toml/internal" +) + +type parser struct { + lx *lexer + context Key // Full key for the current hash in scope. + currentKey string // Base key name for everything except hashes. + pos Position // Current position in the TOML file. + tomlNext bool + + ordered []Key // List of keys in the order that they appear in the TOML data. + + keyInfo map[string]keyInfo // Map keyname → info about the TOML key. + mapping map[string]any // Map keyname → key value. + implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names"). +} + +type keyInfo struct { + pos Position + tomlType tomlType +} + +func parse(data string) (p *parser, err error) { + _, tomlNext := os.LookupEnv("BURNTSUSHI_TOML_110") + + defer func() { + if r := recover(); r != nil { + if pErr, ok := r.(ParseError); ok { + pErr.input = data + err = pErr + return + } + panic(r) + } + }() + + // Read over BOM; do this here as the lexer calls utf8.DecodeRuneInString() + // which mangles stuff. UTF-16 BOM isn't strictly valid, but some tools add + // it anyway. + if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { // UTF-16 + data = data[2:] + } else if strings.HasPrefix(data, "\xef\xbb\xbf") { // UTF-8 + data = data[3:] + } + + // Examine first few bytes for NULL bytes; this probably means it's a UTF-16 + // file (second byte in surrogate pair being NULL). Again, do this here to + // avoid having to deal with UTF-8/16 stuff in the lexer. + ex := 6 + if len(data) < 6 { + ex = len(data) + } + if i := strings.IndexRune(data[:ex], 0); i > -1 { + return nil, ParseError{ + Message: "files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8", + Position: Position{Line: 1, Col: 1, Start: i, Len: 1}, + Line: 1, + input: data, + } + } + + p = &parser{ + keyInfo: make(map[string]keyInfo), + mapping: make(map[string]any), + lx: lex(data, tomlNext), + ordered: make([]Key, 0), + implicits: make(map[string]struct{}), + tomlNext: tomlNext, + } + for { + item := p.next() + if item.typ == itemEOF { + break + } + p.topLevel(item) + } + + return p, nil +} + +func (p *parser) panicErr(it item, err error) { + panic(ParseError{ + Message: err.Error(), + err: err, + Position: it.pos.withCol(p.lx.input), + Line: it.pos.Len, + LastKey: p.current(), + }) +} + +func (p *parser) panicItemf(it item, format string, v ...any) { + panic(ParseError{ + Message: fmt.Sprintf(format, v...), + Position: it.pos.withCol(p.lx.input), + Line: it.pos.Len, + LastKey: p.current(), + }) +} + +func (p *parser) panicf(format string, v ...any) { + panic(ParseError{ + Message: fmt.Sprintf(format, v...), + Position: p.pos.withCol(p.lx.input), + Line: p.pos.Line, + LastKey: p.current(), + }) +} + +func (p *parser) next() item { + it := p.lx.nextItem() + //fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.pos.Line, it.val) + if it.typ == itemError { + if it.err != nil { + panic(ParseError{ + Message: it.err.Error(), + err: it.err, + Position: it.pos.withCol(p.lx.input), + Line: it.pos.Line, + LastKey: p.current(), + }) + } + + p.panicItemf(it, "%s", it.val) + } + return it +} + +func (p *parser) nextPos() item { + it := p.next() + p.pos = it.pos + return it +} + +func (p *parser) bug(format string, v ...any) { + panic(fmt.Sprintf("BUG: "+format+"\n\n", v...)) +} + +func (p *parser) expect(typ itemType) item { + it := p.next() + p.assertEqual(typ, it.typ) + return it +} + +func (p *parser) assertEqual(expected, got itemType) { + if expected != got { + p.bug("Expected '%s' but got '%s'.", expected, got) + } +} + +func (p *parser) topLevel(item item) { + switch item.typ { + case itemCommentStart: // # .. + p.expect(itemText) + case itemTableStart: // [ .. ] + name := p.nextPos() + + var key Key + for ; name.typ != itemTableEnd && name.typ != itemEOF; name = p.next() { + key = append(key, p.keyString(name)) + } + p.assertEqual(itemTableEnd, name.typ) + + p.addContext(key, false) + p.setType("", tomlHash, item.pos) + p.ordered = append(p.ordered, key) + case itemArrayTableStart: // [[ .. ]] + name := p.nextPos() + + var key Key + for ; name.typ != itemArrayTableEnd && name.typ != itemEOF; name = p.next() { + key = append(key, p.keyString(name)) + } + p.assertEqual(itemArrayTableEnd, name.typ) + + p.addContext(key, true) + p.setType("", tomlArrayHash, item.pos) + p.ordered = append(p.ordered, key) + case itemKeyStart: // key = .. + outerContext := p.context + /// Read all the key parts (e.g. 'a' and 'b' in 'a.b') + k := p.nextPos() + var key Key + for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() { + key = append(key, p.keyString(k)) + } + p.assertEqual(itemKeyEnd, k.typ) + + /// The current key is the last part. + p.currentKey = key.last() + + /// All the other parts (if any) are the context; need to set each part + /// as implicit. + context := key.parent() + for i := range context { + p.addImplicitContext(append(p.context, context[i:i+1]...)) + } + p.ordered = append(p.ordered, p.context.add(p.currentKey)) + + /// Set value. + vItem := p.next() + val, typ := p.value(vItem, false) + p.setValue(p.currentKey, val) + p.setType(p.currentKey, typ, vItem.pos) + + /// Remove the context we added (preserving any context from [tbl] lines). + p.context = outerContext + p.currentKey = "" + default: + p.bug("Unexpected type at top level: %s", item.typ) + } +} + +// Gets a string for a key (or part of a key in a table name). +func (p *parser) keyString(it item) string { + switch it.typ { + case itemText: + return it.val + case itemString, itemStringEsc, itemMultilineString, + itemRawString, itemRawMultilineString: + s, _ := p.value(it, false) + return s.(string) + default: + p.bug("Unexpected key type: %s", it.typ) + } + panic("unreachable") +} + +var datetimeRepl = strings.NewReplacer( + "z", "Z", + "t", "T", + " ", "T") + +// value translates an expected value from the lexer into a Go value wrapped +// as an empty interface. +func (p *parser) value(it item, parentIsArray bool) (any, tomlType) { + switch it.typ { + case itemString: + return it.val, p.typeOfPrimitive(it) + case itemStringEsc: + return p.replaceEscapes(it, it.val), p.typeOfPrimitive(it) + case itemMultilineString: + return p.replaceEscapes(it, p.stripEscapedNewlines(stripFirstNewline(it.val))), p.typeOfPrimitive(it) + case itemRawString: + return it.val, p.typeOfPrimitive(it) + case itemRawMultilineString: + return stripFirstNewline(it.val), p.typeOfPrimitive(it) + case itemInteger: + return p.valueInteger(it) + case itemFloat: + return p.valueFloat(it) + case itemBool: + switch it.val { + case "true": + return true, p.typeOfPrimitive(it) + case "false": + return false, p.typeOfPrimitive(it) + default: + p.bug("Expected boolean value, but got '%s'.", it.val) + } + case itemDatetime: + return p.valueDatetime(it) + case itemArray: + return p.valueArray(it) + case itemInlineTableStart: + return p.valueInlineTable(it, parentIsArray) + default: + p.bug("Unexpected value type: %s", it.typ) + } + panic("unreachable") +} + +func (p *parser) valueInteger(it item) (any, tomlType) { + if !numUnderscoresOK(it.val) { + p.panicItemf(it, "Invalid integer %q: underscores must be surrounded by digits", it.val) + } + if numHasLeadingZero(it.val) { + p.panicItemf(it, "Invalid integer %q: cannot have leading zeroes", it.val) + } + + num, err := strconv.ParseInt(it.val, 0, 64) + if err != nil { + // Distinguish integer values. Normally, it'd be a bug if the lexer + // provides an invalid integer, but it's possible that the number is + // out of range of valid values (which the lexer cannot determine). + // So mark the former as a bug but the latter as a legitimate user + // error. + if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { + p.panicErr(it, errParseRange{i: it.val, size: "int64"}) + } else { + p.bug("Expected integer value, but got '%s'.", it.val) + } + } + return num, p.typeOfPrimitive(it) +} + +func (p *parser) valueFloat(it item) (any, tomlType) { + parts := strings.FieldsFunc(it.val, func(r rune) bool { + switch r { + case '.', 'e', 'E': + return true + } + return false + }) + for _, part := range parts { + if !numUnderscoresOK(part) { + p.panicItemf(it, "Invalid float %q: underscores must be surrounded by digits", it.val) + } + } + if len(parts) > 0 && numHasLeadingZero(parts[0]) { + p.panicItemf(it, "Invalid float %q: cannot have leading zeroes", it.val) + } + if !numPeriodsOK(it.val) { + // As a special case, numbers like '123.' or '1.e2', + // which are valid as far as Go/strconv are concerned, + // must be rejected because TOML says that a fractional + // part consists of '.' followed by 1+ digits. + p.panicItemf(it, "Invalid float %q: '.' must be followed by one or more digits", it.val) + } + val := strings.Replace(it.val, "_", "", -1) + signbit := false + if val == "+nan" || val == "-nan" { + signbit = val == "-nan" + val = "nan" + } + num, err := strconv.ParseFloat(val, 64) + if err != nil { + if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { + p.panicErr(it, errParseRange{i: it.val, size: "float64"}) + } else { + p.panicItemf(it, "Invalid float value: %q", it.val) + } + } + if signbit { + num = math.Copysign(num, -1) + } + return num, p.typeOfPrimitive(it) +} + +var dtTypes = []struct { + fmt string + zone *time.Location + next bool +}{ + {time.RFC3339Nano, time.Local, false}, + {"2006-01-02T15:04:05.999999999", internal.LocalDatetime, false}, + {"2006-01-02", internal.LocalDate, false}, + {"15:04:05.999999999", internal.LocalTime, false}, + + // tomlNext + {"2006-01-02T15:04Z07:00", time.Local, true}, + {"2006-01-02T15:04", internal.LocalDatetime, true}, + {"15:04", internal.LocalTime, true}, +} + +func (p *parser) valueDatetime(it item) (any, tomlType) { + it.val = datetimeRepl.Replace(it.val) + var ( + t time.Time + ok bool + err error + ) + for _, dt := range dtTypes { + if dt.next && !p.tomlNext { + continue + } + t, err = time.ParseInLocation(dt.fmt, it.val, dt.zone) + if err == nil { + if missingLeadingZero(it.val, dt.fmt) { + p.panicErr(it, errParseDate{it.val}) + } + ok = true + break + } + } + if !ok { + p.panicErr(it, errParseDate{it.val}) + } + return t, p.typeOfPrimitive(it) +} + +// Go's time.Parse() will accept numbers without a leading zero; there isn't any +// way to require it. https://github.com/golang/go/issues/29911 +// +// Depend on the fact that the separators (- and :) should always be at the same +// location. +func missingLeadingZero(d, l string) bool { + for i, c := range []byte(l) { + if c == '.' || c == 'Z' { + return false + } + if (c < '0' || c > '9') && d[i] != c { + return true + } + } + return false +} + +func (p *parser) valueArray(it item) (any, tomlType) { + p.setType(p.currentKey, tomlArray, it.pos) + + var ( + // Initialize to a non-nil slice to make it consistent with how S = [] + // decodes into a non-nil slice inside something like struct { S + // []string }. See #338 + array = make([]any, 0, 2) + ) + for it = p.next(); it.typ != itemArrayEnd; it = p.next() { + if it.typ == itemCommentStart { + p.expect(itemText) + continue + } + + val, typ := p.value(it, true) + array = append(array, val) + + // XXX: type isn't used here, we need it to record the accurate type + // information. + // + // Not entirely sure how to best store this; could use "key[0]", + // "key[1]" notation, or maybe store it on the Array type? + _ = typ + } + return array, tomlArray +} + +func (p *parser) valueInlineTable(it item, parentIsArray bool) (any, tomlType) { + var ( + topHash = make(map[string]any) + outerContext = p.context + outerKey = p.currentKey + ) + + p.context = append(p.context, p.currentKey) + prevContext := p.context + p.currentKey = "" + + p.addImplicit(p.context) + p.addContext(p.context, parentIsArray) + + /// Loop over all table key/value pairs. + for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() { + if it.typ == itemCommentStart { + p.expect(itemText) + continue + } + + /// Read all key parts. + k := p.nextPos() + var key Key + for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() { + key = append(key, p.keyString(k)) + } + p.assertEqual(itemKeyEnd, k.typ) + + /// The current key is the last part. + p.currentKey = key.last() + + /// All the other parts (if any) are the context; need to set each part + /// as implicit. + context := key.parent() + for i := range context { + p.addImplicitContext(append(p.context, context[i:i+1]...)) + } + p.ordered = append(p.ordered, p.context.add(p.currentKey)) + + /// Set the value. + val, typ := p.value(p.next(), false) + p.setValue(p.currentKey, val) + p.setType(p.currentKey, typ, it.pos) + + hash := topHash + for _, c := range context { + h, ok := hash[c] + if !ok { + h = make(map[string]any) + hash[c] = h + } + hash, ok = h.(map[string]any) + if !ok { + p.panicf("%q is not a table", p.context) + } + } + hash[p.currentKey] = val + + /// Restore context. + p.context = prevContext + } + p.context = outerContext + p.currentKey = outerKey + return topHash, tomlHash +} + +// numHasLeadingZero checks if this number has leading zeroes, allowing for '0', +// +/- signs, and base prefixes. +func numHasLeadingZero(s string) bool { + if len(s) > 1 && s[0] == '0' && !(s[1] == 'b' || s[1] == 'o' || s[1] == 'x') { // Allow 0b, 0o, 0x + return true + } + if len(s) > 2 && (s[0] == '-' || s[0] == '+') && s[1] == '0' { + return true + } + return false +} + +// numUnderscoresOK checks whether each underscore in s is surrounded by +// characters that are not underscores. +func numUnderscoresOK(s string) bool { + switch s { + case "nan", "+nan", "-nan", "inf", "-inf", "+inf": + return true + } + accept := false + for _, r := range s { + if r == '_' { + if !accept { + return false + } + } + + // isHex is a superset of all the permissible characters surrounding an + // underscore. + accept = isHex(r) + } + return accept +} + +// numPeriodsOK checks whether every period in s is followed by a digit. +func numPeriodsOK(s string) bool { + period := false + for _, r := range s { + if period && !isDigit(r) { + return false + } + period = r == '.' + } + return !period +} + +// Set the current context of the parser, where the context is either a hash or +// an array of hashes, depending on the value of the `array` parameter. +// +// Establishing the context also makes sure that the key isn't a duplicate, and +// will create implicit hashes automatically. +func (p *parser) addContext(key Key, array bool) { + /// Always start at the top level and drill down for our context. + hashContext := p.mapping + keyContext := make(Key, 0, len(key)-1) + + /// We only need implicit hashes for the parents. + for _, k := range key.parent() { + _, ok := hashContext[k] + keyContext = append(keyContext, k) + + // No key? Make an implicit hash and move on. + if !ok { + p.addImplicit(keyContext) + hashContext[k] = make(map[string]any) + } + + // If the hash context is actually an array of tables, then set + // the hash context to the last element in that array. + // + // Otherwise, it better be a table, since this MUST be a key group (by + // virtue of it not being the last element in a key). + switch t := hashContext[k].(type) { + case []map[string]any: + hashContext = t[len(t)-1] + case map[string]any: + hashContext = t + default: + p.panicf("Key '%s' was already created as a hash.", keyContext) + } + } + + p.context = keyContext + if array { + // If this is the first element for this array, then allocate a new + // list of tables for it. + k := key.last() + if _, ok := hashContext[k]; !ok { + hashContext[k] = make([]map[string]any, 0, 4) + } + + // Add a new table. But make sure the key hasn't already been used + // for something else. + if hash, ok := hashContext[k].([]map[string]any); ok { + hashContext[k] = append(hash, make(map[string]any)) + } else { + p.panicf("Key '%s' was already created and cannot be used as an array.", key) + } + } else { + p.setValue(key.last(), make(map[string]any)) + } + p.context = append(p.context, key.last()) +} + +// setValue sets the given key to the given value in the current context. +// It will make sure that the key hasn't already been defined, account for +// implicit key groups. +func (p *parser) setValue(key string, value any) { + var ( + tmpHash any + ok bool + hash = p.mapping + keyContext = make(Key, 0, len(p.context)+1) + ) + for _, k := range p.context { + keyContext = append(keyContext, k) + if tmpHash, ok = hash[k]; !ok { + p.bug("Context for key '%s' has not been established.", keyContext) + } + switch t := tmpHash.(type) { + case []map[string]any: + // The context is a table of hashes. Pick the most recent table + // defined as the current hash. + hash = t[len(t)-1] + case map[string]any: + hash = t + default: + p.panicf("Key '%s' has already been defined.", keyContext) + } + } + keyContext = append(keyContext, key) + + if _, ok := hash[key]; ok { + // Normally redefining keys isn't allowed, but the key could have been + // defined implicitly and it's allowed to be redefined concretely. (See + // the `valid/implicit-and-explicit-after.toml` in toml-test) + // + // But we have to make sure to stop marking it as an implicit. (So that + // another redefinition provokes an error.) + // + // Note that since it has already been defined (as a hash), we don't + // want to overwrite it. So our business is done. + if p.isArray(keyContext) { + p.removeImplicit(keyContext) + hash[key] = value + return + } + if p.isImplicit(keyContext) { + p.removeImplicit(keyContext) + return + } + // Otherwise, we have a concrete key trying to override a previous key, + // which is *always* wrong. + p.panicf("Key '%s' has already been defined.", keyContext) + } + + hash[key] = value +} + +// setType sets the type of a particular value at a given key. It should be +// called immediately AFTER setValue. +// +// Note that if `key` is empty, then the type given will be applied to the +// current context (which is either a table or an array of tables). +func (p *parser) setType(key string, typ tomlType, pos Position) { + keyContext := make(Key, 0, len(p.context)+1) + keyContext = append(keyContext, p.context...) + if len(key) > 0 { // allow type setting for hashes + keyContext = append(keyContext, key) + } + // Special case to make empty keys ("" = 1) work. + // Without it it will set "" rather than `""`. + // TODO: why is this needed? And why is this only needed here? + if len(keyContext) == 0 { + keyContext = Key{""} + } + p.keyInfo[keyContext.String()] = keyInfo{tomlType: typ, pos: pos} +} + +// Implicit keys need to be created when tables are implied in "a.b.c.d = 1" and +// "[a.b.c]" (the "a", "b", and "c" hashes are never created explicitly). +func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} } +func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) } +func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok } +func (p *parser) isArray(key Key) bool { return p.keyInfo[key.String()].tomlType == tomlArray } +func (p *parser) addImplicitContext(key Key) { p.addImplicit(key); p.addContext(key, false) } + +// current returns the full key name of the current context. +func (p *parser) current() string { + if len(p.currentKey) == 0 { + return p.context.String() + } + if len(p.context) == 0 { + return p.currentKey + } + return fmt.Sprintf("%s.%s", p.context, p.currentKey) +} + +func stripFirstNewline(s string) string { + if len(s) > 0 && s[0] == '\n' { + return s[1:] + } + if len(s) > 1 && s[0] == '\r' && s[1] == '\n' { + return s[2:] + } + return s +} + +// stripEscapedNewlines removes whitespace after line-ending backslashes in +// multiline strings. +// +// A line-ending backslash is an unescaped \ followed only by whitespace until +// the next newline. After a line-ending backslash, all whitespace is removed +// until the next non-whitespace character. +func (p *parser) stripEscapedNewlines(s string) string { + var ( + b strings.Builder + i int + ) + b.Grow(len(s)) + for { + ix := strings.Index(s[i:], `\`) + if ix < 0 { + b.WriteString(s) + return b.String() + } + i += ix + + if len(s) > i+1 && s[i+1] == '\\' { + // Escaped backslash. + i += 2 + continue + } + // Scan until the next non-whitespace. + j := i + 1 + whitespaceLoop: + for ; j < len(s); j++ { + switch s[j] { + case ' ', '\t', '\r', '\n': + default: + break whitespaceLoop + } + } + if j == i+1 { + // Not a whitespace escape. + i++ + continue + } + if !strings.Contains(s[i:j], "\n") { + // This is not a line-ending backslash. (It's a bad escape sequence, + // but we can let replaceEscapes catch it.) + i++ + continue + } + b.WriteString(s[:i]) + s = s[j:] + i = 0 + } +} + +func (p *parser) replaceEscapes(it item, str string) string { + var ( + b strings.Builder + skip = 0 + ) + b.Grow(len(str)) + for i, c := range str { + if skip > 0 { + skip-- + continue + } + if c != '\\' { + b.WriteRune(c) + continue + } + + if i >= len(str) { + p.bug("Escape sequence at end of string.") + return "" + } + switch str[i+1] { + default: + p.bug("Expected valid escape code after \\, but got %q.", str[i+1]) + case ' ', '\t': + p.panicItemf(it, "invalid escape: '\\%c'", str[i+1]) + case 'b': + b.WriteByte(0x08) + skip = 1 + case 't': + b.WriteByte(0x09) + skip = 1 + case 'n': + b.WriteByte(0x0a) + skip = 1 + case 'f': + b.WriteByte(0x0c) + skip = 1 + case 'r': + b.WriteByte(0x0d) + skip = 1 + case 'e': + if p.tomlNext { + b.WriteByte(0x1b) + skip = 1 + } + case '"': + b.WriteByte(0x22) + skip = 1 + case '\\': + b.WriteByte(0x5c) + skip = 1 + // The lexer guarantees the correct number of characters are present; + // don't need to check here. + case 'x': + if p.tomlNext { + escaped := p.asciiEscapeToUnicode(it, str[i+2:i+4]) + b.WriteRune(escaped) + skip = 3 + } + case 'u': + escaped := p.asciiEscapeToUnicode(it, str[i+2:i+6]) + b.WriteRune(escaped) + skip = 5 + case 'U': + escaped := p.asciiEscapeToUnicode(it, str[i+2:i+10]) + b.WriteRune(escaped) + skip = 9 + } + } + return b.String() +} + +func (p *parser) asciiEscapeToUnicode(it item, s string) rune { + hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32) + if err != nil { + p.bug("Could not parse '%s' as a hexadecimal number, but the lexer claims it's OK: %s", s, err) + } + if !utf8.ValidRune(rune(hex)) { + p.panicItemf(it, "Escaped character '\\u%s' is not valid UTF-8.", s) + } + return rune(hex) +} diff --git a/vendor/github.com/BurntSushi/toml/type_fields.go b/vendor/github.com/BurntSushi/toml/type_fields.go new file mode 100644 index 000000000..10c51f7ee --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/type_fields.go @@ -0,0 +1,238 @@ +package toml + +// Struct field handling is adapted from code in encoding/json: +// +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the Go distribution. + +import ( + "reflect" + "sort" + "sync" +) + +// A field represents a single field found in a struct. +type field struct { + name string // the name of the field (`toml` tag included) + tag bool // whether field has a `toml` tag + index []int // represents the depth of an anonymous field + typ reflect.Type // the type of the field +} + +// byName sorts field by name, breaking ties with depth, +// then breaking ties with "name came from toml tag", then +// breaking ties with index sequence. +type byName []field + +func (x byName) Len() int { return len(x) } +func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } +func (x byName) Less(i, j int) bool { + if x[i].name != x[j].name { + return x[i].name < x[j].name + } + if len(x[i].index) != len(x[j].index) { + return len(x[i].index) < len(x[j].index) + } + if x[i].tag != x[j].tag { + return x[i].tag + } + return byIndex(x).Less(i, j) +} + +// byIndex sorts field by index sequence. +type byIndex []field + +func (x byIndex) Len() int { return len(x) } +func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } +func (x byIndex) Less(i, j int) bool { + for k, xik := range x[i].index { + if k >= len(x[j].index) { + return false + } + if xik != x[j].index[k] { + return xik < x[j].index[k] + } + } + return len(x[i].index) < len(x[j].index) +} + +// typeFields returns a list of fields that TOML should recognize for the given +// type. The algorithm is breadth-first search over the set of structs to +// include - the top struct and then any reachable anonymous structs. +func typeFields(t reflect.Type) []field { + // Anonymous fields to explore at the current level and the next. + current := []field{} + next := []field{{typ: t}} + + // Count of queued names for current level and the next. + var count map[reflect.Type]int + var nextCount map[reflect.Type]int + + // Types already visited at an earlier level. + visited := map[reflect.Type]bool{} + + // Fields found. + var fields []field + + for len(next) > 0 { + current, next = next, current[:0] + count, nextCount = nextCount, map[reflect.Type]int{} + + for _, f := range current { + if visited[f.typ] { + continue + } + visited[f.typ] = true + + // Scan f.typ for fields to include. + for i := 0; i < f.typ.NumField(); i++ { + sf := f.typ.Field(i) + if sf.PkgPath != "" && !sf.Anonymous { // unexported + continue + } + opts := getOptions(sf.Tag) + if opts.skip { + continue + } + index := make([]int, len(f.index)+1) + copy(index, f.index) + index[len(f.index)] = i + + ft := sf.Type + if ft.Name() == "" && ft.Kind() == reflect.Ptr { + // Follow pointer. + ft = ft.Elem() + } + + // Record found field and index sequence. + if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { + tagged := opts.name != "" + name := opts.name + if name == "" { + name = sf.Name + } + fields = append(fields, field{name, tagged, index, ft}) + if count[f.typ] > 1 { + // If there were multiple instances, add a second, + // so that the annihilation code will see a duplicate. + // It only cares about the distinction between 1 or 2, + // so don't bother generating any more copies. + fields = append(fields, fields[len(fields)-1]) + } + continue + } + + // Record new anonymous struct to explore in next round. + nextCount[ft]++ + if nextCount[ft] == 1 { + f := field{name: ft.Name(), index: index, typ: ft} + next = append(next, f) + } + } + } + } + + sort.Sort(byName(fields)) + + // Delete all fields that are hidden by the Go rules for embedded fields, + // except that fields with TOML tags are promoted. + + // The fields are sorted in primary order of name, secondary order + // of field index length. Loop over names; for each name, delete + // hidden fields by choosing the one dominant field that survives. + out := fields[:0] + for advance, i := 0, 0; i < len(fields); i += advance { + // One iteration per name. + // Find the sequence of fields with the name of this first field. + fi := fields[i] + name := fi.name + for advance = 1; i+advance < len(fields); advance++ { + fj := fields[i+advance] + if fj.name != name { + break + } + } + if advance == 1 { // Only one field with this name + out = append(out, fi) + continue + } + dominant, ok := dominantField(fields[i : i+advance]) + if ok { + out = append(out, dominant) + } + } + + fields = out + sort.Sort(byIndex(fields)) + + return fields +} + +// dominantField looks through the fields, all of which are known to +// have the same name, to find the single field that dominates the +// others using Go's embedding rules, modified by the presence of +// TOML tags. If there are multiple top-level fields, the boolean +// will be false: This condition is an error in Go and we skip all +// the fields. +func dominantField(fields []field) (field, bool) { + // The fields are sorted in increasing index-length order. The winner + // must therefore be one with the shortest index length. Drop all + // longer entries, which is easy: just truncate the slice. + length := len(fields[0].index) + tagged := -1 // Index of first tagged field. + for i, f := range fields { + if len(f.index) > length { + fields = fields[:i] + break + } + if f.tag { + if tagged >= 0 { + // Multiple tagged fields at the same level: conflict. + // Return no field. + return field{}, false + } + tagged = i + } + } + if tagged >= 0 { + return fields[tagged], true + } + // All remaining fields have the same length. If there's more than one, + // we have a conflict (two fields named "X" at the same level) and we + // return no field. + if len(fields) > 1 { + return field{}, false + } + return fields[0], true +} + +var fieldCache struct { + sync.RWMutex + m map[reflect.Type][]field +} + +// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. +func cachedTypeFields(t reflect.Type) []field { + fieldCache.RLock() + f := fieldCache.m[t] + fieldCache.RUnlock() + if f != nil { + return f + } + + // Compute fields without lock. + // Might duplicate effort but won't hold other computations back. + f = typeFields(t) + if f == nil { + f = []field{} + } + + fieldCache.Lock() + if fieldCache.m == nil { + fieldCache.m = map[reflect.Type][]field{} + } + fieldCache.m[t] = f + fieldCache.Unlock() + return f +} diff --git a/vendor/github.com/BurntSushi/toml/type_toml.go b/vendor/github.com/BurntSushi/toml/type_toml.go new file mode 100644 index 000000000..1c090d331 --- /dev/null +++ b/vendor/github.com/BurntSushi/toml/type_toml.go @@ -0,0 +1,65 @@ +package toml + +// tomlType represents any Go type that corresponds to a TOML type. +// While the first draft of the TOML spec has a simplistic type system that +// probably doesn't need this level of sophistication, we seem to be militating +// toward adding real composite types. +type tomlType interface { + typeString() string +} + +// typeEqual accepts any two types and returns true if they are equal. +func typeEqual(t1, t2 tomlType) bool { + if t1 == nil || t2 == nil { + return false + } + return t1.typeString() == t2.typeString() +} + +func typeIsTable(t tomlType) bool { + return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash) +} + +type tomlBaseType string + +func (btype tomlBaseType) typeString() string { return string(btype) } +func (btype tomlBaseType) String() string { return btype.typeString() } + +var ( + tomlInteger tomlBaseType = "Integer" + tomlFloat tomlBaseType = "Float" + tomlDatetime tomlBaseType = "Datetime" + tomlString tomlBaseType = "String" + tomlBool tomlBaseType = "Bool" + tomlArray tomlBaseType = "Array" + tomlHash tomlBaseType = "Hash" + tomlArrayHash tomlBaseType = "ArrayHash" +) + +// typeOfPrimitive returns a tomlType of any primitive value in TOML. +// Primitive values are: Integer, Float, Datetime, String and Bool. +// +// Passing a lexer item other than the following will cause a BUG message +// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime. +func (p *parser) typeOfPrimitive(lexItem item) tomlType { + switch lexItem.typ { + case itemInteger: + return tomlInteger + case itemFloat: + return tomlFloat + case itemDatetime: + return tomlDatetime + case itemString, itemStringEsc: + return tomlString + case itemMultilineString: + return tomlString + case itemRawString: + return tomlString + case itemRawMultilineString: + return tomlString + case itemBool: + return tomlBool + } + p.bug("Cannot infer primitive type of lex item '%s'.", lexItem) + panic("unreachable") +} diff --git a/vendor/github.com/KyleBanks/depth/.gitignore b/vendor/github.com/KyleBanks/depth/.gitignore new file mode 100644 index 000000000..8c2e171ea --- /dev/null +++ b/vendor/github.com/KyleBanks/depth/.gitignore @@ -0,0 +1,16 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ + +bin/ diff --git a/vendor/github.com/KyleBanks/depth/.travis.yml b/vendor/github.com/KyleBanks/depth/.travis.yml new file mode 100644 index 000000000..ab506f939 --- /dev/null +++ b/vendor/github.com/KyleBanks/depth/.travis.yml @@ -0,0 +1,9 @@ +language: go +sudo: false +go: + - 1.9.x +before_install: + - go get github.com/mattn/goveralls +script: + - $HOME/gopath/bin/goveralls -service=travis-ci +#script: go test $(go list ./... | grep -v vendor/) diff --git a/vendor/github.com/KyleBanks/depth/LICENSE b/vendor/github.com/KyleBanks/depth/LICENSE new file mode 100644 index 000000000..070b426b8 --- /dev/null +++ b/vendor/github.com/KyleBanks/depth/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Kyle Banks + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/KyleBanks/depth/Makefile b/vendor/github.com/KyleBanks/depth/Makefile new file mode 100644 index 000000000..acd35bb41 --- /dev/null +++ b/vendor/github.com/KyleBanks/depth/Makefile @@ -0,0 +1,32 @@ +VERSION = 1.2.1 + +RELEASE_PKG = ./cmd/depth +INSTALL_PKG = $(RELEASE_PKG) + + +# Remote includes require 'mmake' +# github.com/tj/mmake +include github.com/KyleBanks/make/go/install +include github.com/KyleBanks/make/go/sanity +include github.com/KyleBanks/make/go/release +include github.com/KyleBanks/make/go/bench +include github.com/KyleBanks/make/git/precommit + +# Runs a number of depth commands as examples of what's possible. +example: | install + depth github.com/KyleBanks/depth/cmd/depth strings ./ + + depth -internal strings + + depth -json github.com/KyleBanks/depth/cmd/depth + + depth -test github.com/KyleBanks/depth/cmd/depth + + depth -test -internal strings + + depth -test -internal -max 3 strings + + depth . + + depth ./cmd/depth +.PHONY: example diff --git a/vendor/github.com/KyleBanks/depth/README.md b/vendor/github.com/KyleBanks/depth/README.md new file mode 100644 index 000000000..0de954fd3 --- /dev/null +++ b/vendor/github.com/KyleBanks/depth/README.md @@ -0,0 +1,232 @@ +# depth + +[![GoDoc](https://godoc.org/github.com/KyleBanks/depth?status.svg)](https://godoc.org/github.com/KyleBanks/depth)  +[![Build Status](https://travis-ci.org/KyleBanks/depth.svg?branch=master)](https://travis-ci.org/KyleBanks/depth)  +[![Go Report Card](https://goreportcard.com/badge/github.com/KyleBanks/depth)](https://goreportcard.com/report/github.com/KyleBanks/depth)  +[![Coverage Status](https://coveralls.io/repos/github/KyleBanks/depth/badge.svg?branch=master)](https://coveralls.io/github/KyleBanks/depth?branch=master) + +`depth` is tool to retrieve and visualize Go source code dependency trees. + +## Install + +Download the appropriate binary for your platform from the [Releases](https://github.com/KyleBanks/depth/releases) page, or: + +```sh +go get github.com/KyleBanks/depth/cmd/depth +``` + +## Usage + +`depth` can be used as a standalone command-line application, or as a package within your own project. + +### Command-Line + +Simply execute `depth` with one or more package names to visualize. You can use the fully qualified import path of the package, like so: + +```sh +$ depth github.com/KyleBanks/depth/cmd/depth +github.com/KyleBanks/depth/cmd/depth + ├ encoding/json + ├ flag + ├ fmt + ├ io + ├ log + ├ os + ├ strings + └ github.com/KyleBanks/depth + ├ fmt + ├ go/build + ├ path + ├ sort + └ strings +12 dependencies (11 internal, 1 external, 0 testing). +``` + +Or you can use a relative path, for example: + +```sh +$ depth . +$ depth ./cmd/depth +$ depth ../ +``` + +You can also use `depth` on the Go standard library: + +```sh +$ depth strings +strings + ├ errors + ├ io + ├ unicode + └ unicode/utf8 +5 dependencies (5 internal, 0 external, 0 testing). +``` + +Visualizing multiple packages at a time is supported by simply naming the packages you'd like to visualize: + +```sh +$ depth strings github.com/KyleBanks/depth +strings + ├ errors + ├ io + ├ unicode + └ unicode/utf8 +5 dependencies (5 internal, 0 external, 0 testing). +github.com/KyleBanks/depth + ├ fmt + ├ go/build + ├ path + ├ sort + └ strings +7 dependencies (7 internal, 0 external, 0 testing). +``` + +#### `-internal` + +By default, `depth` only resolves the top level of dependencies for standard library packages, however you can use the `-internal` flag to visualize all internal dependencies: + +```sh +$ depth -internal strings +strings + ├ errors + ├ io + ├ errors + └ sync + ├ internal/race + └ unsafe + ├ runtime + ├ runtime/internal/atomic + └ unsafe + ├ runtime/internal/sys + └ unsafe + ├ sync/atomic + └ unsafe + └ unsafe + ├ unicode + └ unicode/utf8 +12 dependencies (12 internal, 0 external, 0 testing). +``` + +#### `-max` + +The `-max` flag limits the dependency tree to the maximum depth provided. For example, if you supply `-max 1` on the `depth` package, your output would look like so: + +``` +$ depth -max 1 github.com/KyleBanks/depth/cmd/depth +github.com/KyleBanks/depth/cmd/depth + ├ encoding/json + ├ flag + ├ fmt + ├ io + ├ log + ├ os + ├ strings + └ github.com/KyleBanks/depth +7 dependencies (6 internal, 1 external, 0 testing). +``` + +The `-max` flag is particularly useful in conjunction with the `-internal` flag which can lead to very deep dependency trees. + +#### `-test` + +By default, `depth` ignores dependencies that are only required for testing. However, you can view test dependencies using the `-test` flag: + +```sh +$ depth -test strings +strings + ├ bytes + ├ errors + ├ fmt + ├ io + ├ io/ioutil + ├ math/rand + ├ reflect + ├ sync + ├ testing + ├ unicode + ├ unicode/utf8 + └ unsafe +13 dependencies (13 internal, 0 external, 8 testing). +``` + +#### `-explain target-package` + +The `-explain` flag instructs `depth` to print import chains in which the +`target-package` is found: + +```sh +$ depth -explain strings github.com/KyleBanks/depth/cmd/depth +github.com/KyleBanks/depth/cmd/depth -> strings +github.com/KyleBanks/depth/cmd/depth -> github.com/KyleBanks/depth -> strings +``` + +#### `-json` + +The `-json` flag instructs `depth` to output dependencies in JSON format: + +```sh +$ depth -json github.com/KyleBanks/depth/cmd/depth +{ + "name": "github.com/KyleBanks/depth/cmd/depth", + "deps": [ + { + "name": "encoding/json", + "internal": true, + "deps": null + }, + ... + { + "name": "github.com/KyleBanks/depth", + "internal": false, + "deps": [ + { + "name": "go/build", + "internal": true, + "deps": null + }, + ... + ] + } + ] +} +``` + +### Integrating With Your Project + +The `depth` package can easily be used to retrieve the dependency tree for a particular package in your own project. For example, here's how you would retrieve the dependency tree for the `strings` package: + +```go +import "github.com/KyleBanks/depth" + +var t depth.Tree +err := t.Resolve("strings") +if err != nil { + log.Fatal(err) +} + +// Output: "'strings' has 4 dependencies." +log.Printf("'%v' has %v dependencies.", t.Root.Name, len(t.Root.Deps)) +``` + +For additional customization, simply set the appropriate flags on the `Tree` before resolving: + +```go +import "github.com/KyleBanks/depth" + +t := depth.Tree { + ResolveInternal: true, + ResolveTest: true, + MaxDepth: 10, +} + + +err := t.Resolve("strings") +``` + +## Author + +`depth` was developed by [Kyle Banks](https://twitter.com/kylewbanks). + +## License + +`depth` is available under the [MIT](./LICENSE) license. diff --git a/vendor/github.com/KyleBanks/depth/depth.go b/vendor/github.com/KyleBanks/depth/depth.go new file mode 100644 index 000000000..115c28ac9 --- /dev/null +++ b/vendor/github.com/KyleBanks/depth/depth.go @@ -0,0 +1,129 @@ +// Package depth provides the ability to traverse and retrieve Go source code dependencies in the form of +// internal and external packages. +// +// For example, the dependencies of the stdlib `strings` package can be resolved like so: +// +// import "github.com/KyleBanks/depth" +// +// var t depth.Tree +// err := t.Resolve("strings") +// if err != nil { +// log.Fatal(err) +// } +// +// // Output: "strings has 4 dependencies." +// log.Printf("%v has %v dependencies.", t.Root.Name, len(t.Root.Deps)) +// +// For additional customization, simply set the appropriate flags on the `Tree` before resolving: +// +// import "github.com/KyleBanks/depth" +// +// t := depth.Tree { +// ResolveInternal: true, +// ResolveTest: true, +// MaxDepth: 10, +// } +// err := t.Resolve("strings") +package depth + +import ( + "errors" + "go/build" + "os" +) + +// ErrRootPkgNotResolved is returned when the root Pkg of the Tree cannot be resolved, +// typically because it does not exist. +var ErrRootPkgNotResolved = errors.New("unable to resolve root package") + +// Importer defines a type that can import a package and return its details. +type Importer interface { + Import(name, srcDir string, im build.ImportMode) (*build.Package, error) +} + +// Tree represents the top level of a Pkg and the configuration used to +// initialize and represent its contents. +type Tree struct { + Root *Pkg + + ResolveInternal bool + ResolveTest bool + MaxDepth int + + Importer Importer + + importCache map[string]struct{} +} + +// Resolve recursively finds all dependencies for the root Pkg name provided, +// and the packages it depends on. +func (t *Tree) Resolve(name string) error { + pwd, err := os.Getwd() + if err != nil { + return err + } + + t.Root = &Pkg{ + Name: name, + Tree: t, + SrcDir: pwd, + Test: false, + } + + // Reset the import cache each time to ensure a reused Tree doesn't + // reuse the same cache. + t.importCache = nil + + // Allow custom importers, but use build.Default if none is provided. + if t.Importer == nil { + t.Importer = &build.Default + } + + t.Root.Resolve(t.Importer) + if !t.Root.Resolved { + return ErrRootPkgNotResolved + } + + return nil +} + +// shouldResolveInternal determines if internal packages should be further resolved beyond the +// current parent. +// +// For example, if the parent Pkg is `github.com/foo/bar` and true is returned, all the +// internal dependencies it relies on will be resolved. If for example `strings` is one of those +// dependencies, and it is passed as the parent here, false may be returned and its internal +// dependencies will not be resolved. +func (t *Tree) shouldResolveInternal(parent *Pkg) bool { + if t.ResolveInternal { + return true + } + + return parent == t.Root +} + +// isAtMaxDepth returns true when the depth of the Pkg provided is at or beyond the maximum +// depth allowed by the tree. +// +// If the Tree has a MaxDepth of zero, true is never returned. +func (t *Tree) isAtMaxDepth(p *Pkg) bool { + if t.MaxDepth == 0 { + return false + } + + return p.depth() >= t.MaxDepth +} + +// hasSeenImport returns true if the import name provided has already been seen within the tree. +// This function only returns false for a name once. +func (t *Tree) hasSeenImport(name string) bool { + if t.importCache == nil { + t.importCache = make(map[string]struct{}) + } + + if _, ok := t.importCache[name]; ok { + return true + } + t.importCache[name] = struct{}{} + return false +} diff --git a/vendor/github.com/KyleBanks/depth/pkg.go b/vendor/github.com/KyleBanks/depth/pkg.go new file mode 100644 index 000000000..1d54d717d --- /dev/null +++ b/vendor/github.com/KyleBanks/depth/pkg.go @@ -0,0 +1,184 @@ +package depth + +import ( + "bytes" + "go/build" + "path" + "sort" + "strings" +) + +// Pkg represents a Go source package, and its dependencies. +type Pkg struct { + Name string `json:"name"` + SrcDir string `json:"-"` + + Internal bool `json:"internal"` + Resolved bool `json:"resolved"` + Test bool `json:"-"` + + Tree *Tree `json:"-"` + Parent *Pkg `json:"-"` + Deps []Pkg `json:"deps"` + + Raw *build.Package `json:"-"` +} + +// Resolve recursively finds all dependencies for the Pkg and the packages it depends on. +func (p *Pkg) Resolve(i Importer) { + // Resolved is always true, regardless of if we skip the import, + // it is only false if there is an error while importing. + p.Resolved = true + + name := p.cleanName() + if name == "" { + return + } + + // Stop resolving imports if we've reached max depth or found a duplicate. + var importMode build.ImportMode + if p.Tree.hasSeenImport(name) || p.Tree.isAtMaxDepth(p) { + importMode = build.FindOnly + } + + pkg, err := i.Import(name, p.SrcDir, importMode) + if err != nil { + // TODO: Check the error type? + p.Resolved = false + return + } + p.Raw = pkg + + // Update the name with the fully qualified import path. + p.Name = pkg.ImportPath + + // If this is an internal dependency, we may need to skip it. + if pkg.Goroot { + p.Internal = true + if !p.Tree.shouldResolveInternal(p) { + return + } + } + + //first we set the regular dependencies, then we add the test dependencies + //sharing the same set. This allows us to mark all test-only deps linearly + unique := make(map[string]struct{}) + p.setDeps(i, pkg.Imports, pkg.Dir, unique, false) + if p.Tree.ResolveTest { + p.setDeps(i, append(pkg.TestImports, pkg.XTestImports...), pkg.Dir, unique, true) + } +} + +// setDeps takes a slice of import paths and the source directory they are relative to, +// and creates the Deps of the Pkg. Each dependency is also further resolved prior to being added +// to the Pkg. +func (p *Pkg) setDeps(i Importer, imports []string, srcDir string, unique map[string]struct{}, isTest bool) { + for _, imp := range imports { + // Mostly for testing files where cyclic imports are allowed. + if imp == p.Name { + continue + } + + // Skip duplicates. + if _, ok := unique[imp]; ok { + continue + } + unique[imp] = struct{}{} + + p.addDep(i, imp, srcDir, isTest) + } + + sort.Sort(byInternalAndName(p.Deps)) +} + +// addDep creates a Pkg and it's dependencies from an imported package name. +func (p *Pkg) addDep(i Importer, name string, srcDir string, isTest bool) { + dep := Pkg{ + Name: name, + SrcDir: srcDir, + Tree: p.Tree, + Parent: p, + Test: isTest, + } + dep.Resolve(i) + + p.Deps = append(p.Deps, dep) +} + +// isParent goes recursively up the chain of Pkgs to determine if the name provided is ever a +// parent of the current Pkg. +func (p *Pkg) isParent(name string) bool { + if p.Parent == nil { + return false + } + + if p.Parent.Name == name { + return true + } + + return p.Parent.isParent(name) +} + +// depth returns the depth of the Pkg within the Tree. +func (p *Pkg) depth() int { + if p.Parent == nil { + return 0 + } + + return p.Parent.depth() + 1 +} + +// cleanName returns a cleaned version of the Pkg name used for resolving dependencies. +// +// If an empty string is returned, dependencies should not be resolved. +func (p *Pkg) cleanName() string { + name := p.Name + + // C 'package' cannot be resolved. + if name == "C" { + return "" + } + + // Internal golang_org/* packages must be prefixed with vendor/ + // + // Thanks to @davecheney for this: + // https://github.com/davecheney/graphpkg/blob/master/main.go#L46 + if strings.HasPrefix(name, "golang_org") { + name = path.Join("vendor", name) + } + + return name +} + +// String returns a string representation of the Pkg containing the Pkg name and status. +func (p *Pkg) String() string { + b := bytes.NewBufferString(p.Name) + + if !p.Resolved { + b.Write([]byte(" (unresolved)")) + } + + return b.String() +} + +// byInternalAndName ensures a slice of Pkgs are sorted such that the internal stdlib +// packages are always above external packages (ie. github.com/whatever). +type byInternalAndName []Pkg + +func (b byInternalAndName) Len() int { + return len(b) +} + +func (b byInternalAndName) Swap(i, j int) { + b[i], b[j] = b[j], b[i] +} + +func (b byInternalAndName) Less(i, j int) bool { + if b[i].Internal && !b[j].Internal { + return true + } else if !b[i].Internal && b[j].Internal { + return false + } + + return b[i].Name < b[j].Name +} diff --git a/vendor/github.com/PuerkitoBio/purell/.gitignore b/vendor/github.com/PuerkitoBio/purell/.gitignore new file mode 100644 index 000000000..748e4c807 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/.gitignore @@ -0,0 +1,5 @@ +*.sublime-* +.DS_Store +*.swp +*.swo +tags diff --git a/vendor/github.com/PuerkitoBio/purell/.travis.yml b/vendor/github.com/PuerkitoBio/purell/.travis.yml new file mode 100644 index 000000000..cf31e6af6 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/.travis.yml @@ -0,0 +1,12 @@ +language: go + +go: + - 1.4.x + - 1.5.x + - 1.6.x + - 1.7.x + - 1.8.x + - 1.9.x + - "1.10.x" + - "1.11.x" + - tip diff --git a/vendor/github.com/PuerkitoBio/purell/LICENSE b/vendor/github.com/PuerkitoBio/purell/LICENSE new file mode 100644 index 000000000..4b9986dea --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/LICENSE @@ -0,0 +1,12 @@ +Copyright (c) 2012, Martin Angers +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/PuerkitoBio/purell/README.md b/vendor/github.com/PuerkitoBio/purell/README.md new file mode 100644 index 000000000..07de0c498 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/README.md @@ -0,0 +1,188 @@ +# Purell + +Purell is a tiny Go library to normalize URLs. It returns a pure URL. Pure-ell. Sanitizer and all. Yeah, I know... + +Based on the [wikipedia paper][wiki] and the [RFC 3986 document][rfc]. + +[![build status](https://travis-ci.org/PuerkitoBio/purell.svg?branch=master)](http://travis-ci.org/PuerkitoBio/purell) + +## Install + +`go get github.com/PuerkitoBio/purell` + +## Changelog + +* **v1.1.1** : Fix failing test due to Go1.12 changes (thanks to @ianlancetaylor). +* **2016-11-14 (v1.1.0)** : IDN: Conform to RFC 5895: Fold character width (thanks to @beeker1121). +* **2016-07-27 (v1.0.0)** : Normalize IDN to ASCII (thanks to @zenovich). +* **2015-02-08** : Add fix for relative paths issue ([PR #5][pr5]) and add fix for unnecessary encoding of reserved characters ([see issue #7][iss7]). +* **v0.2.0** : Add benchmarks, Attempt IDN support. +* **v0.1.0** : Initial release. + +## Examples + +From `example_test.go` (note that in your code, you would import "github.com/PuerkitoBio/purell", and would prefix references to its methods and constants with "purell."): + +```go +package purell + +import ( + "fmt" + "net/url" +) + +func ExampleNormalizeURLString() { + if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", + FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { + panic(err) + } else { + fmt.Print(normalized) + } + // Output: http://somewebsite.com:80/Amazing%3F/url/ +} + +func ExampleMustNormalizeURLString() { + normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", + FlagsUnsafeGreedy) + fmt.Print(normalized) + + // Output: http://somewebsite.com/Amazing%FA/url +} + +func ExampleNormalizeURL() { + if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { + panic(err) + } else { + normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) + fmt.Print(normalized) + } + + // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 +} +``` + +## API + +As seen in the examples above, purell offers three methods, `NormalizeURLString(string, NormalizationFlags) (string, error)`, `MustNormalizeURLString(string, NormalizationFlags) (string)` and `NormalizeURL(*url.URL, NormalizationFlags) (string)`. They all normalize the provided URL based on the specified flags. Here are the available flags: + +```go +const ( + // Safe normalizations + FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 + FlagLowercaseHost // http://HOST -> http://host + FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF + FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA + FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ + FlagRemoveDefaultPort // http://host:80 -> http://host + FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path + + // Usually safe normalizations + FlagRemoveTrailingSlash // http://host/path/ -> http://host/path + FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) + FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c + + // Unsafe normalizations + FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ + FlagRemoveFragment // http://host/path#fragment -> http://host/path + FlagForceHTTP // https://host -> http://host + FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b + FlagRemoveWWW // http://www.host/ -> http://host/ + FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) + FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 + + // Normalizations not in the wikipedia article, required to cover tests cases + // submitted by jehiah + FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 + FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 + FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 + FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path + FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path + + // Convenience set of safe normalizations + FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator + + // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, + // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". + + // Convenience set of usually safe normalizations (includes FlagsSafe) + FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments + FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments + + // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) + FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery + FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery + + // Convenience set of all available flags + FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator + FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator +) +``` + +For convenience, the set of flags `FlagsSafe`, `FlagsUsuallySafe[Greedy|NonGreedy]`, `FlagsUnsafe[Greedy|NonGreedy]` and `FlagsAll[Greedy|NonGreedy]` are provided for the similarly grouped normalizations on [wikipedia's URL normalization page][wiki]. You can add (using the bitwise OR `|` operator) or remove (using the bitwise AND NOT `&^` operator) individual flags from the sets if required, to build your own custom set. + +The [full godoc reference is available on gopkgdoc][godoc]. + +Some things to note: + +* `FlagDecodeUnnecessaryEscapes`, `FlagEncodeNecessaryEscapes`, `FlagUppercaseEscapes` and `FlagRemoveEmptyQuerySeparator` are always implicitly set, because internally, the URL string is parsed as an URL object, which automatically decodes unnecessary escapes, uppercases and encodes necessary ones, and removes empty query separators (an unnecessary `?` at the end of the url). So this operation cannot **not** be done. For this reason, `FlagRemoveEmptyQuerySeparator` (as well as the other three) has been included in the `FlagsSafe` convenience set, instead of `FlagsUnsafe`, where Wikipedia puts it. + +* The `FlagDecodeUnnecessaryEscapes` decodes the following escapes (*from -> to*): + - %24 -> $ + - %26 -> & + - %2B-%3B -> +,-./0123456789:; + - %3D -> = + - %40-%5A -> @ABCDEFGHIJKLMNOPQRSTUVWXYZ + - %5F -> _ + - %61-%7A -> abcdefghijklmnopqrstuvwxyz + - %7E -> ~ + + +* When the `NormalizeURL` function is used (passing an URL object), this source URL object is modified (that is, after the call, the URL object will be modified to reflect the normalization). + +* The *replace IP with domain name* normalization (`http://208.77.188.166/ → http://www.example.com/`) is obviously not possible for a library without making some network requests. This is not implemented in purell. + +* The *remove unused query string parameters* and *remove default query parameters* are also not implemented, since this is a very case-specific normalization, and it is quite trivial to do with an URL object. + +### Safe vs Usually Safe vs Unsafe + +Purell allows you to control the level of risk you take while normalizing an URL. You can aggressively normalize, play it totally safe, or anything in between. + +Consider the following URL: + +`HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` + +Normalizing with the `FlagsSafe` gives: + +`https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` + +With the `FlagsUsuallySafeGreedy`: + +`https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid` + +And with `FlagsUnsafeGreedy`: + +`http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3` + +## TODOs + +* Add a class/default instance to allow specifying custom directory index names? At the moment, removing directory index removes `(^|/)((?:default|index)\.\w{1,4})$`. + +## Thanks / Contributions + +@rogpeppe +@jehiah +@opennota +@pchristopher1275 +@zenovich +@beeker1121 + +## License + +The [BSD 3-Clause license][bsd]. + +[bsd]: http://opensource.org/licenses/BSD-3-Clause +[wiki]: http://en.wikipedia.org/wiki/URL_normalization +[rfc]: http://tools.ietf.org/html/rfc3986#section-6 +[godoc]: http://go.pkgdoc.org/github.com/PuerkitoBio/purell +[pr5]: https://github.com/PuerkitoBio/purell/pull/5 +[iss7]: https://github.com/PuerkitoBio/purell/issues/7 diff --git a/vendor/github.com/PuerkitoBio/purell/purell.go b/vendor/github.com/PuerkitoBio/purell/purell.go new file mode 100644 index 000000000..6d0fc190a --- /dev/null +++ b/vendor/github.com/PuerkitoBio/purell/purell.go @@ -0,0 +1,379 @@ +/* +Package purell offers URL normalization as described on the wikipedia page: +http://en.wikipedia.org/wiki/URL_normalization +*/ +package purell + +import ( + "bytes" + "fmt" + "net/url" + "regexp" + "sort" + "strconv" + "strings" + + "github.com/PuerkitoBio/urlesc" + "golang.org/x/net/idna" + "golang.org/x/text/unicode/norm" + "golang.org/x/text/width" +) + +// A set of normalization flags determines how a URL will +// be normalized. +type NormalizationFlags uint + +const ( + // Safe normalizations + FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 + FlagLowercaseHost // http://HOST -> http://host + FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF + FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA + FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ + FlagRemoveDefaultPort // http://host:80 -> http://host + FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path + + // Usually safe normalizations + FlagRemoveTrailingSlash // http://host/path/ -> http://host/path + FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) + FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c + + // Unsafe normalizations + FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ + FlagRemoveFragment // http://host/path#fragment -> http://host/path + FlagForceHTTP // https://host -> http://host + FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b + FlagRemoveWWW // http://www.host/ -> http://host/ + FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) + FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 + + // Normalizations not in the wikipedia article, required to cover tests cases + // submitted by jehiah + FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 + FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 + FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 + FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path + FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path + + // Convenience set of safe normalizations + FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator + + // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, + // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". + + // Convenience set of usually safe normalizations (includes FlagsSafe) + FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments + FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments + + // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) + FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery + FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery + + // Convenience set of all available flags + FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator + FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator +) + +const ( + defaultHttpPort = ":80" + defaultHttpsPort = ":443" +) + +// Regular expressions used by the normalizations +var rxPort = regexp.MustCompile(`(:\d+)/?$`) +var rxDirIndex = regexp.MustCompile(`(^|/)((?:default|index)\.\w{1,4})$`) +var rxDupSlashes = regexp.MustCompile(`/{2,}`) +var rxDWORDHost = regexp.MustCompile(`^(\d+)((?:\.+)?(?:\:\d*)?)$`) +var rxOctalHost = regexp.MustCompile(`^(0\d*)\.(0\d*)\.(0\d*)\.(0\d*)((?:\.+)?(?:\:\d*)?)$`) +var rxHexHost = regexp.MustCompile(`^0x([0-9A-Fa-f]+)((?:\.+)?(?:\:\d*)?)$`) +var rxHostDots = regexp.MustCompile(`^(.+?)(:\d+)?$`) +var rxEmptyPort = regexp.MustCompile(`:+$`) + +// Map of flags to implementation function. +// FlagDecodeUnnecessaryEscapes has no action, since it is done automatically +// by parsing the string as an URL. Same for FlagUppercaseEscapes and FlagRemoveEmptyQuerySeparator. + +// Since maps have undefined traversing order, make a slice of ordered keys +var flagsOrder = []NormalizationFlags{ + FlagLowercaseScheme, + FlagLowercaseHost, + FlagRemoveDefaultPort, + FlagRemoveDirectoryIndex, + FlagRemoveDotSegments, + FlagRemoveFragment, + FlagForceHTTP, // Must be after remove default port (because https=443/http=80) + FlagRemoveDuplicateSlashes, + FlagRemoveWWW, + FlagAddWWW, + FlagSortQuery, + FlagDecodeDWORDHost, + FlagDecodeOctalHost, + FlagDecodeHexHost, + FlagRemoveUnnecessaryHostDots, + FlagRemoveEmptyPortSeparator, + FlagRemoveTrailingSlash, // These two (add/remove trailing slash) must be last + FlagAddTrailingSlash, +} + +// ... and then the map, where order is unimportant +var flags = map[NormalizationFlags]func(*url.URL){ + FlagLowercaseScheme: lowercaseScheme, + FlagLowercaseHost: lowercaseHost, + FlagRemoveDefaultPort: removeDefaultPort, + FlagRemoveDirectoryIndex: removeDirectoryIndex, + FlagRemoveDotSegments: removeDotSegments, + FlagRemoveFragment: removeFragment, + FlagForceHTTP: forceHTTP, + FlagRemoveDuplicateSlashes: removeDuplicateSlashes, + FlagRemoveWWW: removeWWW, + FlagAddWWW: addWWW, + FlagSortQuery: sortQuery, + FlagDecodeDWORDHost: decodeDWORDHost, + FlagDecodeOctalHost: decodeOctalHost, + FlagDecodeHexHost: decodeHexHost, + FlagRemoveUnnecessaryHostDots: removeUnncessaryHostDots, + FlagRemoveEmptyPortSeparator: removeEmptyPortSeparator, + FlagRemoveTrailingSlash: removeTrailingSlash, + FlagAddTrailingSlash: addTrailingSlash, +} + +// MustNormalizeURLString returns the normalized string, and panics if an error occurs. +// It takes an URL string as input, as well as the normalization flags. +func MustNormalizeURLString(u string, f NormalizationFlags) string { + result, e := NormalizeURLString(u, f) + if e != nil { + panic(e) + } + return result +} + +// NormalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object. +// It takes an URL string as input, as well as the normalization flags. +func NormalizeURLString(u string, f NormalizationFlags) (string, error) { + parsed, err := url.Parse(u) + if err != nil { + return "", err + } + + if f&FlagLowercaseHost == FlagLowercaseHost { + parsed.Host = strings.ToLower(parsed.Host) + } + + // The idna package doesn't fully conform to RFC 5895 + // (https://tools.ietf.org/html/rfc5895), so we do it here. + // Taken from Go 1.8 cycle source, courtesy of bradfitz. + // TODO: Remove when (if?) idna package conforms to RFC 5895. + parsed.Host = width.Fold.String(parsed.Host) + parsed.Host = norm.NFC.String(parsed.Host) + if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil { + return "", err + } + + return NormalizeURL(parsed, f), nil +} + +// NormalizeURL returns the normalized string. +// It takes a parsed URL object as input, as well as the normalization flags. +func NormalizeURL(u *url.URL, f NormalizationFlags) string { + for _, k := range flagsOrder { + if f&k == k { + flags[k](u) + } + } + return urlesc.Escape(u) +} + +func lowercaseScheme(u *url.URL) { + if len(u.Scheme) > 0 { + u.Scheme = strings.ToLower(u.Scheme) + } +} + +func lowercaseHost(u *url.URL) { + if len(u.Host) > 0 { + u.Host = strings.ToLower(u.Host) + } +} + +func removeDefaultPort(u *url.URL) { + if len(u.Host) > 0 { + scheme := strings.ToLower(u.Scheme) + u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string { + if (scheme == "http" && val == defaultHttpPort) || (scheme == "https" && val == defaultHttpsPort) { + return "" + } + return val + }) + } +} + +func removeTrailingSlash(u *url.URL) { + if l := len(u.Path); l > 0 { + if strings.HasSuffix(u.Path, "/") { + u.Path = u.Path[:l-1] + } + } else if l = len(u.Host); l > 0 { + if strings.HasSuffix(u.Host, "/") { + u.Host = u.Host[:l-1] + } + } +} + +func addTrailingSlash(u *url.URL) { + if l := len(u.Path); l > 0 { + if !strings.HasSuffix(u.Path, "/") { + u.Path += "/" + } + } else if l = len(u.Host); l > 0 { + if !strings.HasSuffix(u.Host, "/") { + u.Host += "/" + } + } +} + +func removeDotSegments(u *url.URL) { + if len(u.Path) > 0 { + var dotFree []string + var lastIsDot bool + + sections := strings.Split(u.Path, "/") + for _, s := range sections { + if s == ".." { + if len(dotFree) > 0 { + dotFree = dotFree[:len(dotFree)-1] + } + } else if s != "." { + dotFree = append(dotFree, s) + } + lastIsDot = (s == "." || s == "..") + } + // Special case if host does not end with / and new path does not begin with / + u.Path = strings.Join(dotFree, "/") + if u.Host != "" && !strings.HasSuffix(u.Host, "/") && !strings.HasPrefix(u.Path, "/") { + u.Path = "/" + u.Path + } + // Special case if the last segment was a dot, make sure the path ends with a slash + if lastIsDot && !strings.HasSuffix(u.Path, "/") { + u.Path += "/" + } + } +} + +func removeDirectoryIndex(u *url.URL) { + if len(u.Path) > 0 { + u.Path = rxDirIndex.ReplaceAllString(u.Path, "$1") + } +} + +func removeFragment(u *url.URL) { + u.Fragment = "" +} + +func forceHTTP(u *url.URL) { + if strings.ToLower(u.Scheme) == "https" { + u.Scheme = "http" + } +} + +func removeDuplicateSlashes(u *url.URL) { + if len(u.Path) > 0 { + u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/") + } +} + +func removeWWW(u *url.URL) { + if len(u.Host) > 0 && strings.HasPrefix(strings.ToLower(u.Host), "www.") { + u.Host = u.Host[4:] + } +} + +func addWWW(u *url.URL) { + if len(u.Host) > 0 && !strings.HasPrefix(strings.ToLower(u.Host), "www.") { + u.Host = "www." + u.Host + } +} + +func sortQuery(u *url.URL) { + q := u.Query() + + if len(q) > 0 { + arKeys := make([]string, len(q)) + i := 0 + for k := range q { + arKeys[i] = k + i++ + } + sort.Strings(arKeys) + buf := new(bytes.Buffer) + for _, k := range arKeys { + sort.Strings(q[k]) + for _, v := range q[k] { + if buf.Len() > 0 { + buf.WriteRune('&') + } + buf.WriteString(fmt.Sprintf("%s=%s", k, urlesc.QueryEscape(v))) + } + } + + // Rebuild the raw query string + u.RawQuery = buf.String() + } +} + +func decodeDWORDHost(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxDWORDHost.FindStringSubmatch(u.Host); len(matches) > 2 { + var parts [4]int64 + + dword, _ := strconv.ParseInt(matches[1], 10, 0) + for i, shift := range []uint{24, 16, 8, 0} { + parts[i] = dword >> shift & 0xFF + } + u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[2]) + } + } +} + +func decodeOctalHost(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxOctalHost.FindStringSubmatch(u.Host); len(matches) > 5 { + var parts [4]int64 + + for i := 1; i <= 4; i++ { + parts[i-1], _ = strconv.ParseInt(matches[i], 8, 0) + } + u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[5]) + } + } +} + +func decodeHexHost(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxHexHost.FindStringSubmatch(u.Host); len(matches) > 2 { + // Conversion is safe because of regex validation + parsed, _ := strconv.ParseInt(matches[1], 16, 0) + // Set host as DWORD (base 10) encoded host + u.Host = fmt.Sprintf("%d%s", parsed, matches[2]) + // The rest is the same as decoding a DWORD host + decodeDWORDHost(u) + } + } +} + +func removeUnncessaryHostDots(u *url.URL) { + if len(u.Host) > 0 { + if matches := rxHostDots.FindStringSubmatch(u.Host); len(matches) > 1 { + // Trim the leading and trailing dots + u.Host = strings.Trim(matches[1], ".") + if len(matches) > 2 { + u.Host += matches[2] + } + } + } +} + +func removeEmptyPortSeparator(u *url.URL) { + if len(u.Host) > 0 { + u.Host = rxEmptyPort.ReplaceAllString(u.Host, "") + } +} diff --git a/vendor/github.com/PuerkitoBio/urlesc/.travis.yml b/vendor/github.com/PuerkitoBio/urlesc/.travis.yml new file mode 100644 index 000000000..ba6b225f9 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/.travis.yml @@ -0,0 +1,15 @@ +language: go + +go: + - 1.4.x + - 1.5.x + - 1.6.x + - 1.7.x + - 1.8.x + - tip + +install: + - go build . + +script: + - go test -v diff --git a/vendor/github.com/PuerkitoBio/urlesc/LICENSE b/vendor/github.com/PuerkitoBio/urlesc/LICENSE new file mode 100644 index 000000000..744875676 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/PuerkitoBio/urlesc/README.md b/vendor/github.com/PuerkitoBio/urlesc/README.md new file mode 100644 index 000000000..57aff0a53 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/README.md @@ -0,0 +1,16 @@ +urlesc [![Build Status](https://travis-ci.org/PuerkitoBio/urlesc.svg?branch=master)](https://travis-ci.org/PuerkitoBio/urlesc) [![GoDoc](http://godoc.org/github.com/PuerkitoBio/urlesc?status.svg)](http://godoc.org/github.com/PuerkitoBio/urlesc) +====== + +Package urlesc implements query escaping as per RFC 3986. + +It contains some parts of the net/url package, modified so as to allow +some reserved characters incorrectly escaped by net/url (see [issue 5684](https://github.com/golang/go/issues/5684)). + +## Install + + go get github.com/PuerkitoBio/urlesc + +## License + +Go license (BSD-3-Clause) + diff --git a/vendor/github.com/PuerkitoBio/urlesc/urlesc.go b/vendor/github.com/PuerkitoBio/urlesc/urlesc.go new file mode 100644 index 000000000..1b8462459 --- /dev/null +++ b/vendor/github.com/PuerkitoBio/urlesc/urlesc.go @@ -0,0 +1,180 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package urlesc implements query escaping as per RFC 3986. +// It contains some parts of the net/url package, modified so as to allow +// some reserved characters incorrectly escaped by net/url. +// See https://github.com/golang/go/issues/5684 +package urlesc + +import ( + "bytes" + "net/url" + "strings" +) + +type encoding int + +const ( + encodePath encoding = 1 + iota + encodeUserPassword + encodeQueryComponent + encodeFragment +) + +// Return true if the specified character should be escaped when +// appearing in a URL string, according to RFC 3986. +func shouldEscape(c byte, mode encoding) bool { + // §2.3 Unreserved characters (alphanum) + if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { + return false + } + + switch c { + case '-', '.', '_', '~': // §2.3 Unreserved characters (mark) + return false + + // §2.2 Reserved characters (reserved) + case ':', '/', '?', '#', '[', ']', '@', // gen-delims + '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // sub-delims + // Different sections of the URL allow a few of + // the reserved characters to appear unescaped. + switch mode { + case encodePath: // §3.3 + // The RFC allows sub-delims and : @. + // '/', '[' and ']' can be used to assign meaning to individual path + // segments. This package only manipulates the path as a whole, + // so we allow those as well. That leaves only ? and # to escape. + return c == '?' || c == '#' + + case encodeUserPassword: // §3.2.1 + // The RFC allows : and sub-delims in + // userinfo. The parsing of userinfo treats ':' as special so we must escape + // all the gen-delims. + return c == ':' || c == '/' || c == '?' || c == '#' || c == '[' || c == ']' || c == '@' + + case encodeQueryComponent: // §3.4 + // The RFC allows / and ?. + return c != '/' && c != '?' + + case encodeFragment: // §4.1 + // The RFC text is silent but the grammar allows + // everything, so escape nothing but # + return c == '#' + } + } + + // Everything else must be escaped. + return true +} + +// QueryEscape escapes the string so it can be safely placed +// inside a URL query. +func QueryEscape(s string) string { + return escape(s, encodeQueryComponent) +} + +func escape(s string, mode encoding) string { + spaceCount, hexCount := 0, 0 + for i := 0; i < len(s); i++ { + c := s[i] + if shouldEscape(c, mode) { + if c == ' ' && mode == encodeQueryComponent { + spaceCount++ + } else { + hexCount++ + } + } + } + + if spaceCount == 0 && hexCount == 0 { + return s + } + + t := make([]byte, len(s)+2*hexCount) + j := 0 + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == ' ' && mode == encodeQueryComponent: + t[j] = '+' + j++ + case shouldEscape(c, mode): + t[j] = '%' + t[j+1] = "0123456789ABCDEF"[c>>4] + t[j+2] = "0123456789ABCDEF"[c&15] + j += 3 + default: + t[j] = s[i] + j++ + } + } + return string(t) +} + +var uiReplacer = strings.NewReplacer( + "%21", "!", + "%27", "'", + "%28", "(", + "%29", ")", + "%2A", "*", +) + +// unescapeUserinfo unescapes some characters that need not to be escaped as per RFC3986. +func unescapeUserinfo(s string) string { + return uiReplacer.Replace(s) +} + +// Escape reassembles the URL into a valid URL string. +// The general form of the result is one of: +// +// scheme:opaque +// scheme://userinfo@host/path?query#fragment +// +// If u.Opaque is non-empty, String uses the first form; +// otherwise it uses the second form. +// +// In the second form, the following rules apply: +// - if u.Scheme is empty, scheme: is omitted. +// - if u.User is nil, userinfo@ is omitted. +// - if u.Host is empty, host/ is omitted. +// - if u.Scheme and u.Host are empty and u.User is nil, +// the entire scheme://userinfo@host/ is omitted. +// - if u.Host is non-empty and u.Path begins with a /, +// the form host/path does not add its own /. +// - if u.RawQuery is empty, ?query is omitted. +// - if u.Fragment is empty, #fragment is omitted. +func Escape(u *url.URL) string { + var buf bytes.Buffer + if u.Scheme != "" { + buf.WriteString(u.Scheme) + buf.WriteByte(':') + } + if u.Opaque != "" { + buf.WriteString(u.Opaque) + } else { + if u.Scheme != "" || u.Host != "" || u.User != nil { + buf.WriteString("//") + if ui := u.User; ui != nil { + buf.WriteString(unescapeUserinfo(ui.String())) + buf.WriteByte('@') + } + if h := u.Host; h != "" { + buf.WriteString(h) + } + } + if u.Path != "" && u.Path[0] != '/' && u.Host != "" { + buf.WriteByte('/') + } + buf.WriteString(escape(u.Path, encodePath)) + } + if u.RawQuery != "" { + buf.WriteByte('?') + buf.WriteString(u.RawQuery) + } + if u.Fragment != "" { + buf.WriteByte('#') + buf.WriteString(escape(u.Fragment, encodeFragment)) + } + return buf.String() +} diff --git a/vendor/github.com/agnivade/levenshtein/.travis.yml b/vendor/github.com/agnivade/levenshtein/.travis.yml deleted file mode 100644 index 0873fa983..000000000 --- a/vendor/github.com/agnivade/levenshtein/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: go - -# See https://travis-ci.community/t/goos-js-goarch-wasm-go-run-fails-panic-newosproc-not-implemented/1651 -#addons: -# chrome: stable - -before_install: -- export GO111MODULE=on - -#install: -#- go get github.com/agnivade/wasmbrowsertest -#- mv $GOPATH/bin/wasmbrowsertest $GOPATH/bin/go_js_wasm_exec -#- export PATH=$GOPATH/bin:$PATH - -go: -- 1.13.x -- 1.14.x -- 1.15.x -- tip - -script: -#- GOOS=js GOARCH=wasm go test -v -- go test -v diff --git a/vendor/github.com/agnivade/levenshtein/Makefile b/vendor/github.com/agnivade/levenshtein/Makefile index 5f6890d61..3bbda319e 100644 --- a/vendor/github.com/agnivade/levenshtein/Makefile +++ b/vendor/github.com/agnivade/levenshtein/Makefile @@ -4,12 +4,10 @@ install: go install lint: - gofmt -l -s -w . && go vet . && golint -set_exit_status=1 . + gofmt -l -s -w . && go vet . -test: # The first 2 go gets are to support older Go versions - go get github.com/arbovm/levenshtein - go get github.com/dgryski/trifles/leven - GO111MODULE=on go test -race -v -coverprofile=coverage.txt -covermode=atomic +test: + go test -race -v -coverprofile=coverage.txt -covermode=atomic bench: go test -run=XXX -bench=. -benchmem -count=5 diff --git a/vendor/github.com/agnivade/levenshtein/README.md b/vendor/github.com/agnivade/levenshtein/README.md index 13c52a210..34378aabe 100644 --- a/vendor/github.com/agnivade/levenshtein/README.md +++ b/vendor/github.com/agnivade/levenshtein/README.md @@ -1,4 +1,4 @@ -levenshtein [![Build Status](https://travis-ci.org/agnivade/levenshtein.svg?branch=master)](https://travis-ci.org/agnivade/levenshtein) [![Go Report Card](https://goreportcard.com/badge/github.com/agnivade/levenshtein)](https://goreportcard.com/report/github.com/agnivade/levenshtein) [![PkgGoDev](https://pkg.go.dev/badge/github.com/agnivade/levenshtein)](https://pkg.go.dev/github.com/agnivade/levenshtein) +levenshtein ![Build Status](https://github.com/agnivade/levenshtein/actions/workflows/ci.yml/badge.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/agnivade/levenshtein)](https://goreportcard.com/report/github.com/agnivade/levenshtein) [![PkgGoDev](https://pkg.go.dev/badge/github.com/agnivade/levenshtein)](https://pkg.go.dev/github.com/agnivade/levenshtein) =========== [Go](http://golang.org) package to calculate the [Levenshtein Distance](http://en.wikipedia.org/wiki/Levenshtein_distance) diff --git a/vendor/github.com/agnivade/levenshtein/levenshtein.go b/vendor/github.com/agnivade/levenshtein/levenshtein.go index f727a66fe..861f409dd 100644 --- a/vendor/github.com/agnivade/levenshtein/levenshtein.go +++ b/vendor/github.com/agnivade/levenshtein/levenshtein.go @@ -41,6 +41,25 @@ func ComputeDistance(a, b string) int { if len(s1) > len(s2) { s1, s2 = s2, s1 } + + // remove trailing identical runes. + for i := 0; i < len(s1); i++ { + if s1[len(s1)-1-i] != s2[len(s2)-1-i] { + s1 = s1[:len(s1)-i] + s2 = s2[:len(s2)-i] + break + } + } + + // Remove leading identical runes. + for i := 0; i < len(s1); i++ { + if s1[i] != s2[i] { + s1 = s1[i:] + s2 = s2[i:] + break + } + } + lenS1 := len(s1) lenS2 := len(s2) @@ -71,7 +90,7 @@ func ComputeDistance(a, b string) int { for j := 1; j <= lenS1; j++ { current := x[j-1] // match if s2[i-1] != s1[j-1] { - current = min(min(x[j-1]+1, prev+1), x[j]+1) + current = min(x[j-1]+1, prev+1, x[j]+1) } x[j-1] = prev prev = current @@ -80,10 +99,3 @@ func ComputeDistance(a, b string) int { } return int(x[lenS1]) } - -func min(a, b uint16) uint16 { - if a < b { - return a - } - return b -} diff --git a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/debug.go b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/debug.go new file mode 100644 index 000000000..0ec4b12c7 --- /dev/null +++ b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/debug.go @@ -0,0 +1,62 @@ +package md2man + +import ( + "fmt" + "io" + "os" + "strings" + + "github.com/russross/blackfriday/v2" +) + +func fmtListFlags(flags blackfriday.ListType) string { + knownFlags := []struct { + name string + flag blackfriday.ListType + }{ + {"ListTypeOrdered", blackfriday.ListTypeOrdered}, + {"ListTypeDefinition", blackfriday.ListTypeDefinition}, + {"ListTypeTerm", blackfriday.ListTypeTerm}, + {"ListItemContainsBlock", blackfriday.ListItemContainsBlock}, + {"ListItemBeginningOfList", blackfriday.ListItemBeginningOfList}, + {"ListItemEndOfList", blackfriday.ListItemEndOfList}, + } + + var f []string + for _, kf := range knownFlags { + if flags&kf.flag != 0 { + f = append(f, kf.name) + flags &^= kf.flag + } + } + if flags != 0 { + f = append(f, fmt.Sprintf("Unknown(%#x)", flags)) + } + return strings.Join(f, "|") +} + +type debugDecorator struct { + blackfriday.Renderer +} + +func depth(node *blackfriday.Node) int { + d := 0 + for n := node.Parent; n != nil; n = n.Parent { + d++ + } + return d +} + +func (d *debugDecorator) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus { + fmt.Fprintf(os.Stderr, "%s%s %v %v\n", + strings.Repeat(" ", depth(node)), + map[bool]string{true: "+", false: "-"}[entering], + node, + fmtListFlags(node.ListFlags)) + var b strings.Builder + status := d.Renderer.RenderNode(io.MultiWriter(&b, w), node, entering) + if b.Len() > 0 { + fmt.Fprintf(os.Stderr, ">> %q\n", b.String()) + } + return status +} diff --git a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go index b48005673..5673f5c0b 100644 --- a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go +++ b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go @@ -1,14 +1,24 @@ +// Package md2man aims in converting markdown into roff (man pages). package md2man import ( + "os" + "strconv" + "github.com/russross/blackfriday/v2" ) // Render converts a markdown document into a roff formatted document. func Render(doc []byte) []byte { renderer := NewRoffRenderer() + var r blackfriday.Renderer = renderer + if v, _ := strconv.ParseBool(os.Getenv("MD2MAN_DEBUG")); v { + r = &debugDecorator{Renderer: r} + } return blackfriday.Run(doc, - []blackfriday.Option{blackfriday.WithRenderer(renderer), - blackfriday.WithExtensions(renderer.GetExtensions())}...) + []blackfriday.Option{ + blackfriday.WithRenderer(r), + blackfriday.WithExtensions(renderer.GetExtensions()), + }...) } diff --git a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go index be2b34360..4f1070fc5 100644 --- a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go +++ b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go @@ -1,6 +1,8 @@ package md2man import ( + "bufio" + "bytes" "fmt" "io" "os" @@ -12,68 +14,72 @@ import ( // roffRenderer implements the blackfriday.Renderer interface for creating // roff format (manpages) from markdown text type roffRenderer struct { - extensions blackfriday.Extensions listCounters []int firstHeader bool - firstDD bool listDepth int } const ( - titleHeader = ".TH " - topLevelHeader = "\n\n.SH " - secondLevelHdr = "\n.SH " - otherHeader = "\n.SS " - crTag = "\n" - emphTag = "\\fI" - emphCloseTag = "\\fP" - strongTag = "\\fB" - strongCloseTag = "\\fP" - breakTag = "\n.br\n" - paraTag = "\n.PP\n" - hruleTag = "\n.ti 0\n\\l'\\n(.lu'\n" - linkTag = "\n\\[la]" - linkCloseTag = "\\[ra]" - codespanTag = "\\fB\\fC" - codespanCloseTag = "\\fR" - codeTag = "\n.PP\n.RS\n\n.nf\n" - codeCloseTag = "\n.fi\n.RE\n" - quoteTag = "\n.PP\n.RS\n" - quoteCloseTag = "\n.RE\n" - listTag = "\n.RS\n" - listCloseTag = "\n.RE\n" - dtTag = "\n.TP\n" - dd2Tag = "\n" - tableStart = "\n.TS\nallbox;\n" - tableEnd = ".TE\n" - tableCellStart = "T{\n" - tableCellEnd = "\nT}\n" + titleHeader = ".TH " + topLevelHeader = "\n\n.SH " + secondLevelHdr = "\n.SH " + otherHeader = "\n.SS " + crTag = "\n" + emphTag = "\\fI" + emphCloseTag = "\\fP" + strongTag = "\\fB" + strongCloseTag = "\\fP" + breakTag = "\n.br\n" + paraTag = "\n.PP\n" + hruleTag = "\n.ti 0\n\\l'\\n(.lu'\n" + linkTag = "\n\\[la]" + linkCloseTag = "\\[ra]" + codespanTag = "\\fB" + codespanCloseTag = "\\fR" + codeTag = "\n.EX\n" + codeCloseTag = ".EE\n" // Do not prepend a newline character since code blocks, by definition, include a newline already (or at least as how blackfriday gives us on). + quoteTag = "\n.PP\n.RS\n" + quoteCloseTag = "\n.RE\n" + listTag = "\n.RS\n" + listCloseTag = ".RE\n" + dtTag = "\n.TP\n" + dd2Tag = "\n" + tableStart = "\n.TS\nallbox;\n" + tableEnd = ".TE\n" + tableCellStart = "T{\n" + tableCellEnd = "\nT}" + tablePreprocessor = `'\" t` ) // NewRoffRenderer creates a new blackfriday Renderer for generating roff documents // from markdown -func NewRoffRenderer() *roffRenderer { // nolint: golint - var extensions blackfriday.Extensions - - extensions |= blackfriday.NoIntraEmphasis - extensions |= blackfriday.Tables - extensions |= blackfriday.FencedCode - extensions |= blackfriday.SpaceHeadings - extensions |= blackfriday.Footnotes - extensions |= blackfriday.Titleblock - extensions |= blackfriday.DefinitionLists - return &roffRenderer{ - extensions: extensions, - } +func NewRoffRenderer() *roffRenderer { + return &roffRenderer{} } // GetExtensions returns the list of extensions used by this renderer implementation -func (r *roffRenderer) GetExtensions() blackfriday.Extensions { - return r.extensions +func (*roffRenderer) GetExtensions() blackfriday.Extensions { + return blackfriday.NoIntraEmphasis | + blackfriday.Tables | + blackfriday.FencedCode | + blackfriday.SpaceHeadings | + blackfriday.Footnotes | + blackfriday.Titleblock | + blackfriday.DefinitionLists } // RenderHeader handles outputting the header at document start func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) { + // We need to walk the tree to check if there are any tables. + // If there are, we need to enable the roff table preprocessor. + ast.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus { + if node.Type == blackfriday.Table { + out(w, tablePreprocessor+"\n") + return blackfriday.Terminate + } + return blackfriday.GoToNext + }) + // disable hyphenation out(w, ".nh\n") } @@ -86,12 +92,27 @@ func (r *roffRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) { // RenderNode is called for each node in a markdown document; based on the node // type the equivalent roff output is sent to the writer func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus { - - var walkAction = blackfriday.GoToNext + walkAction := blackfriday.GoToNext switch node.Type { case blackfriday.Text: - escapeSpecialChars(w, node.Literal) + // Special case: format the NAME section as required for proper whatis parsing. + // Refer to the lexgrog(1) and groff_man(7) manual pages for details. + if node.Parent != nil && + node.Parent.Type == blackfriday.Paragraph && + node.Parent.Prev != nil && + node.Parent.Prev.Type == blackfriday.Heading && + node.Parent.Prev.FirstChild != nil && + bytes.EqualFold(node.Parent.Prev.FirstChild.Literal, []byte("NAME")) { + before, after, found := bytesCut(node.Literal, []byte(" - ")) + escapeSpecialChars(w, before) + if found { + out(w, ` \- `) + escapeSpecialChars(w, after) + } + } else { + escapeSpecialChars(w, node.Literal) + } case blackfriday.Softbreak: out(w, crTag) case blackfriday.Hardbreak: @@ -109,9 +130,16 @@ func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering out(w, strongCloseTag) } case blackfriday.Link: - if !entering { - out(w, linkTag+string(node.LinkData.Destination)+linkCloseTag) + // Don't render the link text for automatic links, because this + // will only duplicate the URL in the roff output. + // See https://daringfireball.net/projects/markdown/syntax#autolink + if !bytes.Equal(node.LinkData.Destination, node.FirstChild.Literal) { + out(w, string(node.FirstChild.Literal)) } + // Hyphens in a link must be escaped to avoid word-wrap in the rendered man page. + escapedLink := strings.ReplaceAll(string(node.LinkData.Destination), "-", "\\-") + out(w, linkTag+escapedLink+linkCloseTag) + walkAction = blackfriday.SkipChildren case blackfriday.Image: // ignore images walkAction = blackfriday.SkipChildren @@ -122,14 +150,25 @@ func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering case blackfriday.Document: break case blackfriday.Paragraph: - // roff .PP markers break lists - if r.listDepth > 0 { - return blackfriday.GoToNext - } if entering { - out(w, paraTag) + if r.listDepth > 0 { + // roff .PP markers break lists + if node.Prev != nil { // continued paragraph + if node.Prev.Type == blackfriday.List && node.Prev.ListFlags&blackfriday.ListTypeDefinition == 0 { + out(w, ".IP\n") + } else { + out(w, crTag) + } + } + } else if node.Prev != nil && node.Prev.Type == blackfriday.Heading { + out(w, crTag) + } else { + out(w, paraTag) + } } else { - out(w, crTag) + if node.Next == nil || node.Next.Type != blackfriday.List { + out(w, crTag) + } } case blackfriday.BlockQuote: if entering { @@ -160,6 +199,11 @@ func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering r.handleTableCell(w, node, entering) case blackfriday.HTMLSpan: // ignore other HTML tags + case blackfriday.HTMLBlock: + if bytes.HasPrefix(node.Literal, []byte(" +[![codecov](https://codecov.io/gh/go-openapi/spec/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/spec) +[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/spec/master/LICENSE) +[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/spec.svg)](https://pkg.go.dev/github.com/go-openapi/spec) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/spec)](https://goreportcard.com/report/github.com/go-openapi/spec) + +The object model for OpenAPI specification documents. + +### FAQ + +* What does this do? + +> 1. This package knows how to marshal and unmarshal Swagger API specifications into a golang object model +> 2. It knows how to resolve $ref and expand them to make a single root document + +* How does it play with the rest of the go-openapi packages ? + +> 1. This package is at the core of the go-openapi suite of packages and [code generator](https://github.com/go-swagger/go-swagger) +> 2. There is a [spec loading package](https://github.com/go-openapi/loads) to fetch specs as JSON or YAML from local or remote locations +> 3. There is a [spec validation package](https://github.com/go-openapi/validate) built on top of it +> 4. There is a [spec analysis package](https://github.com/go-openapi/analysis) built on top of it, to analyze, flatten, fix and merge spec documents + +* Does this library support OpenAPI 3? + +> No. +> This package currently only supports OpenAPI 2.0 (aka Swagger 2.0). +> There is no plan to make it evolve toward supporting OpenAPI 3.x. +> This [discussion thread](https://github.com/go-openapi/spec/issues/21) relates the full story. +> +> An early attempt to support Swagger 3 may be found at: https://github.com/go-openapi/spec3 diff --git a/vendor/github.com/go-openapi/spec/appveyor.yml b/vendor/github.com/go-openapi/spec/appveyor.yml new file mode 100644 index 000000000..090359391 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/appveyor.yml @@ -0,0 +1,32 @@ +version: "0.1.{build}" + +clone_folder: C:\go-openapi\spec +shallow_clone: true # for startup speed +pull_requests: + do_not_increment_build_number: true + +#skip_tags: true +#skip_branch_with_pr: true + +# appveyor.yml +build: off + +environment: + GOPATH: c:\gopath + +stack: go 1.15 + +test_script: + - go test -v -timeout 20m ./... + +deploy: off + +notifications: + - provider: Slack + incoming_webhook: https://hooks.slack.com/services/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 + auth_token: + secure: Sf7kZf7ZGbnwWUMpffHwMu5A0cHkLK2MYY32LNTPj4+/3qC3Ghl7+9v4TSLOqOlCwdRNjOGblAq7s+GDJed6/xgRQl1JtCi1klzZNrYX4q01pgTPvvGcwbBkIYgeMaPeIRcK9OZnud7sRXdttozgTOpytps2U6Js32ip7uj5mHSg2ub0FwoSJwlS6dbezZ8+eDhoha0F/guY99BEwx8Bd+zROrT2TFGsSGOFGN6wFc7moCqTHO/YkWib13a2QNXqOxCCVBy/lt76Wp+JkeFppjHlzs/2lP3EAk13RIUAaesdEUHvIHrzCyNJEd3/+KO2DzsWOYfpktd+KBCvgaYOsoo7ubdT3IROeAegZdCgo/6xgCEsmFc9ZcqCfN5yNx2A+BZ2Vwmpws+bQ1E1+B5HDzzaiLcYfG4X2O210QVGVDLWsv1jqD+uPYeHY2WRfh5ZsIUFvaqgUEnwHwrK44/8REAhQavt1QAj5uJpsRd7CkRVPWRNK+yIky+wgbVUFEchRNmS55E7QWf+W4+4QZkQi7vUTMc9nbTUu2Es9NfvfudOpM2wZbn98fjpb/qq/nRv6Bk+ca+7XD5/IgNLMbWp2ouDdzbiHLCOfDUiHiDJhLfFZx9Bwo7ZwfzeOlbrQX66bx7xRKYmOe4DLrXhNcpbsMa8qbfxlZRCmYbubB/Y8h4= + channel: bots + on_build_success: false + on_build_failure: true + on_build_status_changed: true diff --git a/vendor/github.com/go-openapi/spec/bindata.go b/vendor/github.com/go-openapi/spec/bindata.go new file mode 100644 index 000000000..afc83850c --- /dev/null +++ b/vendor/github.com/go-openapi/spec/bindata.go @@ -0,0 +1,297 @@ +// Code generated by go-bindata. DO NOT EDIT. +// sources: +// schemas/jsonschema-draft-04.json (4.357kB) +// schemas/v2/schema.json (40.248kB) + +package spec + +import ( + "bytes" + "compress/gzip" + "crypto/sha256" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" + "time" +) + +func bindataRead(data []byte, name string) ([]byte, error) { + gz, err := gzip.NewReader(bytes.NewBuffer(data)) + if err != nil { + return nil, fmt.Errorf("read %q: %v", name, err) + } + + var buf bytes.Buffer + _, err = io.Copy(&buf, gz) + clErr := gz.Close() + + if err != nil { + return nil, fmt.Errorf("read %q: %v", name, err) + } + if clErr != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +type asset struct { + bytes []byte + info os.FileInfo + digest [sha256.Size]byte +} + +type bindataFileInfo struct { + name string + size int64 + mode os.FileMode + modTime time.Time +} + +func (fi bindataFileInfo) Name() string { + return fi.name +} +func (fi bindataFileInfo) Size() int64 { + return fi.size +} +func (fi bindataFileInfo) Mode() os.FileMode { + return fi.mode +} +func (fi bindataFileInfo) ModTime() time.Time { + return fi.modTime +} +func (fi bindataFileInfo) IsDir() bool { + return false +} +func (fi bindataFileInfo) Sys() interface{} { + return nil +} + +var _jsonschemaDraft04Json = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xc4\x57\x3d\x6f\xdb\x3c\x10\xde\xf3\x2b\x08\x26\x63\xf2\x2a\x2f\xd0\xc9\x5b\xd1\x2e\x01\x5a\x34\x43\x37\x23\x03\x6d\x9d\x6c\x06\x14\xa9\x50\x54\x60\xc3\xd0\x7f\x2f\x28\x4a\x14\x29\x91\x92\x2d\xa7\x8d\x97\x28\xbc\xaf\xe7\x8e\xf7\xc5\xd3\x0d\x42\x08\x61\x9a\xe2\x15\xc2\x7b\xa5\x8a\x55\x92\xbc\x96\x82\x3f\x94\xdb\x3d\xe4\xe4\x3f\x21\x77\x49\x2a\x49\xa6\x1e\x1e\xbf\x24\xe6\xec\x16\xdf\x1b\xa1\x3b\xf3\xff\x02\xc9\x14\xca\xad\xa4\x85\xa2\x82\x6b\xe9\x6f\x42\x02\x32\x2c\x28\x07\x45\x5a\x15\x3d\x77\x46\x39\xd5\xcc\x25\x5e\x21\x83\xb8\x21\x18\xb6\xaf\x52\x92\xa3\x47\x68\x88\xea\x58\x80\x56\x4e\x1a\xf2\xbd\x4f\xcc\x29\x7f\x52\x90\x6b\x7d\xff\x0f\x48\xb4\x3d\x3f\x21\x7c\x27\x21\xd3\x2a\x6e\x31\xaa\x2d\x53\xdd\xf3\xe3\x42\x94\x54\xd1\x77\x78\xe2\x0a\x76\x20\xe3\x20\x68\xcb\x30\x86\x41\xf3\x2a\xc7\x2b\xf4\x78\x8e\xfe\xef\x90\x91\x8a\xa9\xc7\xb1\x1d\xc2\xd8\x2f\x0d\x75\xed\xc1\x4e\x9c\xc8\x25\x43\xac\xa8\xbe\xd7\xcc\xa9\xd1\xa9\x21\xa0\x1a\xbd\x04\x61\x94\x34\x2f\x18\xfc\x3e\x16\x50\x8e\x4d\x03\x6f\x1c\x58\xdb\x48\x23\xbc\x11\x82\x01\xe1\xfa\xd3\x3a\x8e\x30\xaf\x18\x33\x7f\xf3\x8d\x39\x11\x9b\x57\xd8\x2a\xfd\x55\x2a\x49\xf9\x0e\xc7\xec\x37\xd4\x25\xf7\xec\x5c\x66\xc7\xd7\x99\xaa\xcf\x4f\x89\x8a\xd3\xb7\x0a\x3a\xaa\x92\x15\xf4\x30\x6f\x1c\xb0\xd6\x46\xe7\x98\x39\x2d\xa4\x28\x40\x2a\x3a\x88\x9e\x29\xba\x88\x37\x2d\xca\x60\x38\xfa\xba\x5b\x20\xac\xa8\x62\xb0\x4c\xd4\xaf\xda\x45\x0a\xba\x5c\x3b\xb9\xc7\x79\xc5\x14\x2d\x18\x34\x19\x1c\x51\xdb\x25\x4d\xb4\x7e\x06\x14\x38\x6c\x59\x55\xd2\x77\xf8\x69\x59\xfc\x7b\x73\xed\x93\x43\xcb\x32\x6d\x3c\x28\xdc\x1b\x9a\xd3\x62\xab\xc2\x27\xf7\x41\xc9\x08\x2b\x23\x08\xad\x13\x57\x21\x9c\xd3\x72\x0d\x42\x72\xf8\x01\x7c\xa7\xf6\x83\xce\x39\xd7\x82\x3c\x1f\x2f\xd6\x60\x1b\xa2\xdf\x35\x89\x52\x20\xe7\x73\x74\xe0\x66\x26\x64\x4e\xb4\x97\x58\xc2\x0e\x0e\xe1\x60\x92\x34\x6d\xa0\x10\xd6\xb5\x83\x61\x27\xe6\x47\xd3\x89\xbd\x63\xfd\x3b\x8d\x03\x3d\x6c\x42\x2d\x5b\x70\xee\xe8\xdf\x4b\xf4\x66\x4e\xe1\x01\x45\x17\x80\x74\xad\x4f\xc3\xf3\xae\xc6\x1d\xc6\xd7\xc2\xce\xc9\xe1\x29\x30\x86\x2f\x4a\xa6\x4b\x15\x84\x73\xc9\x6f\xfd\x7f\xa5\x6e\x9e\xbd\xf1\xb0\xd4\xdd\x45\x5a\xc2\x3e\x4b\x78\xab\xa8\x84\x74\x4a\x91\x3b\x92\x23\x05\xf2\x1c\x1e\x7b\xf3\x09\xf8\xcf\xab\x24\xb6\x60\xa2\xe8\x4c\x9f\x75\x77\xaa\x8c\xe6\x01\x45\x36\x86\xcf\xc3\x63\x3a\xea\xd4\x8d\x7e\x06\xac\x14\x0a\xe0\x29\xf0\xed\x07\x22\x1a\x65\xda\x44\xae\xa2\x73\x1a\xe6\x90\x69\xa2\x8c\x46\xb2\x2f\xde\x49\x38\x08\xed\xfe\xfd\x41\xaf\x9f\xa9\x55\xd7\xdd\x22\x8d\xfa\x45\x63\xc5\x0f\x80\xf3\xb4\x08\xd6\x79\x30\x9e\x93\xee\x59\xa6\xd0\x4b\xee\x22\xe3\x33\xc1\x3a\x27\x68\x36\x78\x7e\x87\x0a\x06\xd5\x2e\x20\xd3\xaf\x15\xfb\xd8\x3b\x73\x14\xbb\x92\xed\x05\x5d\x2e\x29\x38\x2c\x94\xe4\x42\x45\x5e\xd3\xb5\x7d\xdf\x47\xca\x38\xb4\x5c\xaf\xfb\x7d\xdd\x6d\xf4\xa1\x2d\x77\xdd\x2f\xce\x6d\xc4\x7b\x8b\x4e\x67\xa9\x6f\xfe\x04\x00\x00\xff\xff\xb1\xd1\x27\x78\x05\x11\x00\x00") + +func jsonschemaDraft04JsonBytes() ([]byte, error) { + return bindataRead( + _jsonschemaDraft04Json, + "jsonschema-draft-04.json", + ) +} + +func jsonschemaDraft04Json() (*asset, error) { + bytes, err := jsonschemaDraft04JsonBytes() + if err != nil { + return nil, err + } + + info := bindataFileInfo{name: "jsonschema-draft-04.json", size: 4357, mode: os.FileMode(0640), modTime: time.Unix(1568963823, 0)} + a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xe1, 0x48, 0x9d, 0xb, 0x47, 0x55, 0xf0, 0x27, 0x93, 0x30, 0x25, 0x91, 0xd3, 0xfc, 0xb8, 0xf0, 0x7b, 0x68, 0x93, 0xa8, 0x2a, 0x94, 0xf2, 0x48, 0x95, 0xf8, 0xe4, 0xed, 0xf1, 0x1b, 0x82, 0xe2}} + return a, nil +} + +var _v2SchemaJson = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xec\x5d\x4f\x93\xdb\x36\xb2\xbf\xfb\x53\xa0\x14\x57\xd9\xae\xd8\x92\xe3\xf7\x2e\xcf\x97\xd4\xbc\xd8\x49\x66\x37\x5e\x4f\x79\x26\xbb\x87\x78\x5c\x05\x91\x2d\x09\x09\x09\x30\x00\x38\x33\x5a\xef\x7c\xf7\x2d\xf0\x9f\x08\x02\x20\x41\x8a\xd2\xc8\x0e\x0f\xa9\x78\x28\xa0\xd1\xdd\x68\x34\x7e\xdd\xf8\xf7\xf9\x11\x42\x33\x49\x64\x04\xb3\xd7\x68\x76\x86\xfe\x76\xf9\xfe\x1f\xe8\x32\xd8\x40\x8c\xd1\x8a\x71\x74\x79\x8b\xd7\x6b\xe0\xe8\xd5\xfc\x25\x3a\xbb\x38\x9f\xcf\x9e\xab\x0a\x24\x54\xa5\x37\x52\x26\xaf\x17\x0b\x91\x17\x99\x13\xb6\xb8\x79\xb5\x10\x59\xdd\xf9\xef\x82\xd1\x6f\xf2\xc2\x8f\xf3\x4f\xb5\x1a\xea\xc7\x17\x45\x41\xc6\xd7\x8b\x90\xe3\x95\x7c\xf1\xf2\x7f\x8b\xca\x45\x3d\xb9\x4d\x32\xa6\xd8\xf2\x77\x08\x64\xfe\x8d\xc3\x9f\x29\xe1\xa0\x9a\xff\xed\x11\x42\x08\xcd\x8a\xd6\xb3\x9f\x15\x67\x74\xc5\xca\x7f\x27\x58\x6e\xc4\xec\x11\x42\xd7\x59\x5d\x1c\x86\x44\x12\x46\x71\x74\xc1\x59\x02\x5c\x12\x10\xb3\xd7\x68\x85\x23\x01\x59\x81\x04\x4b\x09\x9c\x6a\xbf\x7e\xce\x49\x7d\xba\x7b\x51\xfd\xa1\x44\xe2\xb0\x52\xac\x7d\xb3\x08\x61\x45\x68\x46\x56\x2c\x6e\x80\x86\x8c\xbf\xbd\x93\x40\x05\x61\x74\x96\x95\xbe\x7f\x84\xd0\x7d\x4e\xde\x42\xb7\xe4\xbe\x46\xbb\x14\x5b\x48\x4e\xe8\xba\x90\x05\xa1\x19\xd0\x34\xae\xc4\xce\xbe\xbc\x9a\xbf\x9c\x15\x7f\x5d\x57\xc5\x42\x10\x01\x27\x89\xe2\x48\x51\xb9\xda\x40\xd5\x87\x37\xc0\x15\x5f\x88\xad\x90\xdc\x10\x81\x42\x16\xa4\x31\x50\x39\x2f\x38\xad\xab\xb0\x53\xd8\xac\x94\x56\x6f\xc3\x84\xf4\x11\xa4\x50\xb3\xfa\xe9\xd3\x6f\x9f\x3e\xdf\x2f\xd0\xeb\x8f\x1f\x3f\x7e\xbc\xfe\xf6\xe9\xf7\xaf\x5f\x7f\xfc\x18\x7e\xfb\xec\xfb\xc7\xb3\x36\x79\x54\x43\xe8\x29\xc5\x31\x20\xc6\x11\x49\x9e\xe5\x12\x41\x66\xa0\xe8\xed\x1d\x8e\x93\x08\x5e\xa3\x27\x3b\xc3\x7c\xa2\x73\xba\xc4\x02\x2e\xb0\xdc\xf4\xe5\x76\xd1\xca\x96\xa2\x8a\x94\xcd\x21\xc9\x6c\xec\x2c\x70\x42\x9e\x34\x74\x9d\x19\x7c\xcd\x20\x9c\xea\x2e\x0a\xfe\x42\x84\xd4\x29\x04\x8c\x8a\xb4\x41\xa2\xc1\xdc\x19\x8a\x88\x90\x4a\x49\xef\xce\xdf\xbd\x45\x4a\x52\x81\x70\x10\x40\x22\x21\x44\xcb\x6d\xc5\xec\x4e\x3c\x1c\x45\xef\x57\x9a\xb5\x7d\xae\xfe\xe5\xe4\x31\x86\x90\xe0\xab\x6d\x02\x3b\x2e\xcb\x11\x90\xd9\xa8\xc6\x77\xc2\x59\x98\x06\xfd\xf9\x2e\x78\x45\x01\xa6\xa8\xa0\x71\x5c\xbe\x33\xa7\xd2\xd9\x5f\x95\xef\xd9\xd5\xac\xfd\xdc\x5d\xbf\x5e\xb8\xd1\x3e\xc7\x31\x48\xe0\x5e\x4c\x14\x65\xdf\xb8\xa8\x71\x10\x09\xa3\xc2\xc7\x02\xcb\xa2\x4e\x5a\x02\x82\x94\x13\xb9\xf5\x30\xe6\xb2\xa4\xb5\xfe\x9b\x3e\x7a\xb2\x55\xd2\xa8\x4a\xbc\x16\xb6\x71\x8e\x39\xc7\xdb\x9d\xe1\x10\x09\x71\xbd\x9c\xb3\x41\x89\xd7\xa5\x89\xdc\x57\xb5\x53\x4a\xfe\x4c\xe1\xbc\xa0\x21\x79\x0a\x1a\x0f\x70\xa7\x5c\x08\x8e\xde\xb0\xc0\x43\x24\xad\x74\x63\x0e\xb1\xd9\x90\xe1\xb0\x2d\x13\xa7\x6d\x78\xfd\x04\x14\x38\x8e\x90\xaa\xce\x63\xac\x3e\x23\xbc\x64\xa9\xb4\xf8\x03\x63\xde\xcd\xbe\x16\x13\x4a\x55\xac\x82\x12\xc6\xac\xd4\x35\xf7\x22\xd4\x3a\xff\x22\x73\x0e\x6e\x51\xa0\x75\x1e\xae\x8f\xe8\x5d\xc7\x59\xe6\xe4\x9a\x18\x8d\xd6\x1c\x53\x84\x4d\xb7\x67\x28\x37\x09\x84\x69\x88\x12\x0e\x01\x11\x80\x32\xa2\xf5\xb9\xaa\xc6\xd9\x73\x53\xab\xfb\xb4\x2e\x20\xc6\x54\x92\xa0\x9a\xf3\x69\x1a\x2f\x81\x77\x37\xae\x53\x1a\xce\x40\xc4\xa8\x82\x1c\xb5\xef\xda\x24\x7d\xb9\x61\x69\x14\xa2\x25\xa0\x90\xac\x56\xc0\x81\x4a\xb4\xe2\x2c\xce\x4a\x64\x7a\x9a\x23\xf4\x13\x91\x3f\xa7\x4b\xf4\x63\x84\x6f\x18\x87\x10\xbd\xc3\xfc\x8f\x90\xdd\x52\x44\x04\xc2\x51\xc4\x6e\x21\x74\x48\x21\x81\xc7\xe2\xfd\xea\x12\xf8\x0d\x09\xf6\xe9\x47\x35\xaf\x67\xc4\x14\xf7\x22\x27\x97\xe1\xe2\x76\x2d\x06\x8c\x4a\x1c\x48\x3f\x73\x2d\x0b\x5b\x29\x45\x24\x00\x2a\x0c\x11\xec\x94\xca\xc2\xa6\xc1\x37\x21\x43\x83\x3b\x5f\x97\xf1\x43\x5e\x53\x73\x19\xa5\x36\xd8\x2d\x05\x2e\x34\x0b\xeb\x39\xfc\x1d\x63\x51\x01\xbd\x3d\xbb\x90\x84\x40\x25\x59\x6d\x09\x5d\xa3\x1c\x37\xe6\x5c\x16\x9a\x40\x09\x70\xc1\xe8\x82\xf1\x35\xa6\xe4\xdf\x99\x5c\x8e\x9e\x4d\x79\xb4\x27\x2f\xbf\x7e\xf8\x05\x25\x8c\x50\xa9\x98\x29\x90\x62\x60\xea\x75\xae\x13\xca\xbf\x2b\x1a\x29\x27\x76\xd6\x20\xc6\x64\x5f\xe6\x32\x1a\x08\x87\x21\x07\x21\xbc\xb4\xe4\xe0\x32\x67\xa6\xcd\xf3\x1e\xcd\xd9\x6b\xb6\x6f\x8e\x27\xa7\xed\xdb\xe7\xbc\xcc\x1a\x07\xce\x6f\x87\x33\xf0\xba\x51\x17\x22\x66\x78\x79\x8e\xce\xe5\x13\x81\x80\x06\x2c\xe5\x78\x0d\xa1\xb2\xb8\x54\xa8\x79\x09\xbd\xbf\x3c\x47\x01\x8b\x13\x2c\xc9\x32\xaa\xaa\x1d\xd5\xee\xab\x36\xbd\x6c\xfd\x54\x6c\xc8\x08\x01\x3c\xbd\xe7\x07\x88\xb0\x24\x37\x79\x90\x28\x4a\x1d\x10\x1a\x92\x1b\x12\xa6\x38\x42\x40\xc3\x4c\x43\x62\x8e\xae\x36\xb0\x45\x71\x2a\xa4\x9a\x23\x79\x59\xb1\xa8\xf2\xa4\x0c\x60\x9f\xcc\x8d\x40\xf5\x80\xca\xa8\x99\xc3\xa7\x85\x1f\x31\x25\xa9\x82\xc5\x6d\xbd\xd8\x36\x76\x7c\x02\x28\x97\xf6\x1d\x74\x3b\x11\x7e\x91\xae\x32\xf8\x6c\xf4\xe6\x7b\x9a\xa5\x1f\x62\xc6\x21\xcf\x9a\xe5\xed\x8b\x02\xf3\x2c\x33\x33\xdf\x00\xca\xc9\x09\xb4\x04\xf5\xa5\x08\xd7\xc3\x02\x18\x66\xf1\xab\x1e\x83\x37\x4c\xcd\x12\xc1\x1d\x50\xf6\xaa\xbd\xfe\xe2\x73\x48\x38\x08\xa0\x32\x9b\x18\x44\x86\x0b\x6a\xc1\xaa\x26\x96\x2d\x96\x3c\xa0\x54\x65\x73\xe3\x08\xb5\x8b\x99\xbd\x82\xbc\x9e\xc2\xe8\x53\x46\x83\x3f\x33\x54\x2b\x5b\xad\x92\x79\xd9\x8f\x5d\x93\x98\xf2\xe6\xc6\x1c\xe6\x9a\x9e\xfc\x43\x82\x31\x66\x8e\x53\x77\xfe\x90\xe7\xf3\xf6\xe9\x62\x23\x3f\x10\x93\x18\xae\x72\x1a\x9d\xf9\x48\xcb\xcc\x5a\x65\xc7\x4a\x04\xf0\xf3\xd5\xd5\x05\x8a\x41\x08\xbc\x86\x86\x43\x51\x6c\xe0\x46\x57\xf6\x44\x40\x0d\xfb\xff\xa2\xc3\x7c\x3d\x39\x84\xdc\x09\x22\x64\x4f\x12\xd9\xba\xaa\xf6\xe3\xbd\x56\xdd\x91\x25\x6a\x14\x9c\x89\x34\x8e\x31\xdf\xee\x15\x7e\x2f\x39\x81\x15\x2a\x28\x95\x66\x51\xf5\xfd\x83\xc5\xfe\x15\x07\xcf\xf7\x08\xee\x1d\x8e\xb6\xc5\x52\xcc\x8c\x5a\x93\x66\xc5\xd8\x79\x38\x46\xd6\xa7\x88\x37\xc9\x2e\xe3\xd2\xa5\x7b\x4b\x3a\xdc\xa1\xdc\x9e\x29\xf1\x8c\x8a\x99\x16\x47\x8d\xd4\x78\x8b\xf6\x1c\xe9\x71\x54\x1b\x69\xa8\x4a\x93\x37\xe5\xb2\x2c\x4f\x0c\x92\xab\xa0\x73\x32\x72\x59\xd3\xf0\x2d\x8d\xed\xca\x37\x16\x19\x9e\xdb\x1c\xab\x17\x49\xc3\x0f\x37\xdc\x88\xb1\xb4\xd4\x42\xcb\x58\x5e\x6a\x52\x0b\x15\x10\x0a\xb0\x04\xe7\xf8\x58\x32\x16\x01\xa6\xcd\x01\xb2\xc2\x69\x24\x35\x38\x6f\x30\x6a\xae\x1b\xb4\x71\xaa\xad\x1d\xa0\xd6\x20\x2d\x8b\x3c\xc6\x82\x62\x27\x34\x6d\x15\x84\x7b\x43\xb1\x35\x78\xa6\x24\x77\x28\xc1\x6e\xfc\xe9\x48\x74\xf4\x15\xe3\xe1\x84\x42\x88\x40\x7a\x26\x49\x3b\x48\xb1\xa4\x19\x8e\x0c\xa7\xb5\x01\x6c\x0c\x97\x61\x8a\xc2\x32\xd8\x8c\x44\x69\x24\xbf\x65\x1d\x74\xd6\xe5\x44\xef\xec\x48\x5e\xb7\x8a\xa3\x29\x8e\x41\x64\xce\x1f\x88\xdc\x00\x47\x4b\x40\x98\x6e\xd1\x0d\x8e\x48\x98\x63\x5c\x21\xb1\x4c\x05\x0a\x58\x98\xc5\x6d\x4f\x0a\x77\x53\x4f\x8b\xc4\x44\x1f\xb2\xdf\x8d\x3b\xea\x9f\xfe\xf6\xf2\xc5\xff\x5d\x7f\xfe\x9f\xfb\x67\x8f\xff\xf3\xe9\x69\xd1\xfe\xb3\xc7\xfd\x3c\xf8\x3f\x71\x94\x82\x23\xd1\x72\x00\xb7\x42\x99\x6c\xc0\x60\x7b\x0f\x79\xea\xa8\x53\x4b\x56\x31\xfa\x0b\x52\x9f\x96\xdb\xcd\x2f\xd7\x67\xcd\x04\x19\x85\xfe\xdb\x02\x9a\x59\x03\xad\x63\x3c\xea\xff\x2e\x18\xfd\x00\xd9\xe2\x56\x60\x59\x93\xb9\xb6\xb2\x3e\x3c\x2c\xab\x0f\xa7\xb2\x89\x43\xc7\xf6\xd5\xce\x2e\xad\xa6\xa9\xed\xa6\xc6\x5a\xb4\xa6\x67\xdf\x8c\x26\x7b\x50\x5a\x91\x08\x2e\x6d\xd4\x3a\xc1\x9d\xf2\xdb\xde\x1e\xb2\x2c\x6c\xa5\x64\xc9\x16\xb4\x90\xaa\x4a\xb7\x0c\xde\x13\xc3\x2a\x9a\x11\x9b\x7a\x1b\x3d\x95\x97\x37\x31\x6b\x69\x7e\x34\xc0\x67\x1f\x66\x19\x49\xef\xf1\x25\xf5\xac\x0e\xea\x0a\x28\x8d\x4d\x7e\xd9\x57\x4b\x49\xe5\xc6\xb3\x25\xfd\xe6\x57\x42\x25\xac\xcd\xcf\x36\x74\x8e\xca\x24\x47\xe7\x80\xa8\x92\x72\xbd\x3d\x84\x2d\x65\xe2\x82\x1a\x9c\xc4\x44\x92\x1b\x10\x79\x8a\xc4\x4a\x2f\x60\x51\x04\x81\xaa\xf0\xa3\x95\x27\xd7\x12\x7b\xa3\x96\x03\x45\x96\xc1\x8a\x07\xc9\xb2\xb0\x95\x52\x8c\xef\x48\x9c\xc6\x7e\x94\xca\xc2\x0e\x07\x12\x44\xa9\x20\x37\xf0\xae\x0f\x49\xa3\x96\x9d\x4b\x42\x7b\x70\x59\x14\xee\xe0\xb2\x0f\x49\xa3\x96\x4b\x97\xbf\x00\x5d\x4b\x4f\xfc\xbb\x2b\xee\x92\xb9\x17\xb5\xaa\xb8\x0b\x97\x17\x9b\x43\xfd\xd6\xc2\xb2\xc2\x2e\x29\xcf\xfd\x87\x4a\x55\xda\x25\x63\x1f\x5a\x65\x69\x2b\x2d\x3d\x67\xe9\x41\xae\x5e\xc1\x6e\x2b\xd4\xdb\x3e\xa8\xd3\x26\xd2\x48\x92\x24\xca\x61\x86\x8f\x8c\xbb\xf2\x8e\x91\xdf\x1f\x06\x19\x33\xf3\x03\x4d\xba\xcd\xe2\x2d\xfb\x69\xe9\x16\x15\x13\xd5\x56\x85\x4e\x3c\x5b\x8a\xbf\x25\x72\x83\xee\x5e\x20\x22\xf2\xc8\xaa\x7b\xdb\x8e\xe4\x29\x58\xca\x38\xb7\x3f\x2e\x59\xb8\xbd\xa8\x16\x16\xf7\xdb\x79\x51\x9f\x5a\xb4\x8d\x87\x3a\x6e\xbc\x3e\xc5\xb4\xcd\x58\xf9\xf5\x3c\xb9\x6f\x49\xaf\x57\xc1\xfa\x1c\x5d\x6d\x88\x8a\x8b\xd3\x28\xcc\xb7\xef\x10\x8a\x4a\x74\xa9\x4a\xa7\x62\xbf\x0d\x76\x23\x6f\x59\xd9\x31\xee\x40\x11\xfb\x28\xec\x8d\x22\x1c\x13\x5a\x64\x94\x23\x16\x60\xbb\xd2\x7c\xa0\x98\xb2\xe5\x6e\xbc\x54\x33\xe0\x3e\xb9\x52\x17\xdb\xb7\x1b\xc8\x12\x20\x8c\x23\xca\x64\x7e\x78\xa3\x62\x5b\x75\x56\xd9\x9e\x2a\x91\x27\xb0\x70\x34\x1f\x90\x89\xb5\x86\x73\x7e\x71\xda\x1e\xfb\x3a\x72\xdc\x5e\x79\x88\xcb\x74\x79\xd9\x64\xe4\xd4\xc2\x9e\xce\xb1\xfe\x85\x5a\xc0\xe9\x0c\x34\x3d\xd0\x43\xce\xa1\x36\x39\xd5\xa1\x4e\xf5\xf8\xb1\xa9\x23\x08\x75\x84\xac\x53\x6c\x3a\xc5\xa6\x53\x6c\x3a\xc5\xa6\x7f\xc5\xd8\xf4\x51\xfd\xff\x25\x4e\xfa\x33\x05\xbe\x9d\x60\xd2\x04\x93\x6a\x5f\x33\x9b\x98\x50\xd2\xe1\x50\x52\xc6\xcc\xdb\x38\x91\xdb\xe6\xaa\xa2\x8f\xa1\x6a\xa6\xd4\xc6\x56\xd6\x8c\x40\x02\x68\x48\xe8\x1a\xe1\x9a\xd9\x2e\xb7\x05\xc3\x34\xda\x2a\xbb\xcd\x12\x36\x98\x22\x50\x4c\xa1\x1b\xc5\xd5\x84\xf0\xbe\x24\x84\xf7\x2f\x22\x37\xef\x94\xd7\x9f\xa0\xde\x04\xf5\x26\xa8\x37\x41\x3d\x64\x40\x3d\xe5\xf2\xde\x60\x89\x27\xb4\x37\xa1\xbd\xda\xd7\xd2\x2c\x26\xc0\x37\x01\x3e\x1b\xef\x5f\x06\xe0\x6b\x7c\x5c\x91\x08\x26\x10\x38\x81\xc0\x09\x04\x76\x4a\x3d\x81\xc0\xbf\x12\x08\x4c\xb0\xdc\x7c\x99\x00\xd0\x75\x70\xb4\xf8\x5a\x7c\xea\xde\x3e\x39\x08\x30\x5a\x27\x35\xed\xb4\x65\xad\x69\x74\x10\x88\x79\xe2\x30\x52\x19\xd6\x04\x21\xa7\x95\xd5\x0e\x03\xf8\xda\x20\xd7\x84\xb4\x26\xa4\x35\x21\xad\x09\x69\x21\x03\x69\x51\x46\xff\xff\x18\x9b\x54\xed\x87\x47\x06\x9d\x4e\x73\x6e\x9a\xb3\xa9\xce\x83\x5e\x4b\xc6\x71\x20\x45\xd7\x72\xf5\x40\x72\x0e\x34\x6c\xf4\x6c\xf3\xba\x5e\x4b\x97\x0e\x52\xb8\xbe\x8b\x79\xa0\x10\x86\xa1\x75\xb0\x6f\xec\xc8\xf4\x3d\x4d\x7b\x86\xc2\x02\x31\x12\x51\xbf\x07\x94\xad\x10\xd6\x2e\x79\xcf\xe9\x1c\xf5\x1e\x31\x23\x5c\x18\xfb\x9c\xfb\x70\xe0\x62\xbd\xf7\xb5\x94\xcf\xf3\xf6\xfa\xc5\x4e\x9c\x85\x76\x1d\xae\x37\xbc\xde\xa3\x41\xcb\x29\xd0\x5e\x70\x67\x50\x93\x6d\x98\xa8\xd3\x67\x0f\x68\xb1\xeb\x38\x47\x07\x10\x1b\xd2\xe2\x18\x68\x6d\x40\xbb\xa3\x40\xba\x21\xf2\x8e\x81\xfb\xf6\x92\x77\x2f\x70\xe8\xdb\xb2\x36\xbf\x30\x91\xc5\x21\xe7\x45\xcc\x34\x0c\x48\x8e\xd0\xf2\x9b\x7c\x3c\xbd\x1c\x04\x3e\x07\xe8\x7c\x2f\x84\x7a\x48\x4d\x1f\xba\xe1\x76\x45\x7b\x60\xe0\x01\xca\xee\x04\xca\x31\xbe\x73\x5f\xa3\x70\x0c\xad\x1f\xa5\xf5\x76\xd5\xbb\xd2\x7e\xfb\x30\x90\xcf\xfa\x67\x7a\xe6\xc3\x37\x42\x19\xe2\xc9\x9c\x61\x4c\xe7\xd1\x77\x55\x86\x6e\x8f\x7b\x85\x42\x33\xa3\xaa\x57\xae\xfd\xd5\xcc\x9c\x56\x68\xe2\xde\x0e\xa8\x2c\xa9\xb0\x7d\xf0\x54\x2d\x80\xf2\x48\x39\x3d\x98\x1a\x6d\x0b\x9d\xba\x53\xfb\xce\xf8\xd1\x7e\xbb\x60\x4f\x06\xf5\xce\xda\xab\xeb\xca\xcb\xd5\xac\x20\xda\x72\x3b\xa2\x4b\x38\xd7\xb5\x89\xbe\x42\xd9\xb9\x73\xc4\x0c\x6d\xb7\xd9\xf8\x8d\xbd\x3e\x9c\xf5\x53\x68\x48\x14\x36\x8f\x09\xc5\x92\xf1\x21\xd1\x09\x07\x1c\xbe\xa7\x91\xf3\x6a\xc8\xc1\x57\xb0\xdd\xc5\xc6\x1d\xad\x76\x1d\xa8\x82\x0e\x4c\x38\xfe\xa5\x8c\xc5\x0a\x40\x5d\xa1\xbb\x98\xd1\xfb\x74\x61\xed\x1a\x98\xaf\x3c\x8c\x1e\xe3\xc2\x92\x29\x74\x3e\x99\xd0\xf9\x41\x50\xd0\x38\x4b\x57\x7e\x5b\x7a\x0e\xe6\xce\x4e\xd7\x19\x35\x57\xbb\x3c\x3c\xd2\x5e\x4f\x4b\x4c\xf7\x0f\x4d\x2b\x91\x5d\x94\xa6\x95\xc8\x69\x25\x72\x5a\x89\x7c\xb8\x95\xc8\x07\x80\x8c\xda\x9c\x64\x7b\xb7\x71\xdf\x57\x12\x4b\x9a\x1f\x72\x0c\x13\x03\xad\x3c\xd5\x4e\xde\x8e\x57\x13\x6d\x34\x86\xcf\x97\xe6\xa4\x68\xc4\xb0\xf6\xc9\xc2\xeb\x8d\x0b\xd7\xcd\xfe\xba\xa6\xf5\x30\xeb\x30\x33\xbe\xc7\x56\x27\xab\x08\xd9\x6d\xbb\x09\xee\x7c\x2d\xcf\xee\x87\x38\xac\xc8\xdd\x90\x9a\x58\x4a\x4e\x96\xa9\x79\x79\xf3\xde\x20\xf0\x96\xe3\x24\x19\xeb\xba\xf2\x53\x19\xab\x12\xaf\x47\xb3\xa0\x3e\xef\x9b\x8d\x6d\x6d\x7b\xde\x3b\x3b\x1a\xc0\x3f\x95\x7e\xed\x78\xfb\x76\xb8\xaf\xb3\xdd\xc5\xeb\x95\xed\x5a\x62\x41\x82\xb3\x54\x6e\x80\x4a\x92\x6f\x36\xbd\x34\xae\xde\x6f\xa4\xc0\xbc\x08\xe3\x84\xfc\x1d\xb6\xe3\xd0\x62\x38\x95\x9b\x57\xe7\x71\x12\x91\x80\xc8\x31\x69\x5e\x60\x21\x6e\x19\x0f\xc7\xa4\x79\x96\x28\x3e\x47\x54\x65\x41\x36\x08\x40\x88\x1f\x58\x08\x56\xaa\xd5\xbf\xaf\xad\x96\xd7\xd6\xcf\x87\xf5\x34\x0f\x71\x93\x6e\x26\xed\x98\x5b\x9f\x4f\xcf\x95\x34\xc6\xd7\x11\xfa\xb0\x81\x22\x1a\xdb\xdf\x8e\xdc\xc3\xb9\xf8\xdd\x5d\x3c\x74\xe6\xea\xb7\x8b\xbf\xf5\x6e\xb3\x46\x2e\x64\xf4\xab\x3c\x4e\xcf\x36\x1d\xfe\xfa\xb8\x36\xba\x8a\xd8\xad\xf6\xc6\x41\x2a\x37\x8c\x17\x0f\xda\xfe\xda\xe7\x65\xbc\x71\x2c\x36\x57\x8a\x47\x12\x4c\xf1\xbd\x77\x6b\xa4\x50\x7e\x77\x7b\x22\x60\x89\xef\xcd\xf5\xb9\x0c\x97\x79\x0d\x2b\x35\x43\xcb\x3d\x24\xf1\x78\xfc\xf8\xcb\x1f\x15\x06\xe2\x78\xd8\x51\x21\xd9\x1f\xf0\xf5\x8f\x86\xa4\x50\xfa\xb1\x47\x43\xa5\xdd\x69\x14\xe8\xa3\xc0\x86\x91\xa7\x81\x50\xb4\x7c\xc0\x81\x80\x77\x7a\x9f\xc6\xc2\xa9\x8c\x05\x33\xb0\x3b\x31\xa4\xf4\xd7\x1b\x26\x55\x97\x7c\x65\xf8\x69\x1a\x84\x8e\x41\x78\xd9\xec\xc5\x11\x16\x1e\x74\x91\xf5\x56\xf5\x57\x49\x47\x5c\x92\xa9\x1e\x99\x36\xf4\xdb\xb1\x0e\xd3\x78\x02\xb0\x9b\x25\xcb\xe9\xe9\x1d\x0d\x44\x01\x42\x08\x91\x64\xd9\xdd\x37\x08\x17\xef\xf9\xe5\x0f\xbd\x46\x91\xf5\xf9\x89\x92\x37\xdd\x89\x59\x44\x1f\x9c\xee\x34\x1e\xbe\x47\x83\x32\x72\x8e\x37\xdf\xac\x69\x38\xef\x75\xb0\xda\xdb\xac\x83\x94\x2f\x39\xa6\x62\x05\x1c\x25\x9c\x49\x16\xb0\xa8\x3c\xc7\x7e\x76\x71\x3e\x6f\xb5\x24\xe7\xe8\xb7\xb9\xc7\x6c\x43\x92\xee\x21\xd4\x17\xa1\x7f\xba\x35\xfe\xae\x39\xbc\xde\xba\x69\xd9\x8e\xe1\x62\xde\x64\x7d\x16\x88\x1b\xed\x29\x11\xfd\x4f\xa9\xff\x99\x90\xc4\xf6\xf4\xf9\x6e\xe9\x28\x23\xd7\xca\xe5\xee\xee\x9f\x63\xb1\x5b\xfb\x10\xd7\x2f\x1d\xf2\xe3\xbf\xb9\xb5\x6f\xa4\x6d\x7d\x25\x79\xfb\x24\x31\xea\x56\xbe\x5d\x53\xcd\x2d\x36\xa3\x6d\xdf\xab\x1c\xb8\x6d\x6f\xc0\x98\xa7\xdd\xaa\x86\x8c\x1d\x39\xa3\x9d\x70\x2b\x9b\x68\xd9\xfd\x33\xfe\xa9\xb6\x4a\x2e\x63\x0f\xcf\x68\x27\xd9\x4c\xb9\x46\x6d\xcb\xbe\xa1\xa8\xd6\x5f\xc6\xd6\x9f\xf1\x4f\xf4\xd4\xb4\x78\xd0\xd6\xf4\x13\x3c\x3b\xac\xd0\xdc\x90\x34\xda\xc9\xb4\x9a\x1a\x8d\xbd\x93\x87\xd4\xe2\x21\x1b\xb3\x2b\xd1\xbe\xe7\x69\xd4\x53\x67\xd5\x40\xa0\xe3\x19\x3f\x6d\x1a\xbc\x0e\x86\x3c\x10\xb4\x3d\x2a\xcd\x78\x32\xe6\xab\xbd\x36\xc9\xf4\x3a\x58\xae\xc3\xf4\x47\xea\xbf\xfb\x47\xff\x0d\x00\x00\xff\xff\xd2\x32\x5a\x28\x38\x9d\x00\x00") + +func v2SchemaJsonBytes() ([]byte, error) { + return bindataRead( + _v2SchemaJson, + "v2/schema.json", + ) +} + +func v2SchemaJson() (*asset, error) { + bytes, err := v2SchemaJsonBytes() + if err != nil { + return nil, err + } + + info := bindataFileInfo{name: "v2/schema.json", size: 40248, mode: os.FileMode(0640), modTime: time.Unix(1568964748, 0)} + a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xab, 0x88, 0x5e, 0xf, 0xbf, 0x17, 0x74, 0x0, 0xb2, 0x5a, 0x7f, 0xbc, 0x58, 0xcd, 0xc, 0x25, 0x73, 0xd5, 0x29, 0x1c, 0x7a, 0xd0, 0xce, 0x79, 0xd4, 0x89, 0x31, 0x27, 0x90, 0xf2, 0xff, 0xe6}} + return a, nil +} + +// Asset loads and returns the asset for the given name. +// It returns an error if the asset could not be found or +// could not be loaded. +func Asset(name string) ([]byte, error) { + canonicalName := strings.Replace(name, "\\", "/", -1) + if f, ok := _bindata[canonicalName]; ok { + a, err := f() + if err != nil { + return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) + } + return a.bytes, nil + } + return nil, fmt.Errorf("Asset %s not found", name) +} + +// AssetString returns the asset contents as a string (instead of a []byte). +func AssetString(name string) (string, error) { + data, err := Asset(name) + return string(data), err +} + +// MustAsset is like Asset but panics when Asset would return an error. +// It simplifies safe initialization of global variables. +func MustAsset(name string) []byte { + a, err := Asset(name) + if err != nil { + panic("asset: Asset(" + name + "): " + err.Error()) + } + + return a +} + +// MustAssetString is like AssetString but panics when Asset would return an +// error. It simplifies safe initialization of global variables. +func MustAssetString(name string) string { + return string(MustAsset(name)) +} + +// AssetInfo loads and returns the asset info for the given name. +// It returns an error if the asset could not be found or +// could not be loaded. +func AssetInfo(name string) (os.FileInfo, error) { + canonicalName := strings.Replace(name, "\\", "/", -1) + if f, ok := _bindata[canonicalName]; ok { + a, err := f() + if err != nil { + return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) + } + return a.info, nil + } + return nil, fmt.Errorf("AssetInfo %s not found", name) +} + +// AssetDigest returns the digest of the file with the given name. It returns an +// error if the asset could not be found or the digest could not be loaded. +func AssetDigest(name string) ([sha256.Size]byte, error) { + canonicalName := strings.Replace(name, "\\", "/", -1) + if f, ok := _bindata[canonicalName]; ok { + a, err := f() + if err != nil { + return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s can't read by error: %v", name, err) + } + return a.digest, nil + } + return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s not found", name) +} + +// Digests returns a map of all known files and their checksums. +func Digests() (map[string][sha256.Size]byte, error) { + mp := make(map[string][sha256.Size]byte, len(_bindata)) + for name := range _bindata { + a, err := _bindata[name]() + if err != nil { + return nil, err + } + mp[name] = a.digest + } + return mp, nil +} + +// AssetNames returns the names of the assets. +func AssetNames() []string { + names := make([]string, 0, len(_bindata)) + for name := range _bindata { + names = append(names, name) + } + return names +} + +// _bindata is a table, holding each asset generator, mapped to its name. +var _bindata = map[string]func() (*asset, error){ + "jsonschema-draft-04.json": jsonschemaDraft04Json, + + "v2/schema.json": v2SchemaJson, +} + +// AssetDir returns the file names below a certain +// directory embedded in the file by go-bindata. +// For example if you run go-bindata on data/... and data contains the +// following hierarchy: +// data/ +// foo.txt +// img/ +// a.png +// b.png +// then AssetDir("data") would return []string{"foo.txt", "img"}, +// AssetDir("data/img") would return []string{"a.png", "b.png"}, +// AssetDir("foo.txt") and AssetDir("notexist") would return an error, and +// AssetDir("") will return []string{"data"}. +func AssetDir(name string) ([]string, error) { + node := _bintree + if len(name) != 0 { + canonicalName := strings.Replace(name, "\\", "/", -1) + pathList := strings.Split(canonicalName, "/") + for _, p := range pathList { + node = node.Children[p] + if node == nil { + return nil, fmt.Errorf("Asset %s not found", name) + } + } + } + if node.Func != nil { + return nil, fmt.Errorf("Asset %s not found", name) + } + rv := make([]string, 0, len(node.Children)) + for childName := range node.Children { + rv = append(rv, childName) + } + return rv, nil +} + +type bintree struct { + Func func() (*asset, error) + Children map[string]*bintree +} + +var _bintree = &bintree{nil, map[string]*bintree{ + "jsonschema-draft-04.json": {jsonschemaDraft04Json, map[string]*bintree{}}, + "v2": {nil, map[string]*bintree{ + "schema.json": {v2SchemaJson, map[string]*bintree{}}, + }}, +}} + +// RestoreAsset restores an asset under the given directory. +func RestoreAsset(dir, name string) error { + data, err := Asset(name) + if err != nil { + return err + } + info, err := AssetInfo(name) + if err != nil { + return err + } + err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) + if err != nil { + return err + } + err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) + if err != nil { + return err + } + return os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) +} + +// RestoreAssets restores an asset under the given directory recursively. +func RestoreAssets(dir, name string) error { + children, err := AssetDir(name) + // File + if err != nil { + return RestoreAsset(dir, name) + } + // Dir + for _, child := range children { + err = RestoreAssets(dir, filepath.Join(name, child)) + if err != nil { + return err + } + } + return nil +} + +func _filePath(dir, name string) string { + canonicalName := strings.Replace(name, "\\", "/", -1) + return filepath.Join(append([]string{dir}, strings.Split(canonicalName, "/")...)...) +} diff --git a/vendor/github.com/go-openapi/spec/cache.go b/vendor/github.com/go-openapi/spec/cache.go new file mode 100644 index 000000000..122993b44 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/cache.go @@ -0,0 +1,98 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "sync" +) + +// ResolutionCache a cache for resolving urls +type ResolutionCache interface { + Get(string) (interface{}, bool) + Set(string, interface{}) +} + +type simpleCache struct { + lock sync.RWMutex + store map[string]interface{} +} + +func (s *simpleCache) ShallowClone() ResolutionCache { + store := make(map[string]interface{}, len(s.store)) + s.lock.RLock() + for k, v := range s.store { + store[k] = v + } + s.lock.RUnlock() + + return &simpleCache{ + store: store, + } +} + +// Get retrieves a cached URI +func (s *simpleCache) Get(uri string) (interface{}, bool) { + s.lock.RLock() + v, ok := s.store[uri] + + s.lock.RUnlock() + return v, ok +} + +// Set caches a URI +func (s *simpleCache) Set(uri string, data interface{}) { + s.lock.Lock() + s.store[uri] = data + s.lock.Unlock() +} + +var ( + // resCache is a package level cache for $ref resolution and expansion. + // It is initialized lazily by methods that have the need for it: no + // memory is allocated unless some expander methods are called. + // + // It is initialized with JSON schema and swagger schema, + // which do not mutate during normal operations. + // + // All subsequent utilizations of this cache are produced from a shallow + // clone of this initial version. + resCache *simpleCache + onceCache sync.Once + + _ ResolutionCache = &simpleCache{} +) + +// initResolutionCache initializes the URI resolution cache. To be wrapped in a sync.Once.Do call. +func initResolutionCache() { + resCache = defaultResolutionCache() +} + +func defaultResolutionCache() *simpleCache { + return &simpleCache{store: map[string]interface{}{ + "http://swagger.io/v2/schema.json": MustLoadSwagger20Schema(), + "http://json-schema.org/draft-04/schema": MustLoadJSONSchemaDraft04(), + }} +} + +func cacheOrDefault(cache ResolutionCache) ResolutionCache { + onceCache.Do(initResolutionCache) + + if cache != nil { + return cache + } + + // get a shallow clone of the base cache with swagger and json schema + return resCache.ShallowClone() +} diff --git a/vendor/github.com/go-openapi/spec/contact_info.go b/vendor/github.com/go-openapi/spec/contact_info.go new file mode 100644 index 000000000..2f7bb219b --- /dev/null +++ b/vendor/github.com/go-openapi/spec/contact_info.go @@ -0,0 +1,57 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + + "github.com/go-openapi/swag" +) + +// ContactInfo contact information for the exposed API. +// +// For more information: http://goo.gl/8us55a#contactObject +type ContactInfo struct { + ContactInfoProps + VendorExtensible +} + +// ContactInfoProps hold the properties of a ContactInfo object +type ContactInfoProps struct { + Name string `json:"name,omitempty"` + URL string `json:"url,omitempty"` + Email string `json:"email,omitempty"` +} + +// UnmarshalJSON hydrates ContactInfo from json +func (c *ContactInfo) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &c.ContactInfoProps); err != nil { + return err + } + return json.Unmarshal(data, &c.VendorExtensible) +} + +// MarshalJSON produces ContactInfo as json +func (c ContactInfo) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(c.ContactInfoProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(c.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} diff --git a/vendor/github.com/go-openapi/spec/debug.go b/vendor/github.com/go-openapi/spec/debug.go new file mode 100644 index 000000000..fc889f6d0 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/debug.go @@ -0,0 +1,49 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "fmt" + "log" + "os" + "path" + "runtime" +) + +// Debug is true when the SWAGGER_DEBUG env var is not empty. +// +// It enables a more verbose logging of this package. +var Debug = os.Getenv("SWAGGER_DEBUG") != "" + +var ( + // specLogger is a debug logger for this package + specLogger *log.Logger +) + +func init() { + debugOptions() +} + +func debugOptions() { + specLogger = log.New(os.Stdout, "spec:", log.LstdFlags) +} + +func debugLog(msg string, args ...interface{}) { + // A private, trivial trace logger, based on go-openapi/spec/expander.go:debugLog() + if Debug { + _, file1, pos1, _ := runtime.Caller(1) + specLogger.Printf("%s:%d: %s", path.Base(file1), pos1, fmt.Sprintf(msg, args...)) + } +} diff --git a/vendor/github.com/go-openapi/spec/errors.go b/vendor/github.com/go-openapi/spec/errors.go new file mode 100644 index 000000000..6992c7ba7 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/errors.go @@ -0,0 +1,19 @@ +package spec + +import "errors" + +// Error codes +var ( + // ErrUnknownTypeForReference indicates that a resolved reference was found in an unsupported container type + ErrUnknownTypeForReference = errors.New("unknown type for the resolved reference") + + // ErrResolveRefNeedsAPointer indicates that a $ref target must be a valid JSON pointer + ErrResolveRefNeedsAPointer = errors.New("resolve ref: target needs to be a pointer") + + // ErrDerefUnsupportedType indicates that a resolved reference was found in an unsupported container type. + // At the moment, $ref are supported only inside: schemas, parameters, responses, path items + ErrDerefUnsupportedType = errors.New("deref: unsupported type") + + // ErrExpandUnsupportedType indicates that $ref expansion is attempted on some invalid type + ErrExpandUnsupportedType = errors.New("expand: unsupported type. Input should be of type *Parameter or *Response") +) diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go new file mode 100644 index 000000000..d4ea889d4 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/expander.go @@ -0,0 +1,594 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "fmt" +) + +// ExpandOptions provides options for the spec expander. +// +// RelativeBase is the path to the root document. This can be a remote URL or a path to a local file. +// +// If left empty, the root document is assumed to be located in the current working directory: +// all relative $ref's will be resolved from there. +// +// PathLoader injects a document loading method. By default, this resolves to the function provided by the SpecLoader package variable. +// +type ExpandOptions struct { + RelativeBase string // the path to the root document to expand. This is a file, not a directory + SkipSchemas bool // do not expand schemas, just paths, parameters and responses + ContinueOnError bool // continue expanding even after and error is found + PathLoader func(string) (json.RawMessage, error) `json:"-"` // the document loading method that takes a path as input and yields a json document + AbsoluteCircularRef bool // circular $ref remaining after expansion remain absolute URLs +} + +func optionsOrDefault(opts *ExpandOptions) *ExpandOptions { + if opts != nil { + clone := *opts // shallow clone to avoid internal changes to be propagated to the caller + if clone.RelativeBase != "" { + clone.RelativeBase = normalizeBase(clone.RelativeBase) + } + // if the relative base is empty, let the schema loader choose a pseudo root document + return &clone + } + return &ExpandOptions{} +} + +// ExpandSpec expands the references in a swagger spec +func ExpandSpec(spec *Swagger, options *ExpandOptions) error { + options = optionsOrDefault(options) + resolver := defaultSchemaLoader(spec, options, nil, nil) + + specBasePath := options.RelativeBase + + if !options.SkipSchemas { + for key, definition := range spec.Definitions { + parentRefs := make([]string, 0, 10) + parentRefs = append(parentRefs, fmt.Sprintf("#/definitions/%s", key)) + + def, err := expandSchema(definition, parentRefs, resolver, specBasePath) + if resolver.shouldStopOnError(err) { + return err + } + if def != nil { + spec.Definitions[key] = *def + } + } + } + + for key := range spec.Parameters { + parameter := spec.Parameters[key] + if err := expandParameterOrResponse(¶meter, resolver, specBasePath); resolver.shouldStopOnError(err) { + return err + } + spec.Parameters[key] = parameter + } + + for key := range spec.Responses { + response := spec.Responses[key] + if err := expandParameterOrResponse(&response, resolver, specBasePath); resolver.shouldStopOnError(err) { + return err + } + spec.Responses[key] = response + } + + if spec.Paths != nil { + for key := range spec.Paths.Paths { + pth := spec.Paths.Paths[key] + if err := expandPathItem(&pth, resolver, specBasePath); resolver.shouldStopOnError(err) { + return err + } + spec.Paths.Paths[key] = pth + } + } + + return nil +} + +const rootBase = ".root" + +// baseForRoot loads in the cache the root document and produces a fake ".root" base path entry +// for further $ref resolution +// +// Setting the cache is optional and this parameter may safely be left to nil. +func baseForRoot(root interface{}, cache ResolutionCache) string { + if root == nil { + return "" + } + + // cache the root document to resolve $ref's + normalizedBase := normalizeBase(rootBase) + cache.Set(normalizedBase, root) + + return normalizedBase +} + +// ExpandSchema expands the refs in the schema object with reference to the root object. +// +// go-openapi/validate uses this function. +// +// Notice that it is impossible to reference a json schema in a different document other than root +// (use ExpandSchemaWithBasePath to resolve external references). +// +// Setting the cache is optional and this parameter may safely be left to nil. +func ExpandSchema(schema *Schema, root interface{}, cache ResolutionCache) error { + cache = cacheOrDefault(cache) + if root == nil { + root = schema + } + + opts := &ExpandOptions{ + // when a root is specified, cache the root as an in-memory document for $ref retrieval + RelativeBase: baseForRoot(root, cache), + SkipSchemas: false, + ContinueOnError: false, + } + + return ExpandSchemaWithBasePath(schema, cache, opts) +} + +// ExpandSchemaWithBasePath expands the refs in the schema object, base path configured through expand options. +// +// Setting the cache is optional and this parameter may safely be left to nil. +func ExpandSchemaWithBasePath(schema *Schema, cache ResolutionCache, opts *ExpandOptions) error { + if schema == nil { + return nil + } + + cache = cacheOrDefault(cache) + + opts = optionsOrDefault(opts) + + resolver := defaultSchemaLoader(nil, opts, cache, nil) + + parentRefs := make([]string, 0, 10) + s, err := expandSchema(*schema, parentRefs, resolver, opts.RelativeBase) + if err != nil { + return err + } + if s != nil { + // guard for when continuing on error + *schema = *s + } + + return nil +} + +func expandItems(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { + if target.Items == nil { + return &target, nil + } + + // array + if target.Items.Schema != nil { + t, err := expandSchema(*target.Items.Schema, parentRefs, resolver, basePath) + if err != nil { + return nil, err + } + *target.Items.Schema = *t + } + + // tuple + for i := range target.Items.Schemas { + t, err := expandSchema(target.Items.Schemas[i], parentRefs, resolver, basePath) + if err != nil { + return nil, err + } + target.Items.Schemas[i] = *t + } + + return &target, nil +} + +func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { + if target.Ref.String() == "" && target.Ref.IsRoot() { + newRef := normalizeRef(&target.Ref, basePath) + target.Ref = *newRef + return &target, nil + } + + // change the base path of resolution when an ID is encountered + // otherwise the basePath should inherit the parent's + if target.ID != "" { + basePath, _ = resolver.setSchemaID(target, target.ID, basePath) + } + + if target.Ref.String() != "" { + return expandSchemaRef(target, parentRefs, resolver, basePath) + } + + for k := range target.Definitions { + tt, err := expandSchema(target.Definitions[k], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if tt != nil { + target.Definitions[k] = *tt + } + } + + t, err := expandItems(target, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target = *t + } + + for i := range target.AllOf { + t, err := expandSchema(target.AllOf[i], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.AllOf[i] = *t + } + } + + for i := range target.AnyOf { + t, err := expandSchema(target.AnyOf[i], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.AnyOf[i] = *t + } + } + + for i := range target.OneOf { + t, err := expandSchema(target.OneOf[i], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.OneOf[i] = *t + } + } + + if target.Not != nil { + t, err := expandSchema(*target.Not, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.Not = *t + } + } + + for k := range target.Properties { + t, err := expandSchema(target.Properties[k], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.Properties[k] = *t + } + } + + if target.AdditionalProperties != nil && target.AdditionalProperties.Schema != nil { + t, err := expandSchema(*target.AdditionalProperties.Schema, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.AdditionalProperties.Schema = *t + } + } + + for k := range target.PatternProperties { + t, err := expandSchema(target.PatternProperties[k], parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + target.PatternProperties[k] = *t + } + } + + for k := range target.Dependencies { + if target.Dependencies[k].Schema != nil { + t, err := expandSchema(*target.Dependencies[k].Schema, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.Dependencies[k].Schema = *t + } + } + } + + if target.AdditionalItems != nil && target.AdditionalItems.Schema != nil { + t, err := expandSchema(*target.AdditionalItems.Schema, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return &target, err + } + if t != nil { + *target.AdditionalItems.Schema = *t + } + } + return &target, nil +} + +func expandSchemaRef(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { + // if a Ref is found, all sibling fields are skipped + // Ref also changes the resolution scope of children expandSchema + + // here the resolution scope is changed because a $ref was encountered + normalizedRef := normalizeRef(&target.Ref, basePath) + normalizedBasePath := normalizedRef.RemoteURI() + + if resolver.isCircular(normalizedRef, basePath, parentRefs...) { + // this means there is a cycle in the recursion tree: return the Ref + // - circular refs cannot be expanded. We leave them as ref. + // - denormalization means that a new local file ref is set relative to the original basePath + debugLog("short circuit circular ref: basePath: %s, normalizedPath: %s, normalized ref: %s", + basePath, normalizedBasePath, normalizedRef.String()) + if !resolver.options.AbsoluteCircularRef { + target.Ref = denormalizeRef(normalizedRef, resolver.context.basePath, resolver.context.rootID) + } else { + target.Ref = *normalizedRef + } + return &target, nil + } + + var t *Schema + err := resolver.Resolve(&target.Ref, &t, basePath) + if resolver.shouldStopOnError(err) { + return nil, err + } + + if t == nil { + // guard for when continuing on error + return &target, nil + } + + parentRefs = append(parentRefs, normalizedRef.String()) + transitiveResolver := resolver.transitiveResolver(basePath, target.Ref) + + basePath = resolver.updateBasePath(transitiveResolver, normalizedBasePath) + + return expandSchema(*t, parentRefs, transitiveResolver, basePath) +} + +func expandPathItem(pathItem *PathItem, resolver *schemaLoader, basePath string) error { + if pathItem == nil { + return nil + } + + parentRefs := make([]string, 0, 10) + if err := resolver.deref(pathItem, parentRefs, basePath); resolver.shouldStopOnError(err) { + return err + } + + if pathItem.Ref.String() != "" { + transitiveResolver := resolver.transitiveResolver(basePath, pathItem.Ref) + basePath = transitiveResolver.updateBasePath(resolver, basePath) + resolver = transitiveResolver + } + + pathItem.Ref = Ref{} + for i := range pathItem.Parameters { + if err := expandParameterOrResponse(&(pathItem.Parameters[i]), resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + } + + ops := []*Operation{ + pathItem.Get, + pathItem.Head, + pathItem.Options, + pathItem.Put, + pathItem.Post, + pathItem.Patch, + pathItem.Delete, + } + for _, op := range ops { + if err := expandOperation(op, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + } + + return nil +} + +func expandOperation(op *Operation, resolver *schemaLoader, basePath string) error { + if op == nil { + return nil + } + + for i := range op.Parameters { + param := op.Parameters[i] + if err := expandParameterOrResponse(¶m, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + op.Parameters[i] = param + } + + if op.Responses == nil { + return nil + } + + responses := op.Responses + if err := expandParameterOrResponse(responses.Default, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + + for code := range responses.StatusCodeResponses { + response := responses.StatusCodeResponses[code] + if err := expandParameterOrResponse(&response, resolver, basePath); resolver.shouldStopOnError(err) { + return err + } + responses.StatusCodeResponses[code] = response + } + + return nil +} + +// ExpandResponseWithRoot expands a response based on a root document, not a fetchable document +// +// Notice that it is impossible to reference a json schema in a different document other than root +// (use ExpandResponse to resolve external references). +// +// Setting the cache is optional and this parameter may safely be left to nil. +func ExpandResponseWithRoot(response *Response, root interface{}, cache ResolutionCache) error { + cache = cacheOrDefault(cache) + opts := &ExpandOptions{ + RelativeBase: baseForRoot(root, cache), + } + resolver := defaultSchemaLoader(root, opts, cache, nil) + + return expandParameterOrResponse(response, resolver, opts.RelativeBase) +} + +// ExpandResponse expands a response based on a basepath +// +// All refs inside response will be resolved relative to basePath +func ExpandResponse(response *Response, basePath string) error { + opts := optionsOrDefault(&ExpandOptions{ + RelativeBase: basePath, + }) + resolver := defaultSchemaLoader(nil, opts, nil, nil) + + return expandParameterOrResponse(response, resolver, opts.RelativeBase) +} + +// ExpandParameterWithRoot expands a parameter based on a root document, not a fetchable document. +// +// Notice that it is impossible to reference a json schema in a different document other than root +// (use ExpandParameter to resolve external references). +func ExpandParameterWithRoot(parameter *Parameter, root interface{}, cache ResolutionCache) error { + cache = cacheOrDefault(cache) + + opts := &ExpandOptions{ + RelativeBase: baseForRoot(root, cache), + } + resolver := defaultSchemaLoader(root, opts, cache, nil) + + return expandParameterOrResponse(parameter, resolver, opts.RelativeBase) +} + +// ExpandParameter expands a parameter based on a basepath. +// This is the exported version of expandParameter +// all refs inside parameter will be resolved relative to basePath +func ExpandParameter(parameter *Parameter, basePath string) error { + opts := optionsOrDefault(&ExpandOptions{ + RelativeBase: basePath, + }) + resolver := defaultSchemaLoader(nil, opts, nil, nil) + + return expandParameterOrResponse(parameter, resolver, opts.RelativeBase) +} + +func getRefAndSchema(input interface{}) (*Ref, *Schema, error) { + var ( + ref *Ref + sch *Schema + ) + + switch refable := input.(type) { + case *Parameter: + if refable == nil { + return nil, nil, nil + } + ref = &refable.Ref + sch = refable.Schema + case *Response: + if refable == nil { + return nil, nil, nil + } + ref = &refable.Ref + sch = refable.Schema + default: + return nil, nil, fmt.Errorf("unsupported type: %T: %w", input, ErrExpandUnsupportedType) + } + + return ref, sch, nil +} + +func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePath string) error { + ref, _, err := getRefAndSchema(input) + if err != nil { + return err + } + + if ref == nil { + return nil + } + + parentRefs := make([]string, 0, 10) + if err = resolver.deref(input, parentRefs, basePath); resolver.shouldStopOnError(err) { + return err + } + + ref, sch, _ := getRefAndSchema(input) + if ref.String() != "" { + transitiveResolver := resolver.transitiveResolver(basePath, *ref) + basePath = resolver.updateBasePath(transitiveResolver, basePath) + resolver = transitiveResolver + } + + if sch == nil { + // nothing to be expanded + if ref != nil { + *ref = Ref{} + } + return nil + } + + if sch.Ref.String() != "" { + rebasedRef, ern := NewRef(normalizeURI(sch.Ref.String(), basePath)) + if ern != nil { + return ern + } + + switch { + case resolver.isCircular(&rebasedRef, basePath, parentRefs...): + // this is a circular $ref: stop expansion + if !resolver.options.AbsoluteCircularRef { + sch.Ref = denormalizeRef(&rebasedRef, resolver.context.basePath, resolver.context.rootID) + } else { + sch.Ref = rebasedRef + } + case !resolver.options.SkipSchemas: + // schema expanded to a $ref in another root + sch.Ref = rebasedRef + debugLog("rebased to: %s", sch.Ref.String()) + default: + // skip schema expansion but rebase $ref to schema + sch.Ref = denormalizeRef(&rebasedRef, resolver.context.basePath, resolver.context.rootID) + } + } + + if ref != nil { + *ref = Ref{} + } + + // expand schema + if !resolver.options.SkipSchemas { + s, err := expandSchema(*sch, parentRefs, resolver, basePath) + if resolver.shouldStopOnError(err) { + return err + } + if s == nil { + // guard for when continuing on error + return nil + } + *sch = *s + } + + return nil +} diff --git a/vendor/github.com/go-openapi/spec/external_docs.go b/vendor/github.com/go-openapi/spec/external_docs.go new file mode 100644 index 000000000..88add91b2 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/external_docs.go @@ -0,0 +1,24 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +// ExternalDocumentation allows referencing an external resource for +// extended documentation. +// +// For more information: http://goo.gl/8us55a#externalDocumentationObject +type ExternalDocumentation struct { + Description string `json:"description,omitempty"` + URL string `json:"url,omitempty"` +} diff --git a/vendor/github.com/go-openapi/spec/header.go b/vendor/github.com/go-openapi/spec/header.go new file mode 100644 index 000000000..9dfd17b18 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/header.go @@ -0,0 +1,203 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +const ( + jsonArray = "array" +) + +// HeaderProps describes a response header +type HeaderProps struct { + Description string `json:"description,omitempty"` +} + +// Header describes a header for a response of the API +// +// For more information: http://goo.gl/8us55a#headerObject +type Header struct { + CommonValidations + SimpleSchema + VendorExtensible + HeaderProps +} + +// ResponseHeader creates a new header instance for use in a response +func ResponseHeader() *Header { + return new(Header) +} + +// WithDescription sets the description on this response, allows for chaining +func (h *Header) WithDescription(description string) *Header { + h.Description = description + return h +} + +// Typed a fluent builder method for the type of parameter +func (h *Header) Typed(tpe, format string) *Header { + h.Type = tpe + h.Format = format + return h +} + +// CollectionOf a fluent builder method for an array item +func (h *Header) CollectionOf(items *Items, format string) *Header { + h.Type = jsonArray + h.Items = items + h.CollectionFormat = format + return h +} + +// WithDefault sets the default value on this item +func (h *Header) WithDefault(defaultValue interface{}) *Header { + h.Default = defaultValue + return h +} + +// WithMaxLength sets a max length value +func (h *Header) WithMaxLength(max int64) *Header { + h.MaxLength = &max + return h +} + +// WithMinLength sets a min length value +func (h *Header) WithMinLength(min int64) *Header { + h.MinLength = &min + return h +} + +// WithPattern sets a pattern value +func (h *Header) WithPattern(pattern string) *Header { + h.Pattern = pattern + return h +} + +// WithMultipleOf sets a multiple of value +func (h *Header) WithMultipleOf(number float64) *Header { + h.MultipleOf = &number + return h +} + +// WithMaximum sets a maximum number value +func (h *Header) WithMaximum(max float64, exclusive bool) *Header { + h.Maximum = &max + h.ExclusiveMaximum = exclusive + return h +} + +// WithMinimum sets a minimum number value +func (h *Header) WithMinimum(min float64, exclusive bool) *Header { + h.Minimum = &min + h.ExclusiveMinimum = exclusive + return h +} + +// WithEnum sets a the enum values (replace) +func (h *Header) WithEnum(values ...interface{}) *Header { + h.Enum = append([]interface{}{}, values...) + return h +} + +// WithMaxItems sets the max items +func (h *Header) WithMaxItems(size int64) *Header { + h.MaxItems = &size + return h +} + +// WithMinItems sets the min items +func (h *Header) WithMinItems(size int64) *Header { + h.MinItems = &size + return h +} + +// UniqueValues dictates that this array can only have unique items +func (h *Header) UniqueValues() *Header { + h.UniqueItems = true + return h +} + +// AllowDuplicates this array can have duplicates +func (h *Header) AllowDuplicates() *Header { + h.UniqueItems = false + return h +} + +// WithValidations is a fluent method to set header validations +func (h *Header) WithValidations(val CommonValidations) *Header { + h.SetValidations(SchemaValidations{CommonValidations: val}) + return h +} + +// MarshalJSON marshal this to JSON +func (h Header) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(h.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(h.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(h.HeaderProps) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2, b3), nil +} + +// UnmarshalJSON unmarshals this header from JSON +func (h *Header) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &h.CommonValidations); err != nil { + return err + } + if err := json.Unmarshal(data, &h.SimpleSchema); err != nil { + return err + } + if err := json.Unmarshal(data, &h.VendorExtensible); err != nil { + return err + } + return json.Unmarshal(data, &h.HeaderProps) +} + +// JSONLookup look up a value by the json property name +func (h Header) JSONLookup(token string) (interface{}, error) { + if ex, ok := h.Extensions[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(h.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(h.SimpleSchema, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(h.HeaderProps, token) + return r, err +} diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go new file mode 100644 index 000000000..c458b49b2 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/info.go @@ -0,0 +1,165 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// Extensions vendor specific extensions +type Extensions map[string]interface{} + +// Add adds a value to these extensions +func (e Extensions) Add(key string, value interface{}) { + realKey := strings.ToLower(key) + e[realKey] = value +} + +// GetString gets a string value from the extensions +func (e Extensions) GetString(key string) (string, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + str, ok := v.(string) + return str, ok + } + return "", false +} + +// GetBool gets a string value from the extensions +func (e Extensions) GetBool(key string) (bool, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + str, ok := v.(bool) + return str, ok + } + return false, false +} + +// GetStringSlice gets a string value from the extensions +func (e Extensions) GetStringSlice(key string) ([]string, bool) { + if v, ok := e[strings.ToLower(key)]; ok { + arr, isSlice := v.([]interface{}) + if !isSlice { + return nil, false + } + var strs []string + for _, iface := range arr { + str, isString := iface.(string) + if !isString { + return nil, false + } + strs = append(strs, str) + } + return strs, ok + } + return nil, false +} + +// VendorExtensible composition block. +type VendorExtensible struct { + Extensions Extensions +} + +// AddExtension adds an extension to this extensible object +func (v *VendorExtensible) AddExtension(key string, value interface{}) { + if value == nil { + return + } + if v.Extensions == nil { + v.Extensions = make(map[string]interface{}) + } + v.Extensions.Add(key, value) +} + +// MarshalJSON marshals the extensions to json +func (v VendorExtensible) MarshalJSON() ([]byte, error) { + toser := make(map[string]interface{}) + for k, v := range v.Extensions { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + toser[k] = v + } + } + return json.Marshal(toser) +} + +// UnmarshalJSON for this extensible object +func (v *VendorExtensible) UnmarshalJSON(data []byte) error { + var d map[string]interface{} + if err := json.Unmarshal(data, &d); err != nil { + return err + } + for k, vv := range d { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + if v.Extensions == nil { + v.Extensions = map[string]interface{}{} + } + v.Extensions[k] = vv + } + } + return nil +} + +// InfoProps the properties for an info definition +type InfoProps struct { + Description string `json:"description,omitempty"` + Title string `json:"title,omitempty"` + TermsOfService string `json:"termsOfService,omitempty"` + Contact *ContactInfo `json:"contact,omitempty"` + License *License `json:"license,omitempty"` + Version string `json:"version,omitempty"` +} + +// Info object provides metadata about the API. +// The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. +// +// For more information: http://goo.gl/8us55a#infoObject +type Info struct { + VendorExtensible + InfoProps +} + +// JSONLookup look up a value by the json property name +func (i Info) JSONLookup(token string) (interface{}, error) { + if ex, ok := i.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(i.InfoProps, token) + return r, err +} + +// MarshalJSON marshal this to JSON +func (i Info) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(i.InfoProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(i.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON marshal this from JSON +func (i *Info) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &i.InfoProps); err != nil { + return err + } + return json.Unmarshal(data, &i.VendorExtensible) +} diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go new file mode 100644 index 000000000..e2afb2133 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/items.go @@ -0,0 +1,234 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +const ( + jsonRef = "$ref" +) + +// SimpleSchema describe swagger simple schemas for parameters and headers +type SimpleSchema struct { + Type string `json:"type,omitempty"` + Nullable bool `json:"nullable,omitempty"` + Format string `json:"format,omitempty"` + Items *Items `json:"items,omitempty"` + CollectionFormat string `json:"collectionFormat,omitempty"` + Default interface{} `json:"default,omitempty"` + Example interface{} `json:"example,omitempty"` +} + +// TypeName return the type (or format) of a simple schema +func (s *SimpleSchema) TypeName() string { + if s.Format != "" { + return s.Format + } + return s.Type +} + +// ItemsTypeName yields the type of items in a simple schema array +func (s *SimpleSchema) ItemsTypeName() string { + if s.Items == nil { + return "" + } + return s.Items.TypeName() +} + +// Items a limited subset of JSON-Schema's items object. +// It is used by parameter definitions that are not located in "body". +// +// For more information: http://goo.gl/8us55a#items-object +type Items struct { + Refable + CommonValidations + SimpleSchema + VendorExtensible +} + +// NewItems creates a new instance of items +func NewItems() *Items { + return &Items{} +} + +// Typed a fluent builder method for the type of item +func (i *Items) Typed(tpe, format string) *Items { + i.Type = tpe + i.Format = format + return i +} + +// AsNullable flags this schema as nullable. +func (i *Items) AsNullable() *Items { + i.Nullable = true + return i +} + +// CollectionOf a fluent builder method for an array item +func (i *Items) CollectionOf(items *Items, format string) *Items { + i.Type = jsonArray + i.Items = items + i.CollectionFormat = format + return i +} + +// WithDefault sets the default value on this item +func (i *Items) WithDefault(defaultValue interface{}) *Items { + i.Default = defaultValue + return i +} + +// WithMaxLength sets a max length value +func (i *Items) WithMaxLength(max int64) *Items { + i.MaxLength = &max + return i +} + +// WithMinLength sets a min length value +func (i *Items) WithMinLength(min int64) *Items { + i.MinLength = &min + return i +} + +// WithPattern sets a pattern value +func (i *Items) WithPattern(pattern string) *Items { + i.Pattern = pattern + return i +} + +// WithMultipleOf sets a multiple of value +func (i *Items) WithMultipleOf(number float64) *Items { + i.MultipleOf = &number + return i +} + +// WithMaximum sets a maximum number value +func (i *Items) WithMaximum(max float64, exclusive bool) *Items { + i.Maximum = &max + i.ExclusiveMaximum = exclusive + return i +} + +// WithMinimum sets a minimum number value +func (i *Items) WithMinimum(min float64, exclusive bool) *Items { + i.Minimum = &min + i.ExclusiveMinimum = exclusive + return i +} + +// WithEnum sets a the enum values (replace) +func (i *Items) WithEnum(values ...interface{}) *Items { + i.Enum = append([]interface{}{}, values...) + return i +} + +// WithMaxItems sets the max items +func (i *Items) WithMaxItems(size int64) *Items { + i.MaxItems = &size + return i +} + +// WithMinItems sets the min items +func (i *Items) WithMinItems(size int64) *Items { + i.MinItems = &size + return i +} + +// UniqueValues dictates that this array can only have unique items +func (i *Items) UniqueValues() *Items { + i.UniqueItems = true + return i +} + +// AllowDuplicates this array can have duplicates +func (i *Items) AllowDuplicates() *Items { + i.UniqueItems = false + return i +} + +// WithValidations is a fluent method to set Items validations +func (i *Items) WithValidations(val CommonValidations) *Items { + i.SetValidations(SchemaValidations{CommonValidations: val}) + return i +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (i *Items) UnmarshalJSON(data []byte) error { + var validations CommonValidations + if err := json.Unmarshal(data, &validations); err != nil { + return err + } + var ref Refable + if err := json.Unmarshal(data, &ref); err != nil { + return err + } + var simpleSchema SimpleSchema + if err := json.Unmarshal(data, &simpleSchema); err != nil { + return err + } + var vendorExtensible VendorExtensible + if err := json.Unmarshal(data, &vendorExtensible); err != nil { + return err + } + i.Refable = ref + i.CommonValidations = validations + i.SimpleSchema = simpleSchema + i.VendorExtensible = vendorExtensible + return nil +} + +// MarshalJSON converts this items object to JSON +func (i Items) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(i.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(i.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(i.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(i.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b4, b3, b1, b2), nil +} + +// JSONLookup look up a value by the json property name +func (i Items) JSONLookup(token string) (interface{}, error) { + if token == jsonRef { + return &i.Ref, nil + } + + r, _, err := jsonpointer.GetForToken(i.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(i.SimpleSchema, token) + return r, err +} diff --git a/vendor/github.com/go-openapi/spec/license.go b/vendor/github.com/go-openapi/spec/license.go new file mode 100644 index 000000000..b42f80368 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/license.go @@ -0,0 +1,56 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + + "github.com/go-openapi/swag" +) + +// License information for the exposed API. +// +// For more information: http://goo.gl/8us55a#licenseObject +type License struct { + LicenseProps + VendorExtensible +} + +// LicenseProps holds the properties of a License object +type LicenseProps struct { + Name string `json:"name,omitempty"` + URL string `json:"url,omitempty"` +} + +// UnmarshalJSON hydrates License from json +func (l *License) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &l.LicenseProps); err != nil { + return err + } + return json.Unmarshal(data, &l.VendorExtensible) +} + +// MarshalJSON produces License as json +func (l License) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(l.LicenseProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(l.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} diff --git a/vendor/github.com/go-openapi/spec/normalizer.go b/vendor/github.com/go-openapi/spec/normalizer.go new file mode 100644 index 000000000..d6c483971 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/normalizer.go @@ -0,0 +1,203 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "net/url" + "path" + "strings" +) + +const fileScheme = "file" + +// normalizeURI ensures that all $ref paths used internally by the expander are canonicalized. +// +// NOTE(windows): there is a tolerance over the strict URI format on windows. +// +// The normalizer accepts relative file URLs like 'Path\File.JSON' as well as absolute file URLs like +// 'C:\Path\file.Yaml'. +// +// Both are canonicalized with a "file://" scheme, slashes and a lower-cased path: +// 'file:///c:/path/file.yaml' +// +// URLs can be specified with a file scheme, like in 'file:///folder/file.json' or +// 'file:///c:\folder\File.json'. +// +// URLs like file://C:\folder are considered invalid (i.e. there is no host 'c:\folder') and a "repair" +// is attempted. +// +// The base path argument is assumed to be canonicalized (e.g. using normalizeBase()). +func normalizeURI(refPath, base string) string { + refURL, err := url.Parse(refPath) + if err != nil { + specLogger.Printf("warning: invalid URI in $ref %q: %v", refPath, err) + refURL, refPath = repairURI(refPath) + } + + fixWindowsURI(refURL, refPath) // noop on non-windows OS + + refURL.Path = path.Clean(refURL.Path) + if refURL.Path == "." { + refURL.Path = "" + } + + r := MustCreateRef(refURL.String()) + if r.IsCanonical() { + return refURL.String() + } + + baseURL, _ := url.Parse(base) + if path.IsAbs(refURL.Path) { + baseURL.Path = refURL.Path + } else if refURL.Path != "" { + baseURL.Path = path.Join(path.Dir(baseURL.Path), refURL.Path) + } + // copying fragment from ref to base + baseURL.Fragment = refURL.Fragment + + return baseURL.String() +} + +// denormalizeRef returns the simplest notation for a normalized $ref, given the path of the original root document. +// +// When calling this, we assume that: +// * $ref is a canonical URI +// * originalRelativeBase is a canonical URI +// +// denormalizeRef is currently used when we rewrite a $ref after a circular $ref has been detected. +// In this case, expansion stops and normally renders the internal canonical $ref. +// +// This internal $ref is eventually rebased to the original RelativeBase used for the expansion. +// +// There is a special case for schemas that are anchored with an "id": +// in that case, the rebasing is performed // against the id only if this is an anchor for the initial root document. +// All other intermediate "id"'s found along the way are ignored for the purpose of rebasing. +// +func denormalizeRef(ref *Ref, originalRelativeBase, id string) Ref { + debugLog("denormalizeRef called:\n$ref: %q\noriginal: %s\nroot ID:%s", ref.String(), originalRelativeBase, id) + + if ref.String() == "" || ref.IsRoot() || ref.HasFragmentOnly { + // short circuit: $ref to current doc + return *ref + } + + if id != "" { + idBaseURL, err := url.Parse(id) + if err == nil { // if the schema id is not usable as a URI, ignore it + if ref, ok := rebase(ref, idBaseURL, true); ok { // rebase, but keep references to root unchaged (do not want $ref: "") + // $ref relative to the ID of the schema in the root document + return ref + } + } + } + + originalRelativeBaseURL, _ := url.Parse(originalRelativeBase) + + r, _ := rebase(ref, originalRelativeBaseURL, false) + + return r +} + +func rebase(ref *Ref, v *url.URL, notEqual bool) (Ref, bool) { + var newBase url.URL + + u := ref.GetURL() + + if u.Scheme != v.Scheme || u.Host != v.Host { + return *ref, false + } + + docPath := v.Path + v.Path = path.Dir(v.Path) + + if v.Path == "." { + v.Path = "" + } else if !strings.HasSuffix(v.Path, "/") { + v.Path += "/" + } + + newBase.Fragment = u.Fragment + + if strings.HasPrefix(u.Path, docPath) { + newBase.Path = strings.TrimPrefix(u.Path, docPath) + } else { + newBase.Path = strings.TrimPrefix(u.Path, v.Path) + } + + if notEqual && newBase.Path == "" && newBase.Fragment == "" { + // do not want rebasing to end up in an empty $ref + return *ref, false + } + + if path.IsAbs(newBase.Path) { + // whenever we end up with an absolute path, specify the scheme and host + newBase.Scheme = v.Scheme + newBase.Host = v.Host + } + + return MustCreateRef(newBase.String()), true +} + +// normalizeRef canonicalize a Ref, using a canonical relativeBase as its absolute anchor +func normalizeRef(ref *Ref, relativeBase string) *Ref { + r := MustCreateRef(normalizeURI(ref.String(), relativeBase)) + return &r +} + +// normalizeBase performs a normalization of the input base path. +// +// This always yields a canonical URI (absolute), usable for the document cache. +// +// It ensures that all further internal work on basePath may safely assume +// a non-empty, cross-platform, canonical URI (i.e. absolute). +// +// This normalization tolerates windows paths (e.g. C:\x\y\File.dat) and transform this +// in a file:// URL with lower cased drive letter and path. +// +// See also: https://en.wikipedia.org/wiki/File_URI_scheme +func normalizeBase(in string) string { + u, err := url.Parse(in) + if err != nil { + specLogger.Printf("warning: invalid URI in RelativeBase %q: %v", in, err) + u, in = repairURI(in) + } + + u.Fragment = "" // any fragment in the base is irrelevant + + fixWindowsURI(u, in) // noop on non-windows OS + + u.Path = path.Clean(u.Path) + if u.Path == "." { // empty after Clean() + u.Path = "" + } + + if u.Scheme != "" { + if path.IsAbs(u.Path) || u.Scheme != fileScheme { + // this is absolute or explicitly not a local file: we're good + return u.String() + } + } + + // no scheme or file scheme with relative path: assume file and make it absolute + // enforce scheme file://... with absolute path. + // + // If the input path is relative, we anchor the path to the current working directory. + // NOTE: we may end up with a host component. Leave it unchanged: e.g. file://host/folder/file.json + + u.Scheme = fileScheme + u.Path = absPath(u.Path) // platform-dependent + u.RawQuery = "" // any query component is irrelevant for a base + return u.String() +} diff --git a/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go b/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go new file mode 100644 index 000000000..c8a064534 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go @@ -0,0 +1,43 @@ +// +build !windows + +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "net/url" + "path/filepath" +) + +// absPath makes a file path absolute and compatible with a URI path component. +// +// The parameter must be a path, not an URI. +func absPath(in string) string { + anchored, err := filepath.Abs(in) + if err != nil { + specLogger.Printf("warning: could not resolve current working directory: %v", err) + return in + } + return anchored +} + +func repairURI(in string) (*url.URL, string) { + u, _ := url.Parse("") + debugLog("repaired URI: original: %q, repaired: %q", in, "") + return u, "" +} + +func fixWindowsURI(u *url.URL, in string) { +} diff --git a/vendor/github.com/go-openapi/spec/normalizer_windows.go b/vendor/github.com/go-openapi/spec/normalizer_windows.go new file mode 100644 index 000000000..fe2d1ecd4 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/normalizer_windows.go @@ -0,0 +1,154 @@ +// -build windows + +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "net/url" + "os" + "path" + "path/filepath" + "strings" +) + +// absPath makes a file path absolute and compatible with a URI path component +// +// The parameter must be a path, not an URI. +func absPath(in string) string { + // NOTE(windows): filepath.Abs exhibits a special behavior on windows for empty paths. + // See https://github.com/golang/go/issues/24441 + if in == "" { + in = "." + } + + anchored, err := filepath.Abs(in) + if err != nil { + specLogger.Printf("warning: could not resolve current working directory: %v", err) + return in + } + + pth := strings.ReplaceAll(strings.ToLower(anchored), `\`, `/`) + if !strings.HasPrefix(pth, "/") { + pth = "/" + pth + } + + return path.Clean(pth) +} + +// repairURI tolerates invalid file URIs with common typos +// such as 'file://E:\folder\file', that break the regular URL parser. +// +// Adopting the same defaults as for unixes (e.g. return an empty path) would +// result into a counter-intuitive result for that case (e.g. E:\folder\file is +// eventually resolved as the current directory). The repair will detect the missing "/". +// +// Note that this only works for the file scheme. +func repairURI(in string) (*url.URL, string) { + const prefix = fileScheme + "://" + if !strings.HasPrefix(in, prefix) { + // giving up: resolve to empty path + u, _ := url.Parse("") + + return u, "" + } + + // attempt the repair, stripping the scheme should be sufficient + u, _ := url.Parse(strings.TrimPrefix(in, prefix)) + debugLog("repaired URI: original: %q, repaired: %q", in, u.String()) + + return u, u.String() +} + +// fixWindowsURI tolerates an absolute file path on windows such as C:\Base\File.yaml or \\host\share\Base\File.yaml +// and makes it a canonical URI: file:///c:/base/file.yaml +// +// Catch 22 notes for Windows: +// +// * There may be a drive letter on windows (it is lower-cased) +// * There may be a share UNC, e.g. \\server\folder\data.xml +// * Paths are case insensitive +// * Paths may already contain slashes +// * Paths must be slashed +// +// NOTE: there is no escaping. "/" may be valid separators just like "\". +// We don't use ToSlash() (which escapes everything) because windows now also +// tolerates the use of "/". Hence, both C:\File.yaml and C:/File.yaml will work. +func fixWindowsURI(u *url.URL, in string) { + drive := filepath.VolumeName(in) + + if len(drive) > 0 { + if len(u.Scheme) == 1 && strings.EqualFold(u.Scheme, drive[:1]) { // a path with a drive letter + u.Scheme = fileScheme + u.Host = "" + u.Path = strings.Join([]string{drive, u.Opaque, u.Path}, `/`) // reconstruct the full path component (no fragment, no query) + } else if u.Host == "" && strings.HasPrefix(u.Path, drive) { // a path with a \\host volume + // NOTE: the special host@port syntax for UNC is not supported (yet) + u.Scheme = fileScheme + + // this is a modified version of filepath.Dir() to apply on the VolumeName itself + i := len(drive) - 1 + for i >= 0 && !os.IsPathSeparator(drive[i]) { + i-- + } + host := drive[:i] // \\host\share => host + + u.Path = strings.TrimPrefix(u.Path, host) + u.Host = strings.TrimPrefix(host, `\\`) + } + + u.Opaque = "" + u.Path = strings.ReplaceAll(strings.ToLower(u.Path), `\`, `/`) + + // ensure we form an absolute path + if !strings.HasPrefix(u.Path, "/") { + u.Path = "/" + u.Path + } + + u.Path = path.Clean(u.Path) + + return + } + + if u.Scheme == fileScheme { + // Handle dodgy cases for file://{...} URIs on windows. + // A canonical URI should always be followed by an absolute path. + // + // Examples: + // * file:///folder/file => valid, unchanged + // * file:///c:\folder\file => slashed + // * file:///./folder/file => valid, cleaned to remove the dot + // * file:///.\folder\file => remapped to cwd + // * file:///. => dodgy, remapped to / (consistent with the behavior on unix) + // * file:///.. => dodgy, remapped to / (consistent with the behavior on unix) + if (!path.IsAbs(u.Path) && !filepath.IsAbs(u.Path)) || (strings.HasPrefix(u.Path, `/.`) && strings.Contains(u.Path, `\`)) { + // ensure we form an absolute path + u.Path, _ = filepath.Abs(strings.TrimLeft(u.Path, `/`)) + if !strings.HasPrefix(u.Path, "/") { + u.Path = "/" + u.Path + } + } + u.Path = strings.ToLower(u.Path) + } + + // NOTE: lower case normalization does not propagate to inner resources, + // generated when rebasing: when joining a relative URI with a file to an absolute base, + // only the base is currently lower-cased. + // + // For now, we assume this is good enough for most use cases + // and try not to generate too many differences + // between the output produced on different platforms. + u.Path = path.Clean(strings.ReplaceAll(u.Path, `\`, `/`)) +} diff --git a/vendor/github.com/go-openapi/spec/operation.go b/vendor/github.com/go-openapi/spec/operation.go new file mode 100644 index 000000000..995ce6acb --- /dev/null +++ b/vendor/github.com/go-openapi/spec/operation.go @@ -0,0 +1,397 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "bytes" + "encoding/gob" + "encoding/json" + "sort" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +func init() { + gob.Register(map[string]interface{}{}) + gob.Register([]interface{}{}) +} + +// OperationProps describes an operation +// +// NOTES: +// - schemes, when present must be from [http, https, ws, wss]: see validate +// - Security is handled as a special case: see MarshalJSON function +type OperationProps struct { + Description string `json:"description,omitempty"` + Consumes []string `json:"consumes,omitempty"` + Produces []string `json:"produces,omitempty"` + Schemes []string `json:"schemes,omitempty"` + Tags []string `json:"tags,omitempty"` + Summary string `json:"summary,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` + ID string `json:"operationId,omitempty"` + Deprecated bool `json:"deprecated,omitempty"` + Security []map[string][]string `json:"security,omitempty"` + Parameters []Parameter `json:"parameters,omitempty"` + Responses *Responses `json:"responses,omitempty"` +} + +// MarshalJSON takes care of serializing operation properties to JSON +// +// We use a custom marhaller here to handle a special cases related to +// the Security field. We need to preserve zero length slice +// while omitting the field when the value is nil/unset. +func (op OperationProps) MarshalJSON() ([]byte, error) { + type Alias OperationProps + if op.Security == nil { + return json.Marshal(&struct { + Security []map[string][]string `json:"security,omitempty"` + *Alias + }{ + Security: op.Security, + Alias: (*Alias)(&op), + }) + } + return json.Marshal(&struct { + Security []map[string][]string `json:"security"` + *Alias + }{ + Security: op.Security, + Alias: (*Alias)(&op), + }) +} + +// Operation describes a single API operation on a path. +// +// For more information: http://goo.gl/8us55a#operationObject +type Operation struct { + VendorExtensible + OperationProps +} + +// SuccessResponse gets a success response model +func (o *Operation) SuccessResponse() (*Response, int, bool) { + if o.Responses == nil { + return nil, 0, false + } + + responseCodes := make([]int, 0, len(o.Responses.StatusCodeResponses)) + for k := range o.Responses.StatusCodeResponses { + if k >= 200 && k < 300 { + responseCodes = append(responseCodes, k) + } + } + if len(responseCodes) > 0 { + sort.Ints(responseCodes) + v := o.Responses.StatusCodeResponses[responseCodes[0]] + return &v, responseCodes[0], true + } + + return o.Responses.Default, 0, false +} + +// JSONLookup look up a value by the json property name +func (o Operation) JSONLookup(token string) (interface{}, error) { + if ex, ok := o.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(o.OperationProps, token) + return r, err +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (o *Operation) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &o.OperationProps); err != nil { + return err + } + return json.Unmarshal(data, &o.VendorExtensible) +} + +// MarshalJSON converts this items object to JSON +func (o Operation) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(o.OperationProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(o.VendorExtensible) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil +} + +// NewOperation creates a new operation instance. +// It expects an ID as parameter but not passing an ID is also valid. +func NewOperation(id string) *Operation { + op := new(Operation) + op.ID = id + return op +} + +// WithID sets the ID property on this operation, allows for chaining. +func (o *Operation) WithID(id string) *Operation { + o.ID = id + return o +} + +// WithDescription sets the description on this operation, allows for chaining +func (o *Operation) WithDescription(description string) *Operation { + o.Description = description + return o +} + +// WithSummary sets the summary on this operation, allows for chaining +func (o *Operation) WithSummary(summary string) *Operation { + o.Summary = summary + return o +} + +// WithExternalDocs sets/removes the external docs for/from this operation. +// When you pass empty strings as params the external documents will be removed. +// When you pass non-empty string as one value then those values will be used on the external docs object. +// So when you pass a non-empty description, you should also pass the url and vice versa. +func (o *Operation) WithExternalDocs(description, url string) *Operation { + if description == "" && url == "" { + o.ExternalDocs = nil + return o + } + + if o.ExternalDocs == nil { + o.ExternalDocs = &ExternalDocumentation{} + } + o.ExternalDocs.Description = description + o.ExternalDocs.URL = url + return o +} + +// Deprecate marks the operation as deprecated +func (o *Operation) Deprecate() *Operation { + o.Deprecated = true + return o +} + +// Undeprecate marks the operation as not deprected +func (o *Operation) Undeprecate() *Operation { + o.Deprecated = false + return o +} + +// WithConsumes adds media types for incoming body values +func (o *Operation) WithConsumes(mediaTypes ...string) *Operation { + o.Consumes = append(o.Consumes, mediaTypes...) + return o +} + +// WithProduces adds media types for outgoing body values +func (o *Operation) WithProduces(mediaTypes ...string) *Operation { + o.Produces = append(o.Produces, mediaTypes...) + return o +} + +// WithTags adds tags for this operation +func (o *Operation) WithTags(tags ...string) *Operation { + o.Tags = append(o.Tags, tags...) + return o +} + +// AddParam adds a parameter to this operation, when a parameter for that location +// and with that name already exists it will be replaced +func (o *Operation) AddParam(param *Parameter) *Operation { + if param == nil { + return o + } + + for i, p := range o.Parameters { + if p.Name == param.Name && p.In == param.In { + params := append(o.Parameters[:i], *param) + params = append(params, o.Parameters[i+1:]...) + o.Parameters = params + return o + } + } + + o.Parameters = append(o.Parameters, *param) + return o +} + +// RemoveParam removes a parameter from the operation +func (o *Operation) RemoveParam(name, in string) *Operation { + for i, p := range o.Parameters { + if p.Name == name && p.In == in { + o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...) + return o + } + } + return o +} + +// SecuredWith adds a security scope to this operation. +func (o *Operation) SecuredWith(name string, scopes ...string) *Operation { + o.Security = append(o.Security, map[string][]string{name: scopes}) + return o +} + +// WithDefaultResponse adds a default response to the operation. +// Passing a nil value will remove the response +func (o *Operation) WithDefaultResponse(response *Response) *Operation { + return o.RespondsWith(0, response) +} + +// RespondsWith adds a status code response to the operation. +// When the code is 0 the value of the response will be used as default response value. +// When the value of the response is nil it will be removed from the operation +func (o *Operation) RespondsWith(code int, response *Response) *Operation { + if o.Responses == nil { + o.Responses = new(Responses) + } + if code == 0 { + o.Responses.Default = response + return o + } + if response == nil { + delete(o.Responses.StatusCodeResponses, code) + return o + } + if o.Responses.StatusCodeResponses == nil { + o.Responses.StatusCodeResponses = make(map[int]Response) + } + o.Responses.StatusCodeResponses[code] = *response + return o +} + +type opsAlias OperationProps + +type gobAlias struct { + Security []map[string]struct { + List []string + Pad bool + } + Alias *opsAlias + SecurityIsEmpty bool +} + +// GobEncode provides a safe gob encoder for Operation, including empty security requirements +func (o Operation) GobEncode() ([]byte, error) { + raw := struct { + Ext VendorExtensible + Props OperationProps + }{ + Ext: o.VendorExtensible, + Props: o.OperationProps, + } + var b bytes.Buffer + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err +} + +// GobDecode provides a safe gob decoder for Operation, including empty security requirements +func (o *Operation) GobDecode(b []byte) error { + var raw struct { + Ext VendorExtensible + Props OperationProps + } + + buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + o.VendorExtensible = raw.Ext + o.OperationProps = raw.Props + return nil +} + +// GobEncode provides a safe gob encoder for Operation, including empty security requirements +func (op OperationProps) GobEncode() ([]byte, error) { + raw := gobAlias{ + Alias: (*opsAlias)(&op), + } + + var b bytes.Buffer + if op.Security == nil { + // nil security requirement + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } + + if len(op.Security) == 0 { + // empty, but non-nil security requirement + raw.SecurityIsEmpty = true + raw.Alias.Security = nil + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } + + raw.Security = make([]map[string]struct { + List []string + Pad bool + }, 0, len(op.Security)) + for _, req := range op.Security { + v := make(map[string]struct { + List []string + Pad bool + }, len(req)) + for k, val := range req { + v[k] = struct { + List []string + Pad bool + }{ + List: val, + } + } + raw.Security = append(raw.Security, v) + } + + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err +} + +// GobDecode provides a safe gob decoder for Operation, including empty security requirements +func (op *OperationProps) GobDecode(b []byte) error { + var raw gobAlias + + buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + if raw.Alias == nil { + return nil + } + + switch { + case raw.SecurityIsEmpty: + // empty, but non-nil security requirement + raw.Alias.Security = []map[string][]string{} + case len(raw.Alias.Security) == 0: + // nil security requirement + raw.Alias.Security = nil + default: + raw.Alias.Security = make([]map[string][]string, 0, len(raw.Security)) + for _, req := range raw.Security { + v := make(map[string][]string, len(req)) + for k, val := range req { + v[k] = make([]string, 0, len(val.List)) + v[k] = append(v[k], val.List...) + } + raw.Alias.Security = append(raw.Alias.Security, v) + } + } + + *op = *(*OperationProps)(raw.Alias) + return nil +} diff --git a/vendor/github.com/go-openapi/spec/parameter.go b/vendor/github.com/go-openapi/spec/parameter.go new file mode 100644 index 000000000..2b2b89b67 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/parameter.go @@ -0,0 +1,326 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// QueryParam creates a query parameter +func QueryParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}} +} + +// HeaderParam creates a header parameter, this is always required by default +func HeaderParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}} +} + +// PathParam creates a path parameter, this is always required +func PathParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}} +} + +// BodyParam creates a body parameter +func BodyParam(name string, schema *Schema) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema}} +} + +// FormDataParam creates a body parameter +func FormDataParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}} +} + +// FileParam creates a body parameter +func FileParam(name string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}, + SimpleSchema: SimpleSchema{Type: "file"}} +} + +// SimpleArrayParam creates a param for a simple array (string, int, date etc) +func SimpleArrayParam(name, tpe, fmt string) *Parameter { + return &Parameter{ParamProps: ParamProps{Name: name}, + SimpleSchema: SimpleSchema{Type: jsonArray, CollectionFormat: "csv", + Items: &Items{SimpleSchema: SimpleSchema{Type: tpe, Format: fmt}}}} +} + +// ParamRef creates a parameter that's a json reference +func ParamRef(uri string) *Parameter { + p := new(Parameter) + p.Ref = MustCreateRef(uri) + return p +} + +// ParamProps describes the specific attributes of an operation parameter +// +// NOTE: +// - Schema is defined when "in" == "body": see validate +// - AllowEmptyValue is allowed where "in" == "query" || "formData" +type ParamProps struct { + Description string `json:"description,omitempty"` + Name string `json:"name,omitempty"` + In string `json:"in,omitempty"` + Required bool `json:"required,omitempty"` + Schema *Schema `json:"schema,omitempty"` + AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` +} + +// Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). +// +// There are five possible parameter types. +// * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part +// of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, +// the path parameter is `itemId`. +// * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +// * Header - Custom headers that are expected as part of the request. +// * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be +// _one_ body parameter. The name of the body parameter has no effect on the parameter itself and is used for +// documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist +// together for the same operation. +// * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or +// `multipart/form-data` are used as the content type of the request (in Swagger's definition, +// the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used +// to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be +// declared together with a body parameter for the same operation. Form parameters have a different format based on +// the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4). +// * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. +// For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple +// parameters that are being transferred. +// * `multipart/form-data` - each parameter takes a section in the payload with an internal header. +// For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is +// `submit-name`. This type of form parameters is more commonly used for file transfers. +// +// For more information: http://goo.gl/8us55a#parameterObject +type Parameter struct { + Refable + CommonValidations + SimpleSchema + VendorExtensible + ParamProps +} + +// JSONLookup look up a value by the json property name +func (p Parameter) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + if token == jsonRef { + return &p.Ref, nil + } + + r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) + if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { + return nil, err + } + if r != nil { + return r, nil + } + r, _, err = jsonpointer.GetForToken(p.ParamProps, token) + return r, err +} + +// WithDescription a fluent builder method for the description of the parameter +func (p *Parameter) WithDescription(description string) *Parameter { + p.Description = description + return p +} + +// Named a fluent builder method to override the name of the parameter +func (p *Parameter) Named(name string) *Parameter { + p.Name = name + return p +} + +// WithLocation a fluent builder method to override the location of the parameter +func (p *Parameter) WithLocation(in string) *Parameter { + p.In = in + return p +} + +// Typed a fluent builder method for the type of the parameter value +func (p *Parameter) Typed(tpe, format string) *Parameter { + p.Type = tpe + p.Format = format + return p +} + +// CollectionOf a fluent builder method for an array parameter +func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { + p.Type = jsonArray + p.Items = items + p.CollectionFormat = format + return p +} + +// WithDefault sets the default value on this parameter +func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter { + p.AsOptional() // with default implies optional + p.Default = defaultValue + return p +} + +// AllowsEmptyValues flags this parameter as being ok with empty values +func (p *Parameter) AllowsEmptyValues() *Parameter { + p.AllowEmptyValue = true + return p +} + +// NoEmptyValues flags this parameter as not liking empty values +func (p *Parameter) NoEmptyValues() *Parameter { + p.AllowEmptyValue = false + return p +} + +// AsOptional flags this parameter as optional +func (p *Parameter) AsOptional() *Parameter { + p.Required = false + return p +} + +// AsRequired flags this parameter as required +func (p *Parameter) AsRequired() *Parameter { + if p.Default != nil { // with a default required makes no sense + return p + } + p.Required = true + return p +} + +// WithMaxLength sets a max length value +func (p *Parameter) WithMaxLength(max int64) *Parameter { + p.MaxLength = &max + return p +} + +// WithMinLength sets a min length value +func (p *Parameter) WithMinLength(min int64) *Parameter { + p.MinLength = &min + return p +} + +// WithPattern sets a pattern value +func (p *Parameter) WithPattern(pattern string) *Parameter { + p.Pattern = pattern + return p +} + +// WithMultipleOf sets a multiple of value +func (p *Parameter) WithMultipleOf(number float64) *Parameter { + p.MultipleOf = &number + return p +} + +// WithMaximum sets a maximum number value +func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter { + p.Maximum = &max + p.ExclusiveMaximum = exclusive + return p +} + +// WithMinimum sets a minimum number value +func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter { + p.Minimum = &min + p.ExclusiveMinimum = exclusive + return p +} + +// WithEnum sets a the enum values (replace) +func (p *Parameter) WithEnum(values ...interface{}) *Parameter { + p.Enum = append([]interface{}{}, values...) + return p +} + +// WithMaxItems sets the max items +func (p *Parameter) WithMaxItems(size int64) *Parameter { + p.MaxItems = &size + return p +} + +// WithMinItems sets the min items +func (p *Parameter) WithMinItems(size int64) *Parameter { + p.MinItems = &size + return p +} + +// UniqueValues dictates that this array can only have unique items +func (p *Parameter) UniqueValues() *Parameter { + p.UniqueItems = true + return p +} + +// AllowDuplicates this array can have duplicates +func (p *Parameter) AllowDuplicates() *Parameter { + p.UniqueItems = false + return p +} + +// WithValidations is a fluent method to set parameter validations +func (p *Parameter) WithValidations(val CommonValidations) *Parameter { + p.SetValidations(SchemaValidations{CommonValidations: val}) + return p +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (p *Parameter) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &p.CommonValidations); err != nil { + return err + } + if err := json.Unmarshal(data, &p.Refable); err != nil { + return err + } + if err := json.Unmarshal(data, &p.SimpleSchema); err != nil { + return err + } + if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { + return err + } + return json.Unmarshal(data, &p.ParamProps) +} + +// MarshalJSON converts this items object to JSON +func (p Parameter) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(p.CommonValidations) + if err != nil { + return nil, err + } + b2, err := json.Marshal(p.SimpleSchema) + if err != nil { + return nil, err + } + b3, err := json.Marshal(p.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + b5, err := json.Marshal(p.ParamProps) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b3, b1, b2, b4, b5), nil +} diff --git a/vendor/github.com/go-openapi/spec/path_item.go b/vendor/github.com/go-openapi/spec/path_item.go new file mode 100644 index 000000000..68fc8e901 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/path_item.go @@ -0,0 +1,87 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// PathItemProps the path item specific properties +type PathItemProps struct { + Get *Operation `json:"get,omitempty"` + Put *Operation `json:"put,omitempty"` + Post *Operation `json:"post,omitempty"` + Delete *Operation `json:"delete,omitempty"` + Options *Operation `json:"options,omitempty"` + Head *Operation `json:"head,omitempty"` + Patch *Operation `json:"patch,omitempty"` + Parameters []Parameter `json:"parameters,omitempty"` +} + +// PathItem describes the operations available on a single path. +// A Path Item may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). +// The path itself is still exposed to the documentation viewer but they will +// not know which operations and parameters are available. +// +// For more information: http://goo.gl/8us55a#pathItemObject +type PathItem struct { + Refable + VendorExtensible + PathItemProps +} + +// JSONLookup look up a value by the json property name +func (p PathItem) JSONLookup(token string) (interface{}, error) { + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + if token == jsonRef { + return &p.Ref, nil + } + r, _, err := jsonpointer.GetForToken(p.PathItemProps, token) + return r, err +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (p *PathItem) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &p.Refable); err != nil { + return err + } + if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { + return err + } + return json.Unmarshal(data, &p.PathItemProps) +} + +// MarshalJSON converts this items object to JSON +func (p PathItem) MarshalJSON() ([]byte, error) { + b3, err := json.Marshal(p.Refable) + if err != nil { + return nil, err + } + b4, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + b5, err := json.Marshal(p.PathItemProps) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b3, b4, b5) + return concated, nil +} diff --git a/vendor/github.com/go-openapi/spec/paths.go b/vendor/github.com/go-openapi/spec/paths.go new file mode 100644 index 000000000..9dc82a290 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/paths.go @@ -0,0 +1,97 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/go-openapi/swag" +) + +// Paths holds the relative paths to the individual endpoints. +// The path is appended to the [`basePath`](http://goo.gl/8us55a#swaggerBasePath) in order +// to construct the full URL. +// The Paths may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). +// +// For more information: http://goo.gl/8us55a#pathsObject +type Paths struct { + VendorExtensible + Paths map[string]PathItem `json:"-"` // custom serializer to flatten this, each entry must start with "/" +} + +// JSONLookup look up a value by the json property name +func (p Paths) JSONLookup(token string) (interface{}, error) { + if pi, ok := p.Paths[token]; ok { + return &pi, nil + } + if ex, ok := p.Extensions[token]; ok { + return &ex, nil + } + return nil, fmt.Errorf("object has no field %q", token) +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (p *Paths) UnmarshalJSON(data []byte) error { + var res map[string]json.RawMessage + if err := json.Unmarshal(data, &res); err != nil { + return err + } + for k, v := range res { + if strings.HasPrefix(strings.ToLower(k), "x-") { + if p.Extensions == nil { + p.Extensions = make(map[string]interface{}) + } + var d interface{} + if err := json.Unmarshal(v, &d); err != nil { + return err + } + p.Extensions[k] = d + } + if strings.HasPrefix(k, "/") { + if p.Paths == nil { + p.Paths = make(map[string]PathItem) + } + var pi PathItem + if err := json.Unmarshal(v, &pi); err != nil { + return err + } + p.Paths[k] = pi + } + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (p Paths) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(p.VendorExtensible) + if err != nil { + return nil, err + } + + pths := make(map[string]PathItem) + for k, v := range p.Paths { + if strings.HasPrefix(k, "/") { + pths[k] = v + } + } + b2, err := json.Marshal(pths) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil +} diff --git a/vendor/github.com/go-openapi/spec/properties.go b/vendor/github.com/go-openapi/spec/properties.go new file mode 100644 index 000000000..2af13787a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/properties.go @@ -0,0 +1,91 @@ +package spec + +import ( + "bytes" + "encoding/json" + "reflect" + "sort" +) + +// OrderSchemaItem holds a named schema (e.g. from a property of an object) +type OrderSchemaItem struct { + Name string + Schema +} + +// OrderSchemaItems is a sortable slice of named schemas. +// The ordering is defined by the x-order schema extension. +type OrderSchemaItems []OrderSchemaItem + +// MarshalJSON produces a json object with keys defined by the name schemas +// of the OrderSchemaItems slice, keeping the original order of the slice. +func (items OrderSchemaItems) MarshalJSON() ([]byte, error) { + buf := bytes.NewBuffer(nil) + buf.WriteString("{") + for i := range items { + if i > 0 { + buf.WriteString(",") + } + buf.WriteString("\"") + buf.WriteString(items[i].Name) + buf.WriteString("\":") + bs, err := json.Marshal(&items[i].Schema) + if err != nil { + return nil, err + } + buf.Write(bs) + } + buf.WriteString("}") + return buf.Bytes(), nil +} + +func (items OrderSchemaItems) Len() int { return len(items) } +func (items OrderSchemaItems) Swap(i, j int) { items[i], items[j] = items[j], items[i] } +func (items OrderSchemaItems) Less(i, j int) (ret bool) { + ii, oki := items[i].Extensions.GetString("x-order") + ij, okj := items[j].Extensions.GetString("x-order") + if oki { + if okj { + defer func() { + if err := recover(); err != nil { + defer func() { + if err = recover(); err != nil { + ret = items[i].Name < items[j].Name + } + }() + ret = reflect.ValueOf(ii).String() < reflect.ValueOf(ij).String() + } + }() + return reflect.ValueOf(ii).Int() < reflect.ValueOf(ij).Int() + } + return true + } else if okj { + return false + } + return items[i].Name < items[j].Name +} + +// SchemaProperties is a map representing the properties of a Schema object. +// It knows how to transform its keys into an ordered slice. +type SchemaProperties map[string]Schema + +// ToOrderedSchemaItems transforms the map of properties into a sortable slice +func (properties SchemaProperties) ToOrderedSchemaItems() OrderSchemaItems { + items := make(OrderSchemaItems, 0, len(properties)) + for k, v := range properties { + items = append(items, OrderSchemaItem{ + Name: k, + Schema: v, + }) + } + sort.Sort(items) + return items +} + +// MarshalJSON produces properties as json, keeping their order. +func (properties SchemaProperties) MarshalJSON() ([]byte, error) { + if properties == nil { + return []byte("null"), nil + } + return json.Marshal(properties.ToOrderedSchemaItems()) +} diff --git a/vendor/github.com/go-openapi/spec/ref.go b/vendor/github.com/go-openapi/spec/ref.go new file mode 100644 index 000000000..b0ef9bd9c --- /dev/null +++ b/vendor/github.com/go-openapi/spec/ref.go @@ -0,0 +1,193 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "bytes" + "encoding/gob" + "encoding/json" + "net/http" + "os" + "path/filepath" + + "github.com/go-openapi/jsonreference" +) + +// Refable is a struct for things that accept a $ref property +type Refable struct { + Ref Ref +} + +// MarshalJSON marshals the ref to json +func (r Refable) MarshalJSON() ([]byte, error) { + return r.Ref.MarshalJSON() +} + +// UnmarshalJSON unmarshalss the ref from json +func (r *Refable) UnmarshalJSON(d []byte) error { + return json.Unmarshal(d, &r.Ref) +} + +// Ref represents a json reference that is potentially resolved +type Ref struct { + jsonreference.Ref +} + +// RemoteURI gets the remote uri part of the ref +func (r *Ref) RemoteURI() string { + if r.String() == "" { + return "" + } + + u := *r.GetURL() + u.Fragment = "" + return u.String() +} + +// IsValidURI returns true when the url the ref points to can be found +func (r *Ref) IsValidURI(basepaths ...string) bool { + if r.String() == "" { + return true + } + + v := r.RemoteURI() + if v == "" { + return true + } + + if r.HasFullURL { + //nolint:noctx,gosec + rr, err := http.Get(v) + if err != nil { + return false + } + defer rr.Body.Close() + + return rr.StatusCode/100 == 2 + } + + if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { + return false + } + + // check for local file + pth := v + if r.HasURLPathOnly { + base := "." + if len(basepaths) > 0 { + base = filepath.Dir(filepath.Join(basepaths...)) + } + p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) + if e != nil { + return false + } + pth = p + } + + fi, err := os.Stat(filepath.ToSlash(pth)) + if err != nil { + return false + } + + return !fi.IsDir() +} + +// Inherits creates a new reference from a parent and a child +// If the child cannot inherit from the parent, an error is returned +func (r *Ref) Inherits(child Ref) (*Ref, error) { + ref, err := r.Ref.Inherits(child.Ref) + if err != nil { + return nil, err + } + return &Ref{Ref: *ref}, nil +} + +// NewRef creates a new instance of a ref object +// returns an error when the reference uri is an invalid uri +func NewRef(refURI string) (Ref, error) { + ref, err := jsonreference.New(refURI) + if err != nil { + return Ref{}, err + } + return Ref{Ref: ref}, nil +} + +// MustCreateRef creates a ref object but panics when refURI is invalid. +// Use the NewRef method for a version that returns an error. +func MustCreateRef(refURI string) Ref { + return Ref{Ref: jsonreference.MustCreateRef(refURI)} +} + +// MarshalJSON marshals this ref into a JSON object +func (r Ref) MarshalJSON() ([]byte, error) { + str := r.String() + if str == "" { + if r.IsRoot() { + return []byte(`{"$ref":""}`), nil + } + return []byte("{}"), nil + } + v := map[string]interface{}{"$ref": str} + return json.Marshal(v) +} + +// UnmarshalJSON unmarshals this ref from a JSON object +func (r *Ref) UnmarshalJSON(d []byte) error { + var v map[string]interface{} + if err := json.Unmarshal(d, &v); err != nil { + return err + } + return r.fromMap(v) +} + +// GobEncode provides a safe gob encoder for Ref +func (r Ref) GobEncode() ([]byte, error) { + var b bytes.Buffer + raw, err := r.MarshalJSON() + if err != nil { + return nil, err + } + err = gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err +} + +// GobDecode provides a safe gob decoder for Ref +func (r *Ref) GobDecode(b []byte) error { + var raw []byte + buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + return json.Unmarshal(raw, r) +} + +func (r *Ref) fromMap(v map[string]interface{}) error { + if v == nil { + return nil + } + + if vv, ok := v["$ref"]; ok { + if str, ok := vv.(string); ok { + ref, err := jsonreference.New(str) + if err != nil { + return err + } + *r = Ref{Ref: ref} + } + } + + return nil +} diff --git a/vendor/github.com/go-openapi/spec/resolver.go b/vendor/github.com/go-openapi/spec/resolver.go new file mode 100644 index 000000000..47d1ee13f --- /dev/null +++ b/vendor/github.com/go-openapi/spec/resolver.go @@ -0,0 +1,127 @@ +package spec + +import ( + "fmt" + + "github.com/go-openapi/swag" +) + +func resolveAnyWithBase(root interface{}, ref *Ref, result interface{}, options *ExpandOptions) error { + options = optionsOrDefault(options) + resolver := defaultSchemaLoader(root, options, nil, nil) + + if err := resolver.Resolve(ref, result, options.RelativeBase); err != nil { + return err + } + + return nil +} + +// ResolveRefWithBase resolves a reference against a context root with preservation of base path +func ResolveRefWithBase(root interface{}, ref *Ref, options *ExpandOptions) (*Schema, error) { + result := new(Schema) + + if err := resolveAnyWithBase(root, ref, result, options); err != nil { + return nil, err + } + + return result, nil +} + +// ResolveRef resolves a reference for a schema against a context root +// ref is guaranteed to be in root (no need to go to external files) +// +// ResolveRef is ONLY called from the code generation module +func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { + res, _, err := ref.GetPointer().Get(root) + if err != nil { + return nil, err + } + + switch sch := res.(type) { + case Schema: + return &sch, nil + case *Schema: + return sch, nil + case map[string]interface{}: + newSch := new(Schema) + if err = swag.DynamicJSONToStruct(sch, newSch); err != nil { + return nil, err + } + return newSch, nil + default: + return nil, fmt.Errorf("type: %T: %w", sch, ErrUnknownTypeForReference) + } +} + +// ResolveParameterWithBase resolves a parameter reference against a context root and base path +func ResolveParameterWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Parameter, error) { + result := new(Parameter) + + if err := resolveAnyWithBase(root, &ref, result, options); err != nil { + return nil, err + } + + return result, nil +} + +// ResolveParameter resolves a parameter reference against a context root +func ResolveParameter(root interface{}, ref Ref) (*Parameter, error) { + return ResolveParameterWithBase(root, ref, nil) +} + +// ResolveResponseWithBase resolves response a reference against a context root and base path +func ResolveResponseWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Response, error) { + result := new(Response) + + err := resolveAnyWithBase(root, &ref, result, options) + if err != nil { + return nil, err + } + + return result, nil +} + +// ResolveResponse resolves response a reference against a context root +func ResolveResponse(root interface{}, ref Ref) (*Response, error) { + return ResolveResponseWithBase(root, ref, nil) +} + +// ResolvePathItemWithBase resolves response a path item against a context root and base path +func ResolvePathItemWithBase(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) { + result := new(PathItem) + + if err := resolveAnyWithBase(root, &ref, result, options); err != nil { + return nil, err + } + + return result, nil +} + +// ResolvePathItem resolves response a path item against a context root and base path +// +// Deprecated: use ResolvePathItemWithBase instead +func ResolvePathItem(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) { + return ResolvePathItemWithBase(root, ref, options) +} + +// ResolveItemsWithBase resolves parameter items reference against a context root and base path. +// +// NOTE: stricly speaking, this construct is not supported by Swagger 2.0. +// Similarly, $ref are forbidden in response headers. +func ResolveItemsWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) { + result := new(Items) + + if err := resolveAnyWithBase(root, &ref, result, options); err != nil { + return nil, err + } + + return result, nil +} + +// ResolveItems resolves parameter items reference against a context root and base path. +// +// Deprecated: use ResolveItemsWithBase instead +func ResolveItems(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) { + return ResolveItemsWithBase(root, ref, options) +} diff --git a/vendor/github.com/go-openapi/spec/response.go b/vendor/github.com/go-openapi/spec/response.go new file mode 100644 index 000000000..0340b60d8 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/response.go @@ -0,0 +1,152 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// ResponseProps properties specific to a response +type ResponseProps struct { + Description string `json:"description"` + Schema *Schema `json:"schema,omitempty"` + Headers map[string]Header `json:"headers,omitempty"` + Examples map[string]interface{} `json:"examples,omitempty"` +} + +// Response describes a single response from an API Operation. +// +// For more information: http://goo.gl/8us55a#responseObject +type Response struct { + Refable + ResponseProps + VendorExtensible +} + +// JSONLookup look up a value by the json property name +func (r Response) JSONLookup(token string) (interface{}, error) { + if ex, ok := r.Extensions[token]; ok { + return &ex, nil + } + if token == "$ref" { + return &r.Ref, nil + } + ptr, _, err := jsonpointer.GetForToken(r.ResponseProps, token) + return ptr, err +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (r *Response) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &r.ResponseProps); err != nil { + return err + } + if err := json.Unmarshal(data, &r.Refable); err != nil { + return err + } + return json.Unmarshal(data, &r.VendorExtensible) +} + +// MarshalJSON converts this items object to JSON +func (r Response) MarshalJSON() ([]byte, error) { + var ( + b1 []byte + err error + ) + + if r.Ref.String() == "" { + // when there is no $ref, empty description is rendered as an empty string + b1, err = json.Marshal(r.ResponseProps) + } else { + // when there is $ref inside the schema, description should be omitempty-ied + b1, err = json.Marshal(struct { + Description string `json:"description,omitempty"` + Schema *Schema `json:"schema,omitempty"` + Headers map[string]Header `json:"headers,omitempty"` + Examples map[string]interface{} `json:"examples,omitempty"` + }{ + Description: r.ResponseProps.Description, + Schema: r.ResponseProps.Schema, + Examples: r.ResponseProps.Examples, + }) + } + if err != nil { + return nil, err + } + + b2, err := json.Marshal(r.Refable) + if err != nil { + return nil, err + } + b3, err := json.Marshal(r.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2, b3), nil +} + +// NewResponse creates a new response instance +func NewResponse() *Response { + return new(Response) +} + +// ResponseRef creates a response as a json reference +func ResponseRef(url string) *Response { + resp := NewResponse() + resp.Ref = MustCreateRef(url) + return resp +} + +// WithDescription sets the description on this response, allows for chaining +func (r *Response) WithDescription(description string) *Response { + r.Description = description + return r +} + +// WithSchema sets the schema on this response, allows for chaining. +// Passing a nil argument removes the schema from this response +func (r *Response) WithSchema(schema *Schema) *Response { + r.Schema = schema + return r +} + +// AddHeader adds a header to this response +func (r *Response) AddHeader(name string, header *Header) *Response { + if header == nil { + return r.RemoveHeader(name) + } + if r.Headers == nil { + r.Headers = make(map[string]Header) + } + r.Headers[name] = *header + return r +} + +// RemoveHeader removes a header from this response +func (r *Response) RemoveHeader(name string) *Response { + delete(r.Headers, name) + return r +} + +// AddExample adds an example to this response +func (r *Response) AddExample(mediaType string, example interface{}) *Response { + if r.Examples == nil { + r.Examples = make(map[string]interface{}) + } + r.Examples[mediaType] = example + return r +} diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go new file mode 100644 index 000000000..4efb6f868 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/responses.go @@ -0,0 +1,127 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" + + "github.com/go-openapi/swag" +) + +// Responses is a container for the expected responses of an operation. +// The container maps a HTTP response code to the expected response. +// It is not expected from the documentation to necessarily cover all possible HTTP response codes, +// since they may not be known in advance. However, it is expected from the documentation to cover +// a successful operation response and any known errors. +// +// The `default` can be used a default response object for all HTTP codes that are not covered +// individually by the specification. +// +// The `Responses Object` MUST contain at least one response code, and it SHOULD be the response +// for a successful operation call. +// +// For more information: http://goo.gl/8us55a#responsesObject +type Responses struct { + VendorExtensible + ResponsesProps +} + +// JSONLookup implements an interface to customize json pointer lookup +func (r Responses) JSONLookup(token string) (interface{}, error) { + if token == "default" { + return r.Default, nil + } + if ex, ok := r.Extensions[token]; ok { + return &ex, nil + } + if i, err := strconv.Atoi(token); err == nil { + if scr, ok := r.StatusCodeResponses[i]; ok { + return scr, nil + } + } + return nil, fmt.Errorf("object has no field %q", token) +} + +// UnmarshalJSON hydrates this items instance with the data from JSON +func (r *Responses) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { + return err + } + if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { + return err + } + if reflect.DeepEqual(ResponsesProps{}, r.ResponsesProps) { + r.ResponsesProps = ResponsesProps{} + } + return nil +} + +// MarshalJSON converts this items object to JSON +func (r Responses) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(r.ResponsesProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(r.VendorExtensible) + if err != nil { + return nil, err + } + concated := swag.ConcatJSON(b1, b2) + return concated, nil +} + +// ResponsesProps describes all responses for an operation. +// It tells what is the default response and maps all responses with a +// HTTP status code. +type ResponsesProps struct { + Default *Response + StatusCodeResponses map[int]Response +} + +// MarshalJSON marshals responses as JSON +func (r ResponsesProps) MarshalJSON() ([]byte, error) { + toser := map[string]Response{} + if r.Default != nil { + toser["default"] = *r.Default + } + for k, v := range r.StatusCodeResponses { + toser[strconv.Itoa(k)] = v + } + return json.Marshal(toser) +} + +// UnmarshalJSON unmarshals responses from JSON +func (r *ResponsesProps) UnmarshalJSON(data []byte) error { + var res map[string]Response + if err := json.Unmarshal(data, &res); err != nil { + return nil + } + if v, ok := res["default"]; ok { + r.Default = &v + delete(res, "default") + } + for k, v := range res { + if nk, err := strconv.Atoi(k); err == nil { + if r.StatusCodeResponses == nil { + r.StatusCodeResponses = map[int]Response{} + } + r.StatusCodeResponses[nk] = v + } + } + return nil +} diff --git a/vendor/github.com/go-openapi/spec/schema.go b/vendor/github.com/go-openapi/spec/schema.go new file mode 100644 index 000000000..a8d0f737a --- /dev/null +++ b/vendor/github.com/go-openapi/spec/schema.go @@ -0,0 +1,646 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "fmt" + "net/url" + "strings" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// BooleanProperty creates a boolean property +func BooleanProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} +} + +// BoolProperty creates a boolean property +func BoolProperty() *Schema { return BooleanProperty() } + +// StringProperty creates a string property +func StringProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} +} + +// CharProperty creates a string property +func CharProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} +} + +// Float64Property creates a float64/double property +func Float64Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} +} + +// Float32Property creates a float32/float property +func Float32Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} +} + +// Int8Property creates an int8 property +func Int8Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} +} + +// Int16Property creates an int16 property +func Int16Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} +} + +// Int32Property creates an int32 property +func Int32Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} +} + +// Int64Property creates an int64 property +func Int64Property() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} +} + +// StrFmtProperty creates a property for the named string format +func StrFmtProperty(format string) *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} +} + +// DateProperty creates a date property +func DateProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} +} + +// DateTimeProperty creates a date time property +func DateTimeProperty() *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} +} + +// MapProperty creates a map property +func MapProperty(property *Schema) *Schema { + return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, + AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} +} + +// RefProperty creates a ref property +func RefProperty(name string) *Schema { + return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} +} + +// RefSchema creates a ref property +func RefSchema(name string) *Schema { + return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} +} + +// ArrayProperty creates an array property +func ArrayProperty(items *Schema) *Schema { + if items == nil { + return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} + } + return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} +} + +// ComposedSchema creates a schema with allOf +func ComposedSchema(schemas ...Schema) *Schema { + s := new(Schema) + s.AllOf = schemas + return s +} + +// SchemaURL represents a schema url +type SchemaURL string + +// MarshalJSON marshal this to JSON +func (r SchemaURL) MarshalJSON() ([]byte, error) { + if r == "" { + return []byte("{}"), nil + } + v := map[string]interface{}{"$schema": string(r)} + return json.Marshal(v) +} + +// UnmarshalJSON unmarshal this from JSON +func (r *SchemaURL) UnmarshalJSON(data []byte) error { + var v map[string]interface{} + if err := json.Unmarshal(data, &v); err != nil { + return err + } + return r.fromMap(v) +} + +func (r *SchemaURL) fromMap(v map[string]interface{}) error { + if v == nil { + return nil + } + if vv, ok := v["$schema"]; ok { + if str, ok := vv.(string); ok { + u, err := url.Parse(str) + if err != nil { + return err + } + + *r = SchemaURL(u.String()) + } + } + return nil +} + +// SchemaProps describes a JSON schema (draft 4) +type SchemaProps struct { + ID string `json:"id,omitempty"` + Ref Ref `json:"-"` + Schema SchemaURL `json:"-"` + Description string `json:"description,omitempty"` + Type StringOrArray `json:"type,omitempty"` + Nullable bool `json:"nullable,omitempty"` + Format string `json:"format,omitempty"` + Title string `json:"title,omitempty"` + Default interface{} `json:"default,omitempty"` + Maximum *float64 `json:"maximum,omitempty"` + ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` + Minimum *float64 `json:"minimum,omitempty"` + ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` + MaxLength *int64 `json:"maxLength,omitempty"` + MinLength *int64 `json:"minLength,omitempty"` + Pattern string `json:"pattern,omitempty"` + MaxItems *int64 `json:"maxItems,omitempty"` + MinItems *int64 `json:"minItems,omitempty"` + UniqueItems bool `json:"uniqueItems,omitempty"` + MultipleOf *float64 `json:"multipleOf,omitempty"` + Enum []interface{} `json:"enum,omitempty"` + MaxProperties *int64 `json:"maxProperties,omitempty"` + MinProperties *int64 `json:"minProperties,omitempty"` + Required []string `json:"required,omitempty"` + Items *SchemaOrArray `json:"items,omitempty"` + AllOf []Schema `json:"allOf,omitempty"` + OneOf []Schema `json:"oneOf,omitempty"` + AnyOf []Schema `json:"anyOf,omitempty"` + Not *Schema `json:"not,omitempty"` + Properties SchemaProperties `json:"properties,omitempty"` + AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` + PatternProperties SchemaProperties `json:"patternProperties,omitempty"` + Dependencies Dependencies `json:"dependencies,omitempty"` + AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` + Definitions Definitions `json:"definitions,omitempty"` +} + +// SwaggerSchemaProps are additional properties supported by swagger schemas, but not JSON-schema (draft 4) +type SwaggerSchemaProps struct { + Discriminator string `json:"discriminator,omitempty"` + ReadOnly bool `json:"readOnly,omitempty"` + XML *XMLObject `json:"xml,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` + Example interface{} `json:"example,omitempty"` +} + +// Schema the schema object allows the definition of input and output data types. +// These types can be objects, but also primitives and arrays. +// This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) +// and uses a predefined subset of it. +// On top of this subset, there are extensions provided by this specification to allow for more complete documentation. +// +// For more information: http://goo.gl/8us55a#schemaObject +type Schema struct { + VendorExtensible + SchemaProps + SwaggerSchemaProps + ExtraProps map[string]interface{} `json:"-"` +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s Schema) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } + + if ex, ok := s.ExtraProps[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(s.SchemaProps, token) + if r != nil || (err != nil && !strings.HasPrefix(err.Error(), "object has no field")) { + return r, err + } + r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token) + return r, err +} + +// WithID sets the id for this schema, allows for chaining +func (s *Schema) WithID(id string) *Schema { + s.ID = id + return s +} + +// WithTitle sets the title for this schema, allows for chaining +func (s *Schema) WithTitle(title string) *Schema { + s.Title = title + return s +} + +// WithDescription sets the description for this schema, allows for chaining +func (s *Schema) WithDescription(description string) *Schema { + s.Description = description + return s +} + +// WithProperties sets the properties for this schema +func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { + s.Properties = schemas + return s +} + +// SetProperty sets a property on this schema +func (s *Schema) SetProperty(name string, schema Schema) *Schema { + if s.Properties == nil { + s.Properties = make(map[string]Schema) + } + s.Properties[name] = schema + return s +} + +// WithAllOf sets the all of property +func (s *Schema) WithAllOf(schemas ...Schema) *Schema { + s.AllOf = schemas + return s +} + +// WithMaxProperties sets the max number of properties an object can have +func (s *Schema) WithMaxProperties(max int64) *Schema { + s.MaxProperties = &max + return s +} + +// WithMinProperties sets the min number of properties an object must have +func (s *Schema) WithMinProperties(min int64) *Schema { + s.MinProperties = &min + return s +} + +// Typed sets the type of this schema for a single value item +func (s *Schema) Typed(tpe, format string) *Schema { + s.Type = []string{tpe} + s.Format = format + return s +} + +// AddType adds a type with potential format to the types for this schema +func (s *Schema) AddType(tpe, format string) *Schema { + s.Type = append(s.Type, tpe) + if format != "" { + s.Format = format + } + return s +} + +// AsNullable flags this schema as nullable. +func (s *Schema) AsNullable() *Schema { + s.Nullable = true + return s +} + +// CollectionOf a fluent builder method for an array parameter +func (s *Schema) CollectionOf(items Schema) *Schema { + s.Type = []string{jsonArray} + s.Items = &SchemaOrArray{Schema: &items} + return s +} + +// WithDefault sets the default value on this parameter +func (s *Schema) WithDefault(defaultValue interface{}) *Schema { + s.Default = defaultValue + return s +} + +// WithRequired flags this parameter as required +func (s *Schema) WithRequired(items ...string) *Schema { + s.Required = items + return s +} + +// AddRequired adds field names to the required properties array +func (s *Schema) AddRequired(items ...string) *Schema { + s.Required = append(s.Required, items...) + return s +} + +// WithMaxLength sets a max length value +func (s *Schema) WithMaxLength(max int64) *Schema { + s.MaxLength = &max + return s +} + +// WithMinLength sets a min length value +func (s *Schema) WithMinLength(min int64) *Schema { + s.MinLength = &min + return s +} + +// WithPattern sets a pattern value +func (s *Schema) WithPattern(pattern string) *Schema { + s.Pattern = pattern + return s +} + +// WithMultipleOf sets a multiple of value +func (s *Schema) WithMultipleOf(number float64) *Schema { + s.MultipleOf = &number + return s +} + +// WithMaximum sets a maximum number value +func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema { + s.Maximum = &max + s.ExclusiveMaximum = exclusive + return s +} + +// WithMinimum sets a minimum number value +func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema { + s.Minimum = &min + s.ExclusiveMinimum = exclusive + return s +} + +// WithEnum sets a the enum values (replace) +func (s *Schema) WithEnum(values ...interface{}) *Schema { + s.Enum = append([]interface{}{}, values...) + return s +} + +// WithMaxItems sets the max items +func (s *Schema) WithMaxItems(size int64) *Schema { + s.MaxItems = &size + return s +} + +// WithMinItems sets the min items +func (s *Schema) WithMinItems(size int64) *Schema { + s.MinItems = &size + return s +} + +// UniqueValues dictates that this array can only have unique items +func (s *Schema) UniqueValues() *Schema { + s.UniqueItems = true + return s +} + +// AllowDuplicates this array can have duplicates +func (s *Schema) AllowDuplicates() *Schema { + s.UniqueItems = false + return s +} + +// AddToAllOf adds a schema to the allOf property +func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { + s.AllOf = append(s.AllOf, schemas...) + return s +} + +// WithDiscriminator sets the name of the discriminator field +func (s *Schema) WithDiscriminator(discriminator string) *Schema { + s.Discriminator = discriminator + return s +} + +// AsReadOnly flags this schema as readonly +func (s *Schema) AsReadOnly() *Schema { + s.ReadOnly = true + return s +} + +// AsWritable flags this schema as writeable (not read-only) +func (s *Schema) AsWritable() *Schema { + s.ReadOnly = false + return s +} + +// WithExample sets the example for this schema +func (s *Schema) WithExample(example interface{}) *Schema { + s.Example = example + return s +} + +// WithExternalDocs sets/removes the external docs for/from this schema. +// When you pass empty strings as params the external documents will be removed. +// When you pass non-empty string as one value then those values will be used on the external docs object. +// So when you pass a non-empty description, you should also pass the url and vice versa. +func (s *Schema) WithExternalDocs(description, url string) *Schema { + if description == "" && url == "" { + s.ExternalDocs = nil + return s + } + + if s.ExternalDocs == nil { + s.ExternalDocs = &ExternalDocumentation{} + } + s.ExternalDocs.Description = description + s.ExternalDocs.URL = url + return s +} + +// WithXMLName sets the xml name for the object +func (s *Schema) WithXMLName(name string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Name = name + return s +} + +// WithXMLNamespace sets the xml namespace for the object +func (s *Schema) WithXMLNamespace(namespace string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Namespace = namespace + return s +} + +// WithXMLPrefix sets the xml prefix for the object +func (s *Schema) WithXMLPrefix(prefix string) *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Prefix = prefix + return s +} + +// AsXMLAttribute flags this object as xml attribute +func (s *Schema) AsXMLAttribute() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Attribute = true + return s +} + +// AsXMLElement flags this object as an xml node +func (s *Schema) AsXMLElement() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Attribute = false + return s +} + +// AsWrappedXML flags this object as wrapped, this is mostly useful for array types +func (s *Schema) AsWrappedXML() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Wrapped = true + return s +} + +// AsUnwrappedXML flags this object as an xml node +func (s *Schema) AsUnwrappedXML() *Schema { + if s.XML == nil { + s.XML = new(XMLObject) + } + s.XML.Wrapped = false + return s +} + +// SetValidations defines all schema validations. +// +// NOTE: Required, ReadOnly, AllOf, AnyOf, OneOf and Not are not considered. +func (s *Schema) SetValidations(val SchemaValidations) { + s.Maximum = val.Maximum + s.ExclusiveMaximum = val.ExclusiveMaximum + s.Minimum = val.Minimum + s.ExclusiveMinimum = val.ExclusiveMinimum + s.MaxLength = val.MaxLength + s.MinLength = val.MinLength + s.Pattern = val.Pattern + s.MaxItems = val.MaxItems + s.MinItems = val.MinItems + s.UniqueItems = val.UniqueItems + s.MultipleOf = val.MultipleOf + s.Enum = val.Enum + s.MinProperties = val.MinProperties + s.MaxProperties = val.MaxProperties + s.PatternProperties = val.PatternProperties +} + +// WithValidations is a fluent method to set schema validations +func (s *Schema) WithValidations(val SchemaValidations) *Schema { + s.SetValidations(val) + return s +} + +// Validations returns a clone of the validations for this schema +func (s Schema) Validations() SchemaValidations { + return SchemaValidations{ + CommonValidations: CommonValidations{ + Maximum: s.Maximum, + ExclusiveMaximum: s.ExclusiveMaximum, + Minimum: s.Minimum, + ExclusiveMinimum: s.ExclusiveMinimum, + MaxLength: s.MaxLength, + MinLength: s.MinLength, + Pattern: s.Pattern, + MaxItems: s.MaxItems, + MinItems: s.MinItems, + UniqueItems: s.UniqueItems, + MultipleOf: s.MultipleOf, + Enum: s.Enum, + }, + MinProperties: s.MinProperties, + MaxProperties: s.MaxProperties, + PatternProperties: s.PatternProperties, + } +} + +// MarshalJSON marshal this to JSON +func (s Schema) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(s.SchemaProps) + if err != nil { + return nil, fmt.Errorf("schema props %v", err) + } + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, fmt.Errorf("vendor props %v", err) + } + b3, err := s.Ref.MarshalJSON() + if err != nil { + return nil, fmt.Errorf("ref prop %v", err) + } + b4, err := s.Schema.MarshalJSON() + if err != nil { + return nil, fmt.Errorf("schema prop %v", err) + } + b5, err := json.Marshal(s.SwaggerSchemaProps) + if err != nil { + return nil, fmt.Errorf("common validations %v", err) + } + var b6 []byte + if s.ExtraProps != nil { + jj, err := json.Marshal(s.ExtraProps) + if err != nil { + return nil, fmt.Errorf("extra props %v", err) + } + b6 = jj + } + return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil +} + +// UnmarshalJSON marshal this from JSON +func (s *Schema) UnmarshalJSON(data []byte) error { + props := struct { + SchemaProps + SwaggerSchemaProps + }{} + if err := json.Unmarshal(data, &props); err != nil { + return err + } + + sch := Schema{ + SchemaProps: props.SchemaProps, + SwaggerSchemaProps: props.SwaggerSchemaProps, + } + + var d map[string]interface{} + if err := json.Unmarshal(data, &d); err != nil { + return err + } + + _ = sch.Ref.fromMap(d) + _ = sch.Schema.fromMap(d) + + delete(d, "$ref") + delete(d, "$schema") + for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { + delete(d, pn) + } + + for k, vv := range d { + lk := strings.ToLower(k) + if strings.HasPrefix(lk, "x-") { + if sch.Extensions == nil { + sch.Extensions = map[string]interface{}{} + } + sch.Extensions[k] = vv + continue + } + if sch.ExtraProps == nil { + sch.ExtraProps = map[string]interface{}{} + } + sch.ExtraProps[k] = vv + } + + *s = sch + + return nil +} diff --git a/vendor/github.com/go-openapi/spec/schema_loader.go b/vendor/github.com/go-openapi/spec/schema_loader.go new file mode 100644 index 000000000..b81175afd --- /dev/null +++ b/vendor/github.com/go-openapi/spec/schema_loader.go @@ -0,0 +1,338 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + "fmt" + "log" + "net/url" + "reflect" + "strings" + + "github.com/go-openapi/swag" +) + +// PathLoader is a function to use when loading remote refs. +// +// This is a package level default. It may be overridden or bypassed by +// specifying the loader in ExpandOptions. +// +// NOTE: if you are using the go-openapi/loads package, it will override +// this value with its own default (a loader to retrieve YAML documents as +// well as JSON ones). +var PathLoader = func(pth string) (json.RawMessage, error) { + data, err := swag.LoadFromFileOrHTTP(pth) + if err != nil { + return nil, err + } + return json.RawMessage(data), nil +} + +// resolverContext allows to share a context during spec processing. +// At the moment, it just holds the index of circular references found. +type resolverContext struct { + // circulars holds all visited circular references, to shortcircuit $ref resolution. + // + // This structure is privately instantiated and needs not be locked against + // concurrent access, unless we chose to implement a parallel spec walking. + circulars map[string]bool + basePath string + loadDoc func(string) (json.RawMessage, error) + rootID string +} + +func newResolverContext(options *ExpandOptions) *resolverContext { + expandOptions := optionsOrDefault(options) + + // path loader may be overridden by options + var loader func(string) (json.RawMessage, error) + if expandOptions.PathLoader == nil { + loader = PathLoader + } else { + loader = expandOptions.PathLoader + } + + return &resolverContext{ + circulars: make(map[string]bool), + basePath: expandOptions.RelativeBase, // keep the root base path in context + loadDoc: loader, + } +} + +type schemaLoader struct { + root interface{} + options *ExpandOptions + cache ResolutionCache + context *resolverContext +} + +func (r *schemaLoader) transitiveResolver(basePath string, ref Ref) *schemaLoader { + if ref.IsRoot() || ref.HasFragmentOnly { + return r + } + + baseRef := MustCreateRef(basePath) + currentRef := normalizeRef(&ref, basePath) + if strings.HasPrefix(currentRef.String(), baseRef.String()) { + return r + } + + // set a new root against which to resolve + rootURL := currentRef.GetURL() + rootURL.Fragment = "" + root, _ := r.cache.Get(rootURL.String()) + + // shallow copy of resolver options to set a new RelativeBase when + // traversing multiple documents + newOptions := r.options + newOptions.RelativeBase = rootURL.String() + + return defaultSchemaLoader(root, newOptions, r.cache, r.context) +} + +func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string) string { + if transitive != r { + if transitive.options != nil && transitive.options.RelativeBase != "" { + return normalizeBase(transitive.options.RelativeBase) + } + } + + return basePath +} + +func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error { + tgt := reflect.ValueOf(target) + if tgt.Kind() != reflect.Ptr { + return ErrResolveRefNeedsAPointer + } + + if ref.GetURL() == nil { + return nil + } + + var ( + res interface{} + data interface{} + err error + ) + + // Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means + // it is pointing somewhere in the root. + root := r.root + if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" { + if baseRef, erb := NewRef(basePath); erb == nil { + root, _, _, _ = r.load(baseRef.GetURL()) + } + } + + if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil { + data = root + } else { + baseRef := normalizeRef(ref, basePath) + data, _, _, err = r.load(baseRef.GetURL()) + if err != nil { + return err + } + } + + res = data + if ref.String() != "" { + res, _, err = ref.GetPointer().Get(data) + if err != nil { + return err + } + } + return swag.DynamicJSONToStruct(res, target) +} + +func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) { + debugLog("loading schema from url: %s", refURL) + toFetch := *refURL + toFetch.Fragment = "" + + var err error + pth := toFetch.String() + normalized := normalizeBase(pth) + debugLog("loading doc from: %s", normalized) + + unescaped, err := url.PathUnescape(normalized) + if err != nil { + return nil, url.URL{}, false, err + } + + u := url.URL{Path: unescaped} + + data, fromCache := r.cache.Get(u.RequestURI()) + if fromCache { + return data, toFetch, fromCache, nil + } + + b, err := r.context.loadDoc(normalized) + if err != nil { + return nil, url.URL{}, false, err + } + + var doc interface{} + if err := json.Unmarshal(b, &doc); err != nil { + return nil, url.URL{}, false, err + } + r.cache.Set(normalized, doc) + + return doc, toFetch, fromCache, nil +} + +// isCircular detects cycles in sequences of $ref. +// +// It relies on a private context (which needs not be locked). +func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) { + normalizedRef := normalizeURI(ref.String(), basePath) + if _, ok := r.context.circulars[normalizedRef]; ok { + // circular $ref has been already detected in another explored cycle + foundCycle = true + return + } + foundCycle = swag.ContainsStrings(parentRefs, normalizedRef) // normalized windows url's are lower cased + if foundCycle { + r.context.circulars[normalizedRef] = true + } + return +} + +// Resolve resolves a reference against basePath and stores the result in target. +// +// Resolve is not in charge of following references: it only resolves ref by following its URL. +// +// If the schema the ref is referring to holds nested refs, Resolve doesn't resolve them. +// +// If basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct +func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error { + return r.resolveRef(ref, target, basePath) +} + +func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error { + var ref *Ref + switch refable := input.(type) { + case *Schema: + ref = &refable.Ref + case *Parameter: + ref = &refable.Ref + case *Response: + ref = &refable.Ref + case *PathItem: + ref = &refable.Ref + default: + return fmt.Errorf("unsupported type: %T: %w", input, ErrDerefUnsupportedType) + } + + curRef := ref.String() + if curRef == "" { + return nil + } + + normalizedRef := normalizeRef(ref, basePath) + normalizedBasePath := normalizedRef.RemoteURI() + + if r.isCircular(normalizedRef, basePath, parentRefs...) { + return nil + } + + if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) { + return err + } + + if ref.String() == "" || ref.String() == curRef { + // done with rereferencing + return nil + } + + parentRefs = append(parentRefs, normalizedRef.String()) + return r.deref(input, parentRefs, normalizedBasePath) +} + +func (r *schemaLoader) shouldStopOnError(err error) bool { + if err != nil && !r.options.ContinueOnError { + return true + } + + if err != nil { + log.Println(err) + } + + return false +} + +func (r *schemaLoader) setSchemaID(target interface{}, id, basePath string) (string, string) { + debugLog("schema has ID: %s", id) + + // handling the case when id is a folder + // remember that basePath has to point to a file + var refPath string + if strings.HasSuffix(id, "/") { + // ensure this is detected as a file, not a folder + refPath = fmt.Sprintf("%s%s", id, "placeholder.json") + } else { + refPath = id + } + + // updates the current base path + // * important: ID can be a relative path + // * registers target to be fetchable from the new base proposed by this id + newBasePath := normalizeURI(refPath, basePath) + + // store found IDs for possible future reuse in $ref + r.cache.Set(newBasePath, target) + + // the root document has an ID: all $ref relative to that ID may + // be rebased relative to the root document + if basePath == r.context.basePath { + debugLog("root document is a schema with ID: %s (normalized as:%s)", id, newBasePath) + r.context.rootID = newBasePath + } + + return newBasePath, refPath +} + +func defaultSchemaLoader( + root interface{}, + expandOptions *ExpandOptions, + cache ResolutionCache, + context *resolverContext) *schemaLoader { + + if expandOptions == nil { + expandOptions = &ExpandOptions{} + } + + cache = cacheOrDefault(cache) + + if expandOptions.RelativeBase == "" { + // if no relative base is provided, assume the root document + // contains all $ref, or at least, that the relative documents + // may be resolved from the current working directory. + expandOptions.RelativeBase = baseForRoot(root, cache) + } + debugLog("effective expander options: %#v", expandOptions) + + if context == nil { + context = newResolverContext(expandOptions) + } + + return &schemaLoader{ + root: root, + options: expandOptions, + cache: cache, + context: context, + } +} diff --git a/vendor/github.com/go-openapi/spec/security_scheme.go b/vendor/github.com/go-openapi/spec/security_scheme.go new file mode 100644 index 000000000..9d0bdae90 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/security_scheme.go @@ -0,0 +1,170 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +const ( + basic = "basic" + apiKey = "apiKey" + oauth2 = "oauth2" + implicit = "implicit" + password = "password" + application = "application" + accessCode = "accessCode" +) + +// BasicAuth creates a basic auth security scheme +func BasicAuth() *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: basic}} +} + +// APIKeyAuth creates an api key auth security scheme +func APIKeyAuth(fieldName, valueSource string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: apiKey, Name: fieldName, In: valueSource}} +} + +// OAuth2Implicit creates an implicit flow oauth2 security scheme +func OAuth2Implicit(authorizationURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: implicit, + AuthorizationURL: authorizationURL, + }} +} + +// OAuth2Password creates a password flow oauth2 security scheme +func OAuth2Password(tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: password, + TokenURL: tokenURL, + }} +} + +// OAuth2Application creates an application flow oauth2 security scheme +func OAuth2Application(tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: application, + TokenURL: tokenURL, + }} +} + +// OAuth2AccessToken creates an access token flow oauth2 security scheme +func OAuth2AccessToken(authorizationURL, tokenURL string) *SecurityScheme { + return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ + Type: oauth2, + Flow: accessCode, + AuthorizationURL: authorizationURL, + TokenURL: tokenURL, + }} +} + +// SecuritySchemeProps describes a swagger security scheme in the securityDefinitions section +type SecuritySchemeProps struct { + Description string `json:"description,omitempty"` + Type string `json:"type"` + Name string `json:"name,omitempty"` // api key + In string `json:"in,omitempty"` // api key + Flow string `json:"flow,omitempty"` // oauth2 + AuthorizationURL string `json:"authorizationUrl"` // oauth2 + TokenURL string `json:"tokenUrl,omitempty"` // oauth2 + Scopes map[string]string `json:"scopes,omitempty"` // oauth2 +} + +// AddScope adds a scope to this security scheme +func (s *SecuritySchemeProps) AddScope(scope, description string) { + if s.Scopes == nil { + s.Scopes = make(map[string]string) + } + s.Scopes[scope] = description +} + +// SecurityScheme allows the definition of a security scheme that can be used by the operations. +// Supported schemes are basic authentication, an API key (either as a header or as a query parameter) +// and OAuth2's common flows (implicit, password, application and access code). +// +// For more information: http://goo.gl/8us55a#securitySchemeObject +type SecurityScheme struct { + VendorExtensible + SecuritySchemeProps +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SecurityScheme) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(s.SecuritySchemeProps, token) + return r, err +} + +// MarshalJSON marshal this to JSON +func (s SecurityScheme) MarshalJSON() ([]byte, error) { + var ( + b1 []byte + err error + ) + + if s.Type == oauth2 && (s.Flow == "implicit" || s.Flow == "accessCode") { + // when oauth2 for implicit or accessCode flows, empty AuthorizationURL is added as empty string + b1, err = json.Marshal(s.SecuritySchemeProps) + } else { + // when not oauth2, empty AuthorizationURL should be omitted + b1, err = json.Marshal(struct { + Description string `json:"description,omitempty"` + Type string `json:"type"` + Name string `json:"name,omitempty"` // api key + In string `json:"in,omitempty"` // api key + Flow string `json:"flow,omitempty"` // oauth2 + AuthorizationURL string `json:"authorizationUrl,omitempty"` // oauth2 + TokenURL string `json:"tokenUrl,omitempty"` // oauth2 + Scopes map[string]string `json:"scopes,omitempty"` // oauth2 + }{ + Description: s.Description, + Type: s.Type, + Name: s.Name, + In: s.In, + Flow: s.Flow, + AuthorizationURL: s.AuthorizationURL, + TokenURL: s.TokenURL, + Scopes: s.Scopes, + }) + } + if err != nil { + return nil, err + } + + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON marshal this from JSON +func (s *SecurityScheme) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { + return err + } + return json.Unmarshal(data, &s.VendorExtensible) +} diff --git a/vendor/github.com/go-openapi/spec/spec.go b/vendor/github.com/go-openapi/spec/spec.go new file mode 100644 index 000000000..7d38b6e62 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/spec.go @@ -0,0 +1,78 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" +) + +//go:generate curl -L --progress -o ./schemas/v2/schema.json http://swagger.io/v2/schema.json +//go:generate curl -L --progress -o ./schemas/jsonschema-draft-04.json http://json-schema.org/draft-04/schema +//go:generate go-bindata -pkg=spec -prefix=./schemas -ignore=.*\.md ./schemas/... +//go:generate perl -pi -e s,Json,JSON,g bindata.go + +const ( + // SwaggerSchemaURL the url for the swagger 2.0 schema to validate specs + SwaggerSchemaURL = "http://swagger.io/v2/schema.json#" + // JSONSchemaURL the url for the json schema schema + JSONSchemaURL = "http://json-schema.org/draft-04/schema#" +) + +// MustLoadJSONSchemaDraft04 panics when Swagger20Schema returns an error +func MustLoadJSONSchemaDraft04() *Schema { + d, e := JSONSchemaDraft04() + if e != nil { + panic(e) + } + return d +} + +// JSONSchemaDraft04 loads the json schema document for json shema draft04 +func JSONSchemaDraft04() (*Schema, error) { + b, err := Asset("jsonschema-draft-04.json") + if err != nil { + return nil, err + } + + schema := new(Schema) + if err := json.Unmarshal(b, schema); err != nil { + return nil, err + } + return schema, nil +} + +// MustLoadSwagger20Schema panics when Swagger20Schema returns an error +func MustLoadSwagger20Schema() *Schema { + d, e := Swagger20Schema() + if e != nil { + panic(e) + } + return d +} + +// Swagger20Schema loads the swagger 2.0 schema from the embedded assets +func Swagger20Schema() (*Schema, error) { + + b, err := Asset("v2/schema.json") + if err != nil { + return nil, err + } + + schema := new(Schema) + if err := json.Unmarshal(b, schema); err != nil { + return nil, err + } + return schema, nil +} diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go new file mode 100644 index 000000000..44722ffd5 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/swagger.go @@ -0,0 +1,448 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "bytes" + "encoding/gob" + "encoding/json" + "fmt" + "strconv" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// Swagger this is the root document object for the API specification. +// It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) +// together into one document. +// +// For more information: http://goo.gl/8us55a#swagger-object- +type Swagger struct { + VendorExtensible + SwaggerProps +} + +// JSONLookup look up a value by the json property name +func (s Swagger) JSONLookup(token string) (interface{}, error) { + if ex, ok := s.Extensions[token]; ok { + return &ex, nil + } + r, _, err := jsonpointer.GetForToken(s.SwaggerProps, token) + return r, err +} + +// MarshalJSON marshals this swagger structure to json +func (s Swagger) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(s.SwaggerProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(s.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON unmarshals a swagger spec from json +func (s *Swagger) UnmarshalJSON(data []byte) error { + var sw Swagger + if err := json.Unmarshal(data, &sw.SwaggerProps); err != nil { + return err + } + if err := json.Unmarshal(data, &sw.VendorExtensible); err != nil { + return err + } + *s = sw + return nil +} + +// GobEncode provides a safe gob encoder for Swagger, including extensions +func (s Swagger) GobEncode() ([]byte, error) { + var b bytes.Buffer + raw := struct { + Props SwaggerProps + Ext VendorExtensible + }{ + Props: s.SwaggerProps, + Ext: s.VendorExtensible, + } + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err +} + +// GobDecode provides a safe gob decoder for Swagger, including extensions +func (s *Swagger) GobDecode(b []byte) error { + var raw struct { + Props SwaggerProps + Ext VendorExtensible + } + buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + s.SwaggerProps = raw.Props + s.VendorExtensible = raw.Ext + return nil +} + +// SwaggerProps captures the top-level properties of an Api specification +// +// NOTE: validation rules +// - the scheme, when present must be from [http, https, ws, wss] +// - BasePath must start with a leading "/" +// - Paths is required +type SwaggerProps struct { + ID string `json:"id,omitempty"` + Consumes []string `json:"consumes,omitempty"` + Produces []string `json:"produces,omitempty"` + Schemes []string `json:"schemes,omitempty"` + Swagger string `json:"swagger,omitempty"` + Info *Info `json:"info,omitempty"` + Host string `json:"host,omitempty"` + BasePath string `json:"basePath,omitempty"` + Paths *Paths `json:"paths"` + Definitions Definitions `json:"definitions,omitempty"` + Parameters map[string]Parameter `json:"parameters,omitempty"` + Responses map[string]Response `json:"responses,omitempty"` + SecurityDefinitions SecurityDefinitions `json:"securityDefinitions,omitempty"` + Security []map[string][]string `json:"security,omitempty"` + Tags []Tag `json:"tags,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` +} + +type swaggerPropsAlias SwaggerProps + +type gobSwaggerPropsAlias struct { + Security []map[string]struct { + List []string + Pad bool + } + Alias *swaggerPropsAlias + SecurityIsEmpty bool +} + +// GobEncode provides a safe gob encoder for SwaggerProps, including empty security requirements +func (o SwaggerProps) GobEncode() ([]byte, error) { + raw := gobSwaggerPropsAlias{ + Alias: (*swaggerPropsAlias)(&o), + } + + var b bytes.Buffer + if o.Security == nil { + // nil security requirement + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } + + if len(o.Security) == 0 { + // empty, but non-nil security requirement + raw.SecurityIsEmpty = true + raw.Alias.Security = nil + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err + } + + raw.Security = make([]map[string]struct { + List []string + Pad bool + }, 0, len(o.Security)) + for _, req := range o.Security { + v := make(map[string]struct { + List []string + Pad bool + }, len(req)) + for k, val := range req { + v[k] = struct { + List []string + Pad bool + }{ + List: val, + } + } + raw.Security = append(raw.Security, v) + } + + err := gob.NewEncoder(&b).Encode(raw) + return b.Bytes(), err +} + +// GobDecode provides a safe gob decoder for SwaggerProps, including empty security requirements +func (o *SwaggerProps) GobDecode(b []byte) error { + var raw gobSwaggerPropsAlias + + buf := bytes.NewBuffer(b) + err := gob.NewDecoder(buf).Decode(&raw) + if err != nil { + return err + } + if raw.Alias == nil { + return nil + } + + switch { + case raw.SecurityIsEmpty: + // empty, but non-nil security requirement + raw.Alias.Security = []map[string][]string{} + case len(raw.Alias.Security) == 0: + // nil security requirement + raw.Alias.Security = nil + default: + raw.Alias.Security = make([]map[string][]string, 0, len(raw.Security)) + for _, req := range raw.Security { + v := make(map[string][]string, len(req)) + for k, val := range req { + v[k] = make([]string, 0, len(val.List)) + v[k] = append(v[k], val.List...) + } + raw.Alias.Security = append(raw.Alias.Security, v) + } + } + + *o = *(*SwaggerProps)(raw.Alias) + return nil +} + +// Dependencies represent a dependencies property +type Dependencies map[string]SchemaOrStringArray + +// SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property +type SchemaOrBool struct { + Allows bool + Schema *Schema +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SchemaOrBool) JSONLookup(token string) (interface{}, error) { + if token == "allows" { + return s.Allows, nil + } + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err +} + +var jsTrue = []byte("true") +var jsFalse = []byte("false") + +// MarshalJSON convert this object to JSON +func (s SchemaOrBool) MarshalJSON() ([]byte, error) { + if s.Schema != nil { + return json.Marshal(s.Schema) + } + + if s.Schema == nil && !s.Allows { + return jsFalse, nil + } + return jsTrue, nil +} + +// UnmarshalJSON converts this bool or schema object from a JSON structure +func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { + var nw SchemaOrBool + if len(data) >= 4 { + if data[0] == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + nw.Allows = !(data[0] == 'f' && data[1] == 'a' && data[2] == 'l' && data[3] == 's' && data[4] == 'e') + } + *s = nw + return nil +} + +// SchemaOrStringArray represents a schema or a string array +type SchemaOrStringArray struct { + Schema *Schema + Property []string +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SchemaOrStringArray) JSONLookup(token string) (interface{}, error) { + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err +} + +// MarshalJSON converts this schema object or array into JSON structure +func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { + if len(s.Property) > 0 { + return json.Marshal(s.Property) + } + if s.Schema != nil { + return json.Marshal(s.Schema) + } + return []byte("null"), nil +} + +// UnmarshalJSON converts this schema object or array from a JSON structure +func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { + var first byte + if len(data) > 1 { + first = data[0] + } + var nw SchemaOrStringArray + if first == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + if first == '[' { + if err := json.Unmarshal(data, &nw.Property); err != nil { + return err + } + } + *s = nw + return nil +} + +// Definitions contains the models explicitly defined in this spec +// An object to hold data types that can be consumed and produced by operations. +// These data types can be primitives, arrays or models. +// +// For more information: http://goo.gl/8us55a#definitionsObject +type Definitions map[string]Schema + +// SecurityDefinitions a declaration of the security schemes available to be used in the specification. +// This does not enforce the security schemes on the operations and only serves to provide +// the relevant details for each scheme. +// +// For more information: http://goo.gl/8us55a#securityDefinitionsObject +type SecurityDefinitions map[string]*SecurityScheme + +// StringOrArray represents a value that can either be a string +// or an array of strings. Mainly here for serialization purposes +type StringOrArray []string + +// Contains returns true when the value is contained in the slice +func (s StringOrArray) Contains(value string) bool { + for _, str := range s { + if str == value { + return true + } + } + return false +} + +// JSONLookup implements an interface to customize json pointer lookup +func (s SchemaOrArray) JSONLookup(token string) (interface{}, error) { + if _, err := strconv.Atoi(token); err == nil { + r, _, err := jsonpointer.GetForToken(s.Schemas, token) + return r, err + } + r, _, err := jsonpointer.GetForToken(s.Schema, token) + return r, err +} + +// UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string +func (s *StringOrArray) UnmarshalJSON(data []byte) error { + var first byte + if len(data) > 1 { + first = data[0] + } + + if first == '[' { + var parsed []string + if err := json.Unmarshal(data, &parsed); err != nil { + return err + } + *s = StringOrArray(parsed) + return nil + } + + var single interface{} + if err := json.Unmarshal(data, &single); err != nil { + return err + } + if single == nil { + return nil + } + switch v := single.(type) { + case string: + *s = StringOrArray([]string{v}) + return nil + default: + return fmt.Errorf("only string or array is allowed, not %T", single) + } +} + +// MarshalJSON converts this string or array to a JSON array or JSON string +func (s StringOrArray) MarshalJSON() ([]byte, error) { + if len(s) == 1 { + return json.Marshal([]string(s)[0]) + } + return json.Marshal([]string(s)) +} + +// SchemaOrArray represents a value that can either be a Schema +// or an array of Schema. Mainly here for serialization purposes +type SchemaOrArray struct { + Schema *Schema + Schemas []Schema +} + +// Len returns the number of schemas in this property +func (s SchemaOrArray) Len() int { + if s.Schema != nil { + return 1 + } + return len(s.Schemas) +} + +// ContainsType returns true when one of the schemas is of the specified type +func (s *SchemaOrArray) ContainsType(name string) bool { + if s.Schema != nil { + return s.Schema.Type != nil && s.Schema.Type.Contains(name) + } + return false +} + +// MarshalJSON converts this schema object or array into JSON structure +func (s SchemaOrArray) MarshalJSON() ([]byte, error) { + if len(s.Schemas) > 0 { + return json.Marshal(s.Schemas) + } + return json.Marshal(s.Schema) +} + +// UnmarshalJSON converts this schema object or array from a JSON structure +func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { + var nw SchemaOrArray + var first byte + if len(data) > 1 { + first = data[0] + } + if first == '{' { + var sch Schema + if err := json.Unmarshal(data, &sch); err != nil { + return err + } + nw.Schema = &sch + } + if first == '[' { + if err := json.Unmarshal(data, &nw.Schemas); err != nil { + return err + } + } + *s = nw + return nil +} + +// vim:set ft=go noet sts=2 sw=2 ts=2: diff --git a/vendor/github.com/go-openapi/spec/tag.go b/vendor/github.com/go-openapi/spec/tag.go new file mode 100644 index 000000000..faa3d3de1 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/tag.go @@ -0,0 +1,75 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +import ( + "encoding/json" + + "github.com/go-openapi/jsonpointer" + "github.com/go-openapi/swag" +) + +// TagProps describe a tag entry in the top level tags section of a swagger spec +type TagProps struct { + Description string `json:"description,omitempty"` + Name string `json:"name,omitempty"` + ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` +} + +// NewTag creates a new tag +func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag { + return Tag{TagProps: TagProps{Description: description, Name: name, ExternalDocs: externalDocs}} +} + +// Tag allows adding meta data to a single tag that is used by the +// [Operation Object](http://goo.gl/8us55a#operationObject). +// It is not mandatory to have a Tag Object per tag used there. +// +// For more information: http://goo.gl/8us55a#tagObject +type Tag struct { + VendorExtensible + TagProps +} + +// JSONLookup implements an interface to customize json pointer lookup +func (t Tag) JSONLookup(token string) (interface{}, error) { + if ex, ok := t.Extensions[token]; ok { + return &ex, nil + } + + r, _, err := jsonpointer.GetForToken(t.TagProps, token) + return r, err +} + +// MarshalJSON marshal this to JSON +func (t Tag) MarshalJSON() ([]byte, error) { + b1, err := json.Marshal(t.TagProps) + if err != nil { + return nil, err + } + b2, err := json.Marshal(t.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b1, b2), nil +} + +// UnmarshalJSON marshal this from JSON +func (t *Tag) UnmarshalJSON(data []byte) error { + if err := json.Unmarshal(data, &t.TagProps); err != nil { + return err + } + return json.Unmarshal(data, &t.VendorExtensible) +} diff --git a/vendor/github.com/go-openapi/spec/validations.go b/vendor/github.com/go-openapi/spec/validations.go new file mode 100644 index 000000000..6360a8ea7 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/validations.go @@ -0,0 +1,215 @@ +package spec + +// CommonValidations describe common JSON-schema validations +type CommonValidations struct { + Maximum *float64 `json:"maximum,omitempty"` + ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` + Minimum *float64 `json:"minimum,omitempty"` + ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` + MaxLength *int64 `json:"maxLength,omitempty"` + MinLength *int64 `json:"minLength,omitempty"` + Pattern string `json:"pattern,omitempty"` + MaxItems *int64 `json:"maxItems,omitempty"` + MinItems *int64 `json:"minItems,omitempty"` + UniqueItems bool `json:"uniqueItems,omitempty"` + MultipleOf *float64 `json:"multipleOf,omitempty"` + Enum []interface{} `json:"enum,omitempty"` +} + +// SetValidations defines all validations for a simple schema. +// +// NOTE: the input is the larger set of validations available for schemas. +// For simple schemas, MinProperties and MaxProperties are ignored. +func (v *CommonValidations) SetValidations(val SchemaValidations) { + v.Maximum = val.Maximum + v.ExclusiveMaximum = val.ExclusiveMaximum + v.Minimum = val.Minimum + v.ExclusiveMinimum = val.ExclusiveMinimum + v.MaxLength = val.MaxLength + v.MinLength = val.MinLength + v.Pattern = val.Pattern + v.MaxItems = val.MaxItems + v.MinItems = val.MinItems + v.UniqueItems = val.UniqueItems + v.MultipleOf = val.MultipleOf + v.Enum = val.Enum +} + +type clearedValidation struct { + Validation string + Value interface{} +} + +type clearedValidations []clearedValidation + +func (c clearedValidations) apply(cbs []func(string, interface{})) { + for _, cb := range cbs { + for _, cleared := range c { + cb(cleared.Validation, cleared.Value) + } + } +} + +// ClearNumberValidations clears all number validations. +// +// Some callbacks may be set by the caller to capture changed values. +func (v *CommonValidations) ClearNumberValidations(cbs ...func(string, interface{})) { + done := make(clearedValidations, 0, 5) + defer func() { + done.apply(cbs) + }() + + if v.Minimum != nil { + done = append(done, clearedValidation{Validation: "minimum", Value: v.Minimum}) + v.Minimum = nil + } + if v.Maximum != nil { + done = append(done, clearedValidation{Validation: "maximum", Value: v.Maximum}) + v.Maximum = nil + } + if v.ExclusiveMaximum { + done = append(done, clearedValidation{Validation: "exclusiveMaximum", Value: v.ExclusiveMaximum}) + v.ExclusiveMaximum = false + } + if v.ExclusiveMinimum { + done = append(done, clearedValidation{Validation: "exclusiveMinimum", Value: v.ExclusiveMinimum}) + v.ExclusiveMinimum = false + } + if v.MultipleOf != nil { + done = append(done, clearedValidation{Validation: "multipleOf", Value: v.MultipleOf}) + v.MultipleOf = nil + } +} + +// ClearStringValidations clears all string validations. +// +// Some callbacks may be set by the caller to capture changed values. +func (v *CommonValidations) ClearStringValidations(cbs ...func(string, interface{})) { + done := make(clearedValidations, 0, 3) + defer func() { + done.apply(cbs) + }() + + if v.Pattern != "" { + done = append(done, clearedValidation{Validation: "pattern", Value: v.Pattern}) + v.Pattern = "" + } + if v.MinLength != nil { + done = append(done, clearedValidation{Validation: "minLength", Value: v.MinLength}) + v.MinLength = nil + } + if v.MaxLength != nil { + done = append(done, clearedValidation{Validation: "maxLength", Value: v.MaxLength}) + v.MaxLength = nil + } +} + +// ClearArrayValidations clears all array validations. +// +// Some callbacks may be set by the caller to capture changed values. +func (v *CommonValidations) ClearArrayValidations(cbs ...func(string, interface{})) { + done := make(clearedValidations, 0, 3) + defer func() { + done.apply(cbs) + }() + + if v.MaxItems != nil { + done = append(done, clearedValidation{Validation: "maxItems", Value: v.MaxItems}) + v.MaxItems = nil + } + if v.MinItems != nil { + done = append(done, clearedValidation{Validation: "minItems", Value: v.MinItems}) + v.MinItems = nil + } + if v.UniqueItems { + done = append(done, clearedValidation{Validation: "uniqueItems", Value: v.UniqueItems}) + v.UniqueItems = false + } +} + +// Validations returns a clone of the validations for a simple schema. +// +// NOTE: in the context of simple schema objects, MinProperties, MaxProperties +// and PatternProperties remain unset. +func (v CommonValidations) Validations() SchemaValidations { + return SchemaValidations{ + CommonValidations: v, + } +} + +// HasNumberValidations indicates if the validations are for numbers or integers +func (v CommonValidations) HasNumberValidations() bool { + return v.Maximum != nil || v.Minimum != nil || v.MultipleOf != nil +} + +// HasStringValidations indicates if the validations are for strings +func (v CommonValidations) HasStringValidations() bool { + return v.MaxLength != nil || v.MinLength != nil || v.Pattern != "" +} + +// HasArrayValidations indicates if the validations are for arrays +func (v CommonValidations) HasArrayValidations() bool { + return v.MaxItems != nil || v.MinItems != nil || v.UniqueItems +} + +// HasEnum indicates if the validation includes some enum constraint +func (v CommonValidations) HasEnum() bool { + return len(v.Enum) > 0 +} + +// SchemaValidations describes the validation properties of a schema +// +// NOTE: at this moment, this is not embedded in SchemaProps because this would induce a breaking change +// in the exported members: all initializers using litterals would fail. +type SchemaValidations struct { + CommonValidations + + PatternProperties SchemaProperties `json:"patternProperties,omitempty"` + MaxProperties *int64 `json:"maxProperties,omitempty"` + MinProperties *int64 `json:"minProperties,omitempty"` +} + +// HasObjectValidations indicates if the validations are for objects +func (v SchemaValidations) HasObjectValidations() bool { + return v.MaxProperties != nil || v.MinProperties != nil || v.PatternProperties != nil +} + +// SetValidations for schema validations +func (v *SchemaValidations) SetValidations(val SchemaValidations) { + v.CommonValidations.SetValidations(val) + v.PatternProperties = val.PatternProperties + v.MaxProperties = val.MaxProperties + v.MinProperties = val.MinProperties +} + +// Validations for a schema +func (v SchemaValidations) Validations() SchemaValidations { + val := v.CommonValidations.Validations() + val.PatternProperties = v.PatternProperties + val.MinProperties = v.MinProperties + val.MaxProperties = v.MaxProperties + return val +} + +// ClearObjectValidations returns a clone of the validations with all object validations cleared. +// +// Some callbacks may be set by the caller to capture changed values. +func (v *SchemaValidations) ClearObjectValidations(cbs ...func(string, interface{})) { + done := make(clearedValidations, 0, 3) + defer func() { + done.apply(cbs) + }() + + if v.MaxProperties != nil { + done = append(done, clearedValidation{Validation: "maxProperties", Value: v.MaxProperties}) + v.MaxProperties = nil + } + if v.MinProperties != nil { + done = append(done, clearedValidation{Validation: "minProperties", Value: v.MinProperties}) + v.MinProperties = nil + } + if v.PatternProperties != nil { + done = append(done, clearedValidation{Validation: "patternProperties", Value: v.PatternProperties}) + v.PatternProperties = nil + } +} diff --git a/vendor/github.com/go-openapi/spec/xml_object.go b/vendor/github.com/go-openapi/spec/xml_object.go new file mode 100644 index 000000000..945a46703 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/xml_object.go @@ -0,0 +1,68 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package spec + +// XMLObject a metadata object that allows for more fine-tuned XML model definitions. +// +// For more information: http://goo.gl/8us55a#xmlObject +type XMLObject struct { + Name string `json:"name,omitempty"` + Namespace string `json:"namespace,omitempty"` + Prefix string `json:"prefix,omitempty"` + Attribute bool `json:"attribute,omitempty"` + Wrapped bool `json:"wrapped,omitempty"` +} + +// WithName sets the xml name for the object +func (x *XMLObject) WithName(name string) *XMLObject { + x.Name = name + return x +} + +// WithNamespace sets the xml namespace for the object +func (x *XMLObject) WithNamespace(namespace string) *XMLObject { + x.Namespace = namespace + return x +} + +// WithPrefix sets the xml prefix for the object +func (x *XMLObject) WithPrefix(prefix string) *XMLObject { + x.Prefix = prefix + return x +} + +// AsAttribute flags this object as xml attribute +func (x *XMLObject) AsAttribute() *XMLObject { + x.Attribute = true + return x +} + +// AsElement flags this object as an xml node +func (x *XMLObject) AsElement() *XMLObject { + x.Attribute = false + return x +} + +// AsWrapped flags this object as wrapped, this is mostly useful for array types +func (x *XMLObject) AsWrapped() *XMLObject { + x.Wrapped = true + return x +} + +// AsUnwrapped flags this object as an xml node +func (x *XMLObject) AsUnwrapped() *XMLObject { + x.Wrapped = false + return x +} diff --git a/vendor/github.com/go-openapi/swag/.editorconfig b/vendor/github.com/go-openapi/swag/.editorconfig new file mode 100644 index 000000000..3152da69a --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.editorconfig @@ -0,0 +1,26 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +# Set default charset +[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] +charset = utf-8 + +# Tab indentation (no size specified) +[*.go] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false + +# Matches the exact files either package.json or .travis.yml +[{package.json,.travis.yml}] +indent_style = space +indent_size = 2 diff --git a/vendor/github.com/go-openapi/swag/.gitignore b/vendor/github.com/go-openapi/swag/.gitignore new file mode 100644 index 000000000..d69b53acc --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.gitignore @@ -0,0 +1,4 @@ +secrets.yml +vendor +Godeps +.idea diff --git a/vendor/github.com/go-openapi/swag/.golangci.yml b/vendor/github.com/go-openapi/swag/.golangci.yml new file mode 100644 index 000000000..842ac1c09 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.golangci.yml @@ -0,0 +1,41 @@ +linters-settings: + govet: + check-shadowing: true + golint: + min-confidence: 0 + gocyclo: + min-complexity: 25 + maligned: + suggest-new: true + dupl: + threshold: 100 + goconst: + min-len: 3 + min-occurrences: 2 + +linters: + enable-all: true + disable: + - maligned + - lll + - gochecknoinits + - gochecknoglobals + - nlreturn + - testpackage + - wrapcheck + - gomnd + - exhaustive + - exhaustivestruct + - goerr113 + - wsl + - whitespace + - gofumpt + - godot + - nestif + - godox + - funlen + - gci + - gocognit + - paralleltest + - thelper + - ifshort diff --git a/vendor/github.com/go-openapi/swag/.travis.yml b/vendor/github.com/go-openapi/swag/.travis.yml new file mode 100644 index 000000000..fc25a8872 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/.travis.yml @@ -0,0 +1,37 @@ +after_success: +- bash <(curl -s https://codecov.io/bash) +go: +- 1.14.x +- 1.x +arch: +- amd64 +jobs: + include: + # include arch ppc, but only for latest go version - skip testing for race + - go: 1.x + arch: ppc64le + install: ~ + script: + - go test -v + + #- go: 1.x + # arch: arm + # install: ~ + # script: + # - go test -v + + # include linting job, but only for latest go version and amd64 arch + - go: 1.x + arch: amd64 + install: + go get github.com/golangci/golangci-lint/cmd/golangci-lint + script: + - golangci-lint run --new-from-rev master +install: +- GO111MODULE=off go get -u gotest.tools/gotestsum +language: go +notifications: + slack: + secure: QUWvCkBBK09GF7YtEvHHVt70JOkdlNBG0nIKu/5qc4/nW5HP8I2w0SEf/XR2je0eED1Qe3L/AfMCWwrEj+IUZc3l4v+ju8X8R3Lomhme0Eb0jd1MTMCuPcBT47YCj0M7RON7vXtbFfm1hFJ/jLe5+9FXz0hpXsR24PJc5ZIi/ogNwkaPqG4BmndzecpSh0vc2FJPZUD9LT0I09REY/vXR0oQAalLkW0asGD5taHZTUZq/kBpsNxaAFrLM23i4mUcf33M5fjLpvx5LRICrX/57XpBrDh2TooBU6Qj3CgoY0uPRYUmSNxbVx1czNzl2JtEpb5yjoxfVPQeg0BvQM00G8LJINISR+ohrjhkZmAqchDupAX+yFrxTtORa78CtnIL6z/aTNlgwwVD8kvL/1pFA/JWYmKDmz93mV/+6wubGzNSQCstzjkFA4/iZEKewKUoRIAi/fxyscP6L/rCpmY/4llZZvrnyTqVbt6URWpopUpH4rwYqreXAtJxJsfBJIeSmUIiDIOMGkCTvyTEW3fWGmGoqWtSHLoaWDyAIGb7azb+KvfpWtEcoPFWfSWU+LGee0A/YsUhBl7ADB9A0CJEuR8q4BPpKpfLwPKSiKSAXL7zDkyjExyhtgqbSl2jS+rKIHOZNL8JkCcTP2MKMVd563C5rC5FMKqu3S9m2b6380E= +script: +- gotestsum -f short-verbose -- -race -coverprofile=coverage.txt -covermode=atomic ./... diff --git a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..9322b065e --- /dev/null +++ b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at ivan+abuse@flanders.co.nz. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/swag/LICENSE b/vendor/github.com/go-openapi/swag/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md new file mode 100644 index 000000000..217f6fa50 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/README.md @@ -0,0 +1,21 @@ +# Swag [![Build Status](https://travis-ci.org/go-openapi/swag.svg?branch=master)](https://travis-ci.org/go-openapi/swag) [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) + +[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) +[![GoDoc](https://godoc.org/github.com/go-openapi/swag?status.svg)](http://godoc.org/github.com/go-openapi/swag) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/swag)](https://goreportcard.com/report/github.com/go-openapi/swag) + +Contains a bunch of helper functions for go-openapi and go-swagger projects. + +You may also use it standalone for your projects. + +* convert between value and pointers for builtin types +* convert from string to builtin types (wraps strconv) +* fast json concatenation +* search in path +* load from file or http +* name mangling + + +This repo has only few dependencies outside of the standard library: + +* YAML utilities depend on gopkg.in/yaml.v2 diff --git a/vendor/github.com/go-openapi/swag/convert.go b/vendor/github.com/go-openapi/swag/convert.go new file mode 100644 index 000000000..fc085aeb8 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/convert.go @@ -0,0 +1,208 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "math" + "strconv" + "strings" +) + +// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER +const ( + maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 + minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 + epsilon float64 = 1e-9 +) + +// IsFloat64AJSONInteger allow for integers [-2^53, 2^53-1] inclusive +func IsFloat64AJSONInteger(f float64) bool { + if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { + return false + } + fa := math.Abs(f) + g := float64(uint64(f)) + ga := math.Abs(g) + + diff := math.Abs(f - g) + + // more info: https://floating-point-gui.de/errors/comparison/#look-out-for-edge-cases + switch { + case f == g: // best case + return true + case f == float64(int64(f)) || f == float64(uint64(f)): // optimistic case + return true + case f == 0 || g == 0 || diff < math.SmallestNonzeroFloat64: // very close to 0 values + return diff < (epsilon * math.SmallestNonzeroFloat64) + } + // check the relative error + return diff/math.Min(fa+ga, math.MaxFloat64) < epsilon +} + +var evaluatesAsTrue map[string]struct{} + +func init() { + evaluatesAsTrue = map[string]struct{}{ + "true": {}, + "1": {}, + "yes": {}, + "ok": {}, + "y": {}, + "on": {}, + "selected": {}, + "checked": {}, + "t": {}, + "enabled": {}, + } +} + +// ConvertBool turn a string into a boolean +func ConvertBool(str string) (bool, error) { + _, ok := evaluatesAsTrue[strings.ToLower(str)] + return ok, nil +} + +// ConvertFloat32 turn a string into a float32 +func ConvertFloat32(str string) (float32, error) { + f, err := strconv.ParseFloat(str, 32) + if err != nil { + return 0, err + } + return float32(f), nil +} + +// ConvertFloat64 turn a string into a float64 +func ConvertFloat64(str string) (float64, error) { + return strconv.ParseFloat(str, 64) +} + +// ConvertInt8 turn a string into an int8 +func ConvertInt8(str string) (int8, error) { + i, err := strconv.ParseInt(str, 10, 8) + if err != nil { + return 0, err + } + return int8(i), nil +} + +// ConvertInt16 turn a string into an int16 +func ConvertInt16(str string) (int16, error) { + i, err := strconv.ParseInt(str, 10, 16) + if err != nil { + return 0, err + } + return int16(i), nil +} + +// ConvertInt32 turn a string into an int32 +func ConvertInt32(str string) (int32, error) { + i, err := strconv.ParseInt(str, 10, 32) + if err != nil { + return 0, err + } + return int32(i), nil +} + +// ConvertInt64 turn a string into an int64 +func ConvertInt64(str string) (int64, error) { + return strconv.ParseInt(str, 10, 64) +} + +// ConvertUint8 turn a string into an uint8 +func ConvertUint8(str string) (uint8, error) { + i, err := strconv.ParseUint(str, 10, 8) + if err != nil { + return 0, err + } + return uint8(i), nil +} + +// ConvertUint16 turn a string into an uint16 +func ConvertUint16(str string) (uint16, error) { + i, err := strconv.ParseUint(str, 10, 16) + if err != nil { + return 0, err + } + return uint16(i), nil +} + +// ConvertUint32 turn a string into an uint32 +func ConvertUint32(str string) (uint32, error) { + i, err := strconv.ParseUint(str, 10, 32) + if err != nil { + return 0, err + } + return uint32(i), nil +} + +// ConvertUint64 turn a string into an uint64 +func ConvertUint64(str string) (uint64, error) { + return strconv.ParseUint(str, 10, 64) +} + +// FormatBool turns a boolean into a string +func FormatBool(value bool) string { + return strconv.FormatBool(value) +} + +// FormatFloat32 turns a float32 into a string +func FormatFloat32(value float32) string { + return strconv.FormatFloat(float64(value), 'f', -1, 32) +} + +// FormatFloat64 turns a float64 into a string +func FormatFloat64(value float64) string { + return strconv.FormatFloat(value, 'f', -1, 64) +} + +// FormatInt8 turns an int8 into a string +func FormatInt8(value int8) string { + return strconv.FormatInt(int64(value), 10) +} + +// FormatInt16 turns an int16 into a string +func FormatInt16(value int16) string { + return strconv.FormatInt(int64(value), 10) +} + +// FormatInt32 turns an int32 into a string +func FormatInt32(value int32) string { + return strconv.Itoa(int(value)) +} + +// FormatInt64 turns an int64 into a string +func FormatInt64(value int64) string { + return strconv.FormatInt(value, 10) +} + +// FormatUint8 turns an uint8 into a string +func FormatUint8(value uint8) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatUint16 turns an uint16 into a string +func FormatUint16(value uint16) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatUint32 turns an uint32 into a string +func FormatUint32(value uint32) string { + return strconv.FormatUint(uint64(value), 10) +} + +// FormatUint64 turns an uint64 into a string +func FormatUint64(value uint64) string { + return strconv.FormatUint(value, 10) +} diff --git a/vendor/github.com/go-openapi/swag/convert_types.go b/vendor/github.com/go-openapi/swag/convert_types.go new file mode 100644 index 000000000..c49cc473a --- /dev/null +++ b/vendor/github.com/go-openapi/swag/convert_types.go @@ -0,0 +1,730 @@ +package swag + +import "time" + +// This file was taken from the aws go sdk + +// String returns a pointer to of the string value passed in. +func String(v string) *string { + return &v +} + +// StringValue returns the value of the string pointer passed in or +// "" if the pointer is nil. +func StringValue(v *string) string { + if v != nil { + return *v + } + return "" +} + +// StringSlice converts a slice of string values into a slice of +// string pointers +func StringSlice(src []string) []*string { + dst := make([]*string, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// StringValueSlice converts a slice of string pointers into a slice of +// string values +func StringValueSlice(src []*string) []string { + dst := make([]string, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// StringMap converts a string map of string values into a string +// map of string pointers +func StringMap(src map[string]string) map[string]*string { + dst := make(map[string]*string) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// StringValueMap converts a string map of string pointers into a string +// map of string values +func StringValueMap(src map[string]*string) map[string]string { + dst := make(map[string]string) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Bool returns a pointer to of the bool value passed in. +func Bool(v bool) *bool { + return &v +} + +// BoolValue returns the value of the bool pointer passed in or +// false if the pointer is nil. +func BoolValue(v *bool) bool { + if v != nil { + return *v + } + return false +} + +// BoolSlice converts a slice of bool values into a slice of +// bool pointers +func BoolSlice(src []bool) []*bool { + dst := make([]*bool, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// BoolValueSlice converts a slice of bool pointers into a slice of +// bool values +func BoolValueSlice(src []*bool) []bool { + dst := make([]bool, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// BoolMap converts a string map of bool values into a string +// map of bool pointers +func BoolMap(src map[string]bool) map[string]*bool { + dst := make(map[string]*bool) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// BoolValueMap converts a string map of bool pointers into a string +// map of bool values +func BoolValueMap(src map[string]*bool) map[string]bool { + dst := make(map[string]bool) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int returns a pointer to of the int value passed in. +func Int(v int) *int { + return &v +} + +// IntValue returns the value of the int pointer passed in or +// 0 if the pointer is nil. +func IntValue(v *int) int { + if v != nil { + return *v + } + return 0 +} + +// IntSlice converts a slice of int values into a slice of +// int pointers +func IntSlice(src []int) []*int { + dst := make([]*int, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// IntValueSlice converts a slice of int pointers into a slice of +// int values +func IntValueSlice(src []*int) []int { + dst := make([]int, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// IntMap converts a string map of int values into a string +// map of int pointers +func IntMap(src map[string]int) map[string]*int { + dst := make(map[string]*int) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// IntValueMap converts a string map of int pointers into a string +// map of int values +func IntValueMap(src map[string]*int) map[string]int { + dst := make(map[string]int) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int32 returns a pointer to of the int32 value passed in. +func Int32(v int32) *int32 { + return &v +} + +// Int32Value returns the value of the int32 pointer passed in or +// 0 if the pointer is nil. +func Int32Value(v *int32) int32 { + if v != nil { + return *v + } + return 0 +} + +// Int32Slice converts a slice of int32 values into a slice of +// int32 pointers +func Int32Slice(src []int32) []*int32 { + dst := make([]*int32, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Int32ValueSlice converts a slice of int32 pointers into a slice of +// int32 values +func Int32ValueSlice(src []*int32) []int32 { + dst := make([]int32, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Int32Map converts a string map of int32 values into a string +// map of int32 pointers +func Int32Map(src map[string]int32) map[string]*int32 { + dst := make(map[string]*int32) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Int32ValueMap converts a string map of int32 pointers into a string +// map of int32 values +func Int32ValueMap(src map[string]*int32) map[string]int32 { + dst := make(map[string]int32) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int64 returns a pointer to of the int64 value passed in. +func Int64(v int64) *int64 { + return &v +} + +// Int64Value returns the value of the int64 pointer passed in or +// 0 if the pointer is nil. +func Int64Value(v *int64) int64 { + if v != nil { + return *v + } + return 0 +} + +// Int64Slice converts a slice of int64 values into a slice of +// int64 pointers +func Int64Slice(src []int64) []*int64 { + dst := make([]*int64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Int64ValueSlice converts a slice of int64 pointers into a slice of +// int64 values +func Int64ValueSlice(src []*int64) []int64 { + dst := make([]int64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Int64Map converts a string map of int64 values into a string +// map of int64 pointers +func Int64Map(src map[string]int64) map[string]*int64 { + dst := make(map[string]*int64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Int64ValueMap converts a string map of int64 pointers into a string +// map of int64 values +func Int64ValueMap(src map[string]*int64) map[string]int64 { + dst := make(map[string]int64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Uint16 returns a pointer to of the uint16 value passed in. +func Uint16(v uint16) *uint16 { + return &v +} + +// Uint16Value returns the value of the uint16 pointer passed in or +// 0 if the pointer is nil. +func Uint16Value(v *uint16) uint16 { + if v != nil { + return *v + } + + return 0 +} + +// Uint16Slice converts a slice of uint16 values into a slice of +// uint16 pointers +func Uint16Slice(src []uint16) []*uint16 { + dst := make([]*uint16, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + + return dst +} + +// Uint16ValueSlice converts a slice of uint16 pointers into a slice of +// uint16 values +func Uint16ValueSlice(src []*uint16) []uint16 { + dst := make([]uint16, len(src)) + + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + + return dst +} + +// Uint16Map converts a string map of uint16 values into a string +// map of uint16 pointers +func Uint16Map(src map[string]uint16) map[string]*uint16 { + dst := make(map[string]*uint16) + + for k, val := range src { + v := val + dst[k] = &v + } + + return dst +} + +// Uint16ValueMap converts a string map of uint16 pointers into a string +// map of uint16 values +func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { + dst := make(map[string]uint16) + + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + + return dst +} + +// Uint returns a pointer to of the uint value passed in. +func Uint(v uint) *uint { + return &v +} + +// UintValue returns the value of the uint pointer passed in or +// 0 if the pointer is nil. +func UintValue(v *uint) uint { + if v != nil { + return *v + } + return 0 +} + +// UintSlice converts a slice of uint values into a slice of +// uint pointers +func UintSlice(src []uint) []*uint { + dst := make([]*uint, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// UintValueSlice converts a slice of uint pointers into a slice of +// uint values +func UintValueSlice(src []*uint) []uint { + dst := make([]uint, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// UintMap converts a string map of uint values into a string +// map of uint pointers +func UintMap(src map[string]uint) map[string]*uint { + dst := make(map[string]*uint) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// UintValueMap converts a string map of uint pointers into a string +// map of uint values +func UintValueMap(src map[string]*uint) map[string]uint { + dst := make(map[string]uint) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Uint32 returns a pointer to of the uint32 value passed in. +func Uint32(v uint32) *uint32 { + return &v +} + +// Uint32Value returns the value of the uint32 pointer passed in or +// 0 if the pointer is nil. +func Uint32Value(v *uint32) uint32 { + if v != nil { + return *v + } + return 0 +} + +// Uint32Slice converts a slice of uint32 values into a slice of +// uint32 pointers +func Uint32Slice(src []uint32) []*uint32 { + dst := make([]*uint32, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Uint32ValueSlice converts a slice of uint32 pointers into a slice of +// uint32 values +func Uint32ValueSlice(src []*uint32) []uint32 { + dst := make([]uint32, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Uint32Map converts a string map of uint32 values into a string +// map of uint32 pointers +func Uint32Map(src map[string]uint32) map[string]*uint32 { + dst := make(map[string]*uint32) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Uint32ValueMap converts a string map of uint32 pointers into a string +// map of uint32 values +func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { + dst := make(map[string]uint32) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Uint64 returns a pointer to of the uint64 value passed in. +func Uint64(v uint64) *uint64 { + return &v +} + +// Uint64Value returns the value of the uint64 pointer passed in or +// 0 if the pointer is nil. +func Uint64Value(v *uint64) uint64 { + if v != nil { + return *v + } + return 0 +} + +// Uint64Slice converts a slice of uint64 values into a slice of +// uint64 pointers +func Uint64Slice(src []uint64) []*uint64 { + dst := make([]*uint64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Uint64ValueSlice converts a slice of uint64 pointers into a slice of +// uint64 values +func Uint64ValueSlice(src []*uint64) []uint64 { + dst := make([]uint64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Uint64Map converts a string map of uint64 values into a string +// map of uint64 pointers +func Uint64Map(src map[string]uint64) map[string]*uint64 { + dst := make(map[string]*uint64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Uint64ValueMap converts a string map of uint64 pointers into a string +// map of uint64 values +func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { + dst := make(map[string]uint64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Float32 returns a pointer to of the float32 value passed in. +func Float32(v float32) *float32 { + return &v +} + +// Float32Value returns the value of the float32 pointer passed in or +// 0 if the pointer is nil. +func Float32Value(v *float32) float32 { + if v != nil { + return *v + } + + return 0 +} + +// Float32Slice converts a slice of float32 values into a slice of +// float32 pointers +func Float32Slice(src []float32) []*float32 { + dst := make([]*float32, len(src)) + + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + + return dst +} + +// Float32ValueSlice converts a slice of float32 pointers into a slice of +// float32 values +func Float32ValueSlice(src []*float32) []float32 { + dst := make([]float32, len(src)) + + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + + return dst +} + +// Float32Map converts a string map of float32 values into a string +// map of float32 pointers +func Float32Map(src map[string]float32) map[string]*float32 { + dst := make(map[string]*float32) + + for k, val := range src { + v := val + dst[k] = &v + } + + return dst +} + +// Float32ValueMap converts a string map of float32 pointers into a string +// map of float32 values +func Float32ValueMap(src map[string]*float32) map[string]float32 { + dst := make(map[string]float32) + + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + + return dst +} + +// Float64 returns a pointer to of the float64 value passed in. +func Float64(v float64) *float64 { + return &v +} + +// Float64Value returns the value of the float64 pointer passed in or +// 0 if the pointer is nil. +func Float64Value(v *float64) float64 { + if v != nil { + return *v + } + return 0 +} + +// Float64Slice converts a slice of float64 values into a slice of +// float64 pointers +func Float64Slice(src []float64) []*float64 { + dst := make([]*float64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Float64ValueSlice converts a slice of float64 pointers into a slice of +// float64 values +func Float64ValueSlice(src []*float64) []float64 { + dst := make([]float64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Float64Map converts a string map of float64 values into a string +// map of float64 pointers +func Float64Map(src map[string]float64) map[string]*float64 { + dst := make(map[string]*float64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Float64ValueMap converts a string map of float64 pointers into a string +// map of float64 values +func Float64ValueMap(src map[string]*float64) map[string]float64 { + dst := make(map[string]float64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Time returns a pointer to of the time.Time value passed in. +func Time(v time.Time) *time.Time { + return &v +} + +// TimeValue returns the value of the time.Time pointer passed in or +// time.Time{} if the pointer is nil. +func TimeValue(v *time.Time) time.Time { + if v != nil { + return *v + } + return time.Time{} +} + +// TimeSlice converts a slice of time.Time values into a slice of +// time.Time pointers +func TimeSlice(src []time.Time) []*time.Time { + dst := make([]*time.Time, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// TimeValueSlice converts a slice of time.Time pointers into a slice of +// time.Time values +func TimeValueSlice(src []*time.Time) []time.Time { + dst := make([]time.Time, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// TimeMap converts a string map of time.Time values into a string +// map of time.Time pointers +func TimeMap(src map[string]time.Time) map[string]*time.Time { + dst := make(map[string]*time.Time) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// TimeValueMap converts a string map of time.Time pointers into a string +// map of time.Time values +func TimeValueMap(src map[string]*time.Time) map[string]time.Time { + dst := make(map[string]time.Time) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} diff --git a/vendor/github.com/go-openapi/swag/doc.go b/vendor/github.com/go-openapi/swag/doc.go new file mode 100644 index 000000000..8d2c8c501 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/doc.go @@ -0,0 +1,32 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* +Package swag contains a bunch of helper functions for go-openapi and go-swagger projects. + +You may also use it standalone for your projects. + + * convert between value and pointers for builtin types + * convert from string to builtin types (wraps strconv) + * fast json concatenation + * search in path + * load from file or http + * name mangling + + +This repo has only few dependencies outside of the standard library: + + * YAML utilities depend on gopkg.in/yaml.v2 +*/ +package swag diff --git a/vendor/github.com/go-openapi/swag/json.go b/vendor/github.com/go-openapi/swag/json.go new file mode 100644 index 000000000..7e9902ca3 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/json.go @@ -0,0 +1,312 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "bytes" + "encoding/json" + "log" + "reflect" + "strings" + "sync" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" +) + +// nullJSON represents a JSON object with null type +var nullJSON = []byte("null") + +// DefaultJSONNameProvider the default cache for types +var DefaultJSONNameProvider = NewNameProvider() + +const comma = byte(',') + +var closers map[byte]byte + +func init() { + closers = map[byte]byte{ + '{': '}', + '[': ']', + } +} + +type ejMarshaler interface { + MarshalEasyJSON(w *jwriter.Writer) +} + +type ejUnmarshaler interface { + UnmarshalEasyJSON(w *jlexer.Lexer) +} + +// WriteJSON writes json data, prefers finding an appropriate interface to short-circuit the marshaler +// so it takes the fastest option available. +func WriteJSON(data interface{}) ([]byte, error) { + if d, ok := data.(ejMarshaler); ok { + jw := new(jwriter.Writer) + d.MarshalEasyJSON(jw) + return jw.BuildBytes() + } + if d, ok := data.(json.Marshaler); ok { + return d.MarshalJSON() + } + return json.Marshal(data) +} + +// ReadJSON reads json data, prefers finding an appropriate interface to short-circuit the unmarshaler +// so it takes the fastest option available +func ReadJSON(data []byte, value interface{}) error { + trimmedData := bytes.Trim(data, "\x00") + if d, ok := value.(ejUnmarshaler); ok { + jl := &jlexer.Lexer{Data: trimmedData} + d.UnmarshalEasyJSON(jl) + return jl.Error() + } + if d, ok := value.(json.Unmarshaler); ok { + return d.UnmarshalJSON(trimmedData) + } + return json.Unmarshal(trimmedData, value) +} + +// DynamicJSONToStruct converts an untyped json structure into a struct +func DynamicJSONToStruct(data interface{}, target interface{}) error { + // TODO: convert straight to a json typed map (mergo + iterate?) + b, err := WriteJSON(data) + if err != nil { + return err + } + return ReadJSON(b, target) +} + +// ConcatJSON concatenates multiple json objects efficiently +func ConcatJSON(blobs ...[]byte) []byte { + if len(blobs) == 0 { + return nil + } + + last := len(blobs) - 1 + for blobs[last] == nil || bytes.Equal(blobs[last], nullJSON) { + // strips trailing null objects + last-- + if last < 0 { + // there was nothing but "null"s or nil... + return nil + } + } + if last == 0 { + return blobs[0] + } + + var opening, closing byte + var idx, a int + buf := bytes.NewBuffer(nil) + + for i, b := range blobs[:last+1] { + if b == nil || bytes.Equal(b, nullJSON) { + // a null object is in the list: skip it + continue + } + if len(b) > 0 && opening == 0 { // is this an array or an object? + opening, closing = b[0], closers[b[0]] + } + + if opening != '{' && opening != '[' { + continue // don't know how to concatenate non container objects + } + + if len(b) < 3 { // yep empty but also the last one, so closing this thing + if i == last && a > 0 { + if err := buf.WriteByte(closing); err != nil { + log.Println(err) + } + } + continue + } + + idx = 0 + if a > 0 { // we need to join with a comma for everything beyond the first non-empty item + if err := buf.WriteByte(comma); err != nil { + log.Println(err) + } + idx = 1 // this is not the first or the last so we want to drop the leading bracket + } + + if i != last { // not the last one, strip brackets + if _, err := buf.Write(b[idx : len(b)-1]); err != nil { + log.Println(err) + } + } else { // last one, strip only the leading bracket + if _, err := buf.Write(b[idx:]); err != nil { + log.Println(err) + } + } + a++ + } + // somehow it ended up being empty, so provide a default value + if buf.Len() == 0 { + if err := buf.WriteByte(opening); err != nil { + log.Println(err) + } + if err := buf.WriteByte(closing); err != nil { + log.Println(err) + } + } + return buf.Bytes() +} + +// ToDynamicJSON turns an object into a properly JSON typed structure +func ToDynamicJSON(data interface{}) interface{} { + // TODO: convert straight to a json typed map (mergo + iterate?) + b, err := json.Marshal(data) + if err != nil { + log.Println(err) + } + var res interface{} + if err := json.Unmarshal(b, &res); err != nil { + log.Println(err) + } + return res +} + +// FromDynamicJSON turns an object into a properly JSON typed structure +func FromDynamicJSON(data, target interface{}) error { + b, err := json.Marshal(data) + if err != nil { + log.Println(err) + } + return json.Unmarshal(b, target) +} + +// NameProvider represents an object capable of translating from go property names +// to json property names +// This type is thread-safe. +type NameProvider struct { + lock *sync.Mutex + index map[reflect.Type]nameIndex +} + +type nameIndex struct { + jsonNames map[string]string + goNames map[string]string +} + +// NewNameProvider creates a new name provider +func NewNameProvider() *NameProvider { + return &NameProvider{ + lock: &sync.Mutex{}, + index: make(map[reflect.Type]nameIndex), + } +} + +func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { + for i := 0; i < tpe.NumField(); i++ { + targetDes := tpe.Field(i) + + if targetDes.PkgPath != "" { // unexported + continue + } + + if targetDes.Anonymous { // walk embedded structures tree down first + buildnameIndex(targetDes.Type, idx, reverseIdx) + continue + } + + if tag := targetDes.Tag.Get("json"); tag != "" { + + parts := strings.Split(tag, ",") + if len(parts) == 0 { + continue + } + + nm := parts[0] + if nm == "-" { + continue + } + if nm == "" { // empty string means we want to use the Go name + nm = targetDes.Name + } + + idx[nm] = targetDes.Name + reverseIdx[targetDes.Name] = nm + } + } +} + +func newNameIndex(tpe reflect.Type) nameIndex { + var idx = make(map[string]string, tpe.NumField()) + var reverseIdx = make(map[string]string, tpe.NumField()) + + buildnameIndex(tpe, idx, reverseIdx) + return nameIndex{jsonNames: idx, goNames: reverseIdx} +} + +// GetJSONNames gets all the json property names for a type +func (n *NameProvider) GetJSONNames(subject interface{}) []string { + n.lock.Lock() + defer n.lock.Unlock() + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + + res := make([]string, 0, len(names.jsonNames)) + for k := range names.jsonNames { + res = append(res, k) + } + return res +} + +// GetJSONName gets the json name for a go property name +func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetJSONNameForType(tpe, name) +} + +// GetJSONNameForType gets the json name for a go property name on a given type +func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.goNames[name] + return nme, ok +} + +func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { + names := newNameIndex(tpe) + n.index[tpe] = names + return names +} + +// GetGoName gets the go name for a json property name +func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { + tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() + return n.GetGoNameForType(tpe, name) +} + +// GetGoNameForType gets the go name for a given type for a json property name +func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { + n.lock.Lock() + defer n.lock.Unlock() + names, ok := n.index[tpe] + if !ok { + names = n.makeNameIndex(tpe) + } + nme, ok := names.jsonNames[name] + return nme, ok +} diff --git a/vendor/github.com/go-openapi/swag/loading.go b/vendor/github.com/go-openapi/swag/loading.go new file mode 100644 index 000000000..9a6040972 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/loading.go @@ -0,0 +1,120 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "fmt" + "io/ioutil" + "log" + "net/http" + "net/url" + "path/filepath" + "runtime" + "strings" + "time" +) + +// LoadHTTPTimeout the default timeout for load requests +var LoadHTTPTimeout = 30 * time.Second + +// LoadHTTPBasicAuthUsername the username to use when load requests require basic auth +var LoadHTTPBasicAuthUsername = "" + +// LoadHTTPBasicAuthPassword the password to use when load requests require basic auth +var LoadHTTPBasicAuthPassword = "" + +// LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests +var LoadHTTPCustomHeaders = map[string]string{} + +// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in +func LoadFromFileOrHTTP(path string) ([]byte, error) { + return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path) +} + +// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in +// timeout arg allows for per request overriding of the request timeout +func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) { + return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(timeout))(path) +} + +// LoadStrategy returns a loader function for a given path or uri +func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { + if strings.HasPrefix(path, "http") { + return remote + } + return func(pth string) ([]byte, error) { + upth, err := pathUnescape(pth) + if err != nil { + return nil, err + } + + if strings.HasPrefix(pth, `file://`) { + if runtime.GOOS == "windows" { + // support for canonical file URIs on windows. + // Zero tolerance here for dodgy URIs. + u, _ := url.Parse(upth) + if u.Host != "" { + // assume UNC name (volume share) + // file://host/share/folder\... ==> \\host\share\path\folder + // NOTE: UNC port not yet supported + upth = strings.Join([]string{`\`, u.Host, u.Path}, `\`) + } else { + // file:///c:/folder/... ==> just remove the leading slash + upth = strings.TrimPrefix(upth, `file:///`) + } + } else { + upth = strings.TrimPrefix(upth, `file://`) + } + } + + return local(filepath.FromSlash(upth)) + } +} + +func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { + return func(path string) ([]byte, error) { + client := &http.Client{Timeout: timeout} + req, err := http.NewRequest("GET", path, nil) // nolint: noctx + if err != nil { + return nil, err + } + + if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" { + req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword) + } + + for key, val := range LoadHTTPCustomHeaders { + req.Header.Set(key, val) + } + + resp, err := client.Do(req) + defer func() { + if resp != nil { + if e := resp.Body.Close(); e != nil { + log.Println(e) + } + } + }() + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status) + } + + return ioutil.ReadAll(resp.Body) + } +} diff --git a/vendor/github.com/go-openapi/swag/name_lexem.go b/vendor/github.com/go-openapi/swag/name_lexem.go new file mode 100644 index 000000000..aa7f6a9bb --- /dev/null +++ b/vendor/github.com/go-openapi/swag/name_lexem.go @@ -0,0 +1,87 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import "unicode" + +type ( + nameLexem interface { + GetUnsafeGoName() string + GetOriginal() string + IsInitialism() bool + } + + initialismNameLexem struct { + original string + matchedInitialism string + } + + casualNameLexem struct { + original string + } +) + +func newInitialismNameLexem(original, matchedInitialism string) *initialismNameLexem { + return &initialismNameLexem{ + original: original, + matchedInitialism: matchedInitialism, + } +} + +func newCasualNameLexem(original string) *casualNameLexem { + return &casualNameLexem{ + original: original, + } +} + +func (l *initialismNameLexem) GetUnsafeGoName() string { + return l.matchedInitialism +} + +func (l *casualNameLexem) GetUnsafeGoName() string { + var first rune + var rest string + for i, orig := range l.original { + if i == 0 { + first = orig + continue + } + if i > 0 { + rest = l.original[i:] + break + } + } + if len(l.original) > 1 { + return string(unicode.ToUpper(first)) + lower(rest) + } + + return l.original +} + +func (l *initialismNameLexem) GetOriginal() string { + return l.original +} + +func (l *casualNameLexem) GetOriginal() string { + return l.original +} + +func (l *initialismNameLexem) IsInitialism() bool { + return true +} + +func (l *casualNameLexem) IsInitialism() bool { + return false +} diff --git a/vendor/github.com/go-openapi/swag/net.go b/vendor/github.com/go-openapi/swag/net.go new file mode 100644 index 000000000..821235f84 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/net.go @@ -0,0 +1,38 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "net" + "strconv" +) + +// SplitHostPort splits a network address into a host and a port. +// The port is -1 when there is no port to be found +func SplitHostPort(addr string) (host string, port int, err error) { + h, p, err := net.SplitHostPort(addr) + if err != nil { + return "", -1, err + } + if p == "" { + return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} + } + + pi, err := strconv.Atoi(p) + if err != nil { + return "", -1, err + } + return h, pi, nil +} diff --git a/vendor/github.com/go-openapi/swag/path.go b/vendor/github.com/go-openapi/swag/path.go new file mode 100644 index 000000000..941bd0176 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/path.go @@ -0,0 +1,59 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "os" + "path/filepath" + "runtime" + "strings" +) + +const ( + // GOPATHKey represents the env key for gopath + GOPATHKey = "GOPATH" +) + +// FindInSearchPath finds a package in a provided lists of paths +func FindInSearchPath(searchPath, pkg string) string { + pathsList := filepath.SplitList(searchPath) + for _, path := range pathsList { + if evaluatedPath, err := filepath.EvalSymlinks(filepath.Join(path, "src", pkg)); err == nil { + if _, err := os.Stat(evaluatedPath); err == nil { + return evaluatedPath + } + } + } + return "" +} + +// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT +func FindInGoSearchPath(pkg string) string { + return FindInSearchPath(FullGoSearchPath(), pkg) +} + +// FullGoSearchPath gets the search paths for finding packages +func FullGoSearchPath() string { + allPaths := os.Getenv(GOPATHKey) + if allPaths == "" { + allPaths = filepath.Join(os.Getenv("HOME"), "go") + } + if allPaths != "" { + allPaths = strings.Join([]string{allPaths, runtime.GOROOT()}, ":") + } else { + allPaths = runtime.GOROOT() + } + return allPaths +} diff --git a/vendor/github.com/go-openapi/swag/post_go18.go b/vendor/github.com/go-openapi/swag/post_go18.go new file mode 100644 index 000000000..c2e686d31 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/post_go18.go @@ -0,0 +1,23 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.8 + +package swag + +import "net/url" + +func pathUnescape(path string) (string, error) { + return url.PathUnescape(path) +} diff --git a/vendor/github.com/go-openapi/swag/post_go19.go b/vendor/github.com/go-openapi/swag/post_go19.go new file mode 100644 index 000000000..eb2f2d8bc --- /dev/null +++ b/vendor/github.com/go-openapi/swag/post_go19.go @@ -0,0 +1,67 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build go1.9 + +package swag + +import ( + "sort" + "sync" +) + +// indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms. +// Since go1.9, this may be implemented with sync.Map. +type indexOfInitialisms struct { + sortMutex *sync.Mutex + index *sync.Map +} + +func newIndexOfInitialisms() *indexOfInitialisms { + return &indexOfInitialisms{ + sortMutex: new(sync.Mutex), + index: new(sync.Map), + } +} + +func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms { + m.sortMutex.Lock() + defer m.sortMutex.Unlock() + for k, v := range initial { + m.index.Store(k, v) + } + return m +} + +func (m *indexOfInitialisms) isInitialism(key string) bool { + _, ok := m.index.Load(key) + return ok +} + +func (m *indexOfInitialisms) add(key string) *indexOfInitialisms { + m.index.Store(key, true) + return m +} + +func (m *indexOfInitialisms) sorted() (result []string) { + m.sortMutex.Lock() + defer m.sortMutex.Unlock() + m.index.Range(func(key, value interface{}) bool { + k := key.(string) + result = append(result, k) + return true + }) + sort.Sort(sort.Reverse(byInitialism(result))) + return +} diff --git a/vendor/github.com/go-openapi/swag/pre_go18.go b/vendor/github.com/go-openapi/swag/pre_go18.go new file mode 100644 index 000000000..6607f3393 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/pre_go18.go @@ -0,0 +1,23 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.8 + +package swag + +import "net/url" + +func pathUnescape(path string) (string, error) { + return url.QueryUnescape(path) +} diff --git a/vendor/github.com/go-openapi/swag/pre_go19.go b/vendor/github.com/go-openapi/swag/pre_go19.go new file mode 100644 index 000000000..4bae187d1 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/pre_go19.go @@ -0,0 +1,69 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.9 + +package swag + +import ( + "sort" + "sync" +) + +// indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms. +// Before go1.9, this may be implemented with a mutex on the map. +type indexOfInitialisms struct { + getMutex *sync.Mutex + index map[string]bool +} + +func newIndexOfInitialisms() *indexOfInitialisms { + return &indexOfInitialisms{ + getMutex: new(sync.Mutex), + index: make(map[string]bool, 50), + } +} + +func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms { + m.getMutex.Lock() + defer m.getMutex.Unlock() + for k, v := range initial { + m.index[k] = v + } + return m +} + +func (m *indexOfInitialisms) isInitialism(key string) bool { + m.getMutex.Lock() + defer m.getMutex.Unlock() + _, ok := m.index[key] + return ok +} + +func (m *indexOfInitialisms) add(key string) *indexOfInitialisms { + m.getMutex.Lock() + defer m.getMutex.Unlock() + m.index[key] = true + return m +} + +func (m *indexOfInitialisms) sorted() (result []string) { + m.getMutex.Lock() + defer m.getMutex.Unlock() + for k := range m.index { + result = append(result, k) + } + sort.Sort(sort.Reverse(byInitialism(result))) + return +} diff --git a/vendor/github.com/go-openapi/swag/split.go b/vendor/github.com/go-openapi/swag/split.go new file mode 100644 index 000000000..a1825fb7d --- /dev/null +++ b/vendor/github.com/go-openapi/swag/split.go @@ -0,0 +1,262 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "unicode" +) + +var nameReplaceTable = map[rune]string{ + '@': "At ", + '&': "And ", + '|': "Pipe ", + '$': "Dollar ", + '!': "Bang ", + '-': "", + '_': "", +} + +type ( + splitter struct { + postSplitInitialismCheck bool + initialisms []string + } + + splitterOption func(*splitter) *splitter +) + +// split calls the splitter; splitter provides more control and post options +func split(str string) []string { + lexems := newSplitter().split(str) + result := make([]string, 0, len(lexems)) + + for _, lexem := range lexems { + result = append(result, lexem.GetOriginal()) + } + + return result + +} + +func (s *splitter) split(str string) []nameLexem { + return s.toNameLexems(str) +} + +func newSplitter(options ...splitterOption) *splitter { + splitter := &splitter{ + postSplitInitialismCheck: false, + initialisms: initialisms, + } + + for _, option := range options { + splitter = option(splitter) + } + + return splitter +} + +// withPostSplitInitialismCheck allows to catch initialisms after main split process +func withPostSplitInitialismCheck(s *splitter) *splitter { + s.postSplitInitialismCheck = true + return s +} + +type ( + initialismMatch struct { + start, end int + body []rune + complete bool + } + initialismMatches []*initialismMatch +) + +func (s *splitter) toNameLexems(name string) []nameLexem { + nameRunes := []rune(name) + matches := s.gatherInitialismMatches(nameRunes) + return s.mapMatchesToNameLexems(nameRunes, matches) +} + +func (s *splitter) gatherInitialismMatches(nameRunes []rune) initialismMatches { + matches := make(initialismMatches, 0) + + for currentRunePosition, currentRune := range nameRunes { + newMatches := make(initialismMatches, 0, len(matches)) + + // check current initialism matches + for _, match := range matches { + if keepCompleteMatch := match.complete; keepCompleteMatch { + newMatches = append(newMatches, match) + continue + } + + // drop failed match + currentMatchRune := match.body[currentRunePosition-match.start] + if !s.initialismRuneEqual(currentMatchRune, currentRune) { + continue + } + + // try to complete ongoing match + if currentRunePosition-match.start == len(match.body)-1 { + // we are close; the next step is to check the symbol ahead + // if it is a small letter, then it is not the end of match + // but beginning of the next word + + if currentRunePosition < len(nameRunes)-1 { + nextRune := nameRunes[currentRunePosition+1] + if newWord := unicode.IsLower(nextRune); newWord { + // oh ok, it was the start of a new word + continue + } + } + + match.complete = true + match.end = currentRunePosition + } + + newMatches = append(newMatches, match) + } + + // check for new initialism matches + for _, initialism := range s.initialisms { + initialismRunes := []rune(initialism) + if s.initialismRuneEqual(initialismRunes[0], currentRune) { + newMatches = append(newMatches, &initialismMatch{ + start: currentRunePosition, + body: initialismRunes, + complete: false, + }) + } + } + + matches = newMatches + } + + return matches +} + +func (s *splitter) mapMatchesToNameLexems(nameRunes []rune, matches initialismMatches) []nameLexem { + nameLexems := make([]nameLexem, 0) + + var lastAcceptedMatch *initialismMatch + for _, match := range matches { + if !match.complete { + continue + } + + if firstMatch := lastAcceptedMatch == nil; firstMatch { + nameLexems = append(nameLexems, s.breakCasualString(nameRunes[:match.start])...) + nameLexems = append(nameLexems, s.breakInitialism(string(match.body))) + + lastAcceptedMatch = match + + continue + } + + if overlappedMatch := match.start <= lastAcceptedMatch.end; overlappedMatch { + continue + } + + middle := nameRunes[lastAcceptedMatch.end+1 : match.start] + nameLexems = append(nameLexems, s.breakCasualString(middle)...) + nameLexems = append(nameLexems, s.breakInitialism(string(match.body))) + + lastAcceptedMatch = match + } + + // we have not found any accepted matches + if lastAcceptedMatch == nil { + return s.breakCasualString(nameRunes) + } + + if lastAcceptedMatch.end+1 != len(nameRunes) { + rest := nameRunes[lastAcceptedMatch.end+1:] + nameLexems = append(nameLexems, s.breakCasualString(rest)...) + } + + return nameLexems +} + +func (s *splitter) initialismRuneEqual(a, b rune) bool { + return a == b +} + +func (s *splitter) breakInitialism(original string) nameLexem { + return newInitialismNameLexem(original, original) +} + +func (s *splitter) breakCasualString(str []rune) []nameLexem { + segments := make([]nameLexem, 0) + currentSegment := "" + + addCasualNameLexem := func(original string) { + segments = append(segments, newCasualNameLexem(original)) + } + + addInitialismNameLexem := func(original, match string) { + segments = append(segments, newInitialismNameLexem(original, match)) + } + + addNameLexem := func(original string) { + if s.postSplitInitialismCheck { + for _, initialism := range s.initialisms { + if upper(initialism) == upper(original) { + addInitialismNameLexem(original, initialism) + return + } + } + } + + addCasualNameLexem(original) + } + + for _, rn := range string(str) { + if replace, found := nameReplaceTable[rn]; found { + if currentSegment != "" { + addNameLexem(currentSegment) + currentSegment = "" + } + + if replace != "" { + addNameLexem(replace) + } + + continue + } + + if !unicode.In(rn, unicode.L, unicode.M, unicode.N, unicode.Pc) { + if currentSegment != "" { + addNameLexem(currentSegment) + currentSegment = "" + } + + continue + } + + if unicode.IsUpper(rn) { + if currentSegment != "" { + addNameLexem(currentSegment) + } + currentSegment = "" + } + + currentSegment += string(rn) + } + + if currentSegment != "" { + addNameLexem(currentSegment) + } + + return segments +} diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go new file mode 100644 index 000000000..193702f2c --- /dev/null +++ b/vendor/github.com/go-openapi/swag/util.go @@ -0,0 +1,385 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "reflect" + "strings" + "unicode" +) + +// commonInitialisms are common acronyms that are kept as whole uppercased words. +var commonInitialisms *indexOfInitialisms + +// initialisms is a slice of sorted initialisms +var initialisms []string + +var isInitialism func(string) bool + +// GoNamePrefixFunc sets an optional rule to prefix go names +// which do not start with a letter. +// +// e.g. to help convert "123" into "{prefix}123" +// +// The default is to prefix with "X" +var GoNamePrefixFunc func(string) string + +func init() { + // Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769 + var configuredInitialisms = map[string]bool{ + "ACL": true, + "API": true, + "ASCII": true, + "CPU": true, + "CSS": true, + "DNS": true, + "EOF": true, + "GUID": true, + "HTML": true, + "HTTPS": true, + "HTTP": true, + "ID": true, + "IP": true, + "IPv4": true, + "IPv6": true, + "JSON": true, + "LHS": true, + "OAI": true, + "QPS": true, + "RAM": true, + "RHS": true, + "RPC": true, + "SLA": true, + "SMTP": true, + "SQL": true, + "SSH": true, + "TCP": true, + "TLS": true, + "TTL": true, + "UDP": true, + "UI": true, + "UID": true, + "UUID": true, + "URI": true, + "URL": true, + "UTF8": true, + "VM": true, + "XML": true, + "XMPP": true, + "XSRF": true, + "XSS": true, + } + + // a thread-safe index of initialisms + commonInitialisms = newIndexOfInitialisms().load(configuredInitialisms) + initialisms = commonInitialisms.sorted() + + // a test function + isInitialism = commonInitialisms.isInitialism +} + +const ( + // collectionFormatComma = "csv" + collectionFormatSpace = "ssv" + collectionFormatTab = "tsv" + collectionFormatPipe = "pipes" + collectionFormatMulti = "multi" +) + +// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute): +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +func JoinByFormat(data []string, format string) []string { + if len(data) == 0 { + return data + } + var sep string + switch format { + case collectionFormatSpace: + sep = " " + case collectionFormatTab: + sep = "\t" + case collectionFormatPipe: + sep = "|" + case collectionFormatMulti: + return data + default: + sep = "," + } + return []string{strings.Join(data, sep)} +} + +// SplitByFormat splits a string by a known format: +// ssv: space separated value +// tsv: tab separated value +// pipes: pipe (|) separated value +// csv: comma separated value (default) +// +func SplitByFormat(data, format string) []string { + if data == "" { + return nil + } + var sep string + switch format { + case collectionFormatSpace: + sep = " " + case collectionFormatTab: + sep = "\t" + case collectionFormatPipe: + sep = "|" + case collectionFormatMulti: + return nil + default: + sep = "," + } + var result []string + for _, s := range strings.Split(data, sep) { + if ts := strings.TrimSpace(s); ts != "" { + result = append(result, ts) + } + } + return result +} + +type byInitialism []string + +func (s byInitialism) Len() int { + return len(s) +} +func (s byInitialism) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} +func (s byInitialism) Less(i, j int) bool { + if len(s[i]) != len(s[j]) { + return len(s[i]) < len(s[j]) + } + + return strings.Compare(s[i], s[j]) > 0 +} + +// Removes leading whitespaces +func trim(str string) string { + return strings.Trim(str, " ") +} + +// Shortcut to strings.ToUpper() +func upper(str string) string { + return strings.ToUpper(trim(str)) +} + +// Shortcut to strings.ToLower() +func lower(str string) string { + return strings.ToLower(trim(str)) +} + +// Camelize an uppercased word +func Camelize(word string) (camelized string) { + for pos, ru := range []rune(word) { + if pos > 0 { + camelized += string(unicode.ToLower(ru)) + } else { + camelized += string(unicode.ToUpper(ru)) + } + } + return +} + +// ToFileName lowercases and underscores a go type name +func ToFileName(name string) string { + in := split(name) + out := make([]string, 0, len(in)) + + for _, w := range in { + out = append(out, lower(w)) + } + + return strings.Join(out, "_") +} + +// ToCommandName lowercases and underscores a go type name +func ToCommandName(name string) string { + in := split(name) + out := make([]string, 0, len(in)) + + for _, w := range in { + out = append(out, lower(w)) + } + return strings.Join(out, "-") +} + +// ToHumanNameLower represents a code name as a human series of words +func ToHumanNameLower(name string) string { + in := newSplitter(withPostSplitInitialismCheck).split(name) + out := make([]string, 0, len(in)) + + for _, w := range in { + if !w.IsInitialism() { + out = append(out, lower(w.GetOriginal())) + } else { + out = append(out, w.GetOriginal()) + } + } + + return strings.Join(out, " ") +} + +// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized +func ToHumanNameTitle(name string) string { + in := newSplitter(withPostSplitInitialismCheck).split(name) + + out := make([]string, 0, len(in)) + for _, w := range in { + original := w.GetOriginal() + if !w.IsInitialism() { + out = append(out, Camelize(original)) + } else { + out = append(out, original) + } + } + return strings.Join(out, " ") +} + +// ToJSONName camelcases a name which can be underscored or pascal cased +func ToJSONName(name string) string { + in := split(name) + out := make([]string, 0, len(in)) + + for i, w := range in { + if i == 0 { + out = append(out, lower(w)) + continue + } + out = append(out, Camelize(w)) + } + return strings.Join(out, "") +} + +// ToVarName camelcases a name which can be underscored or pascal cased +func ToVarName(name string) string { + res := ToGoName(name) + if isInitialism(res) { + return lower(res) + } + if len(res) <= 1 { + return lower(res) + } + return lower(res[:1]) + res[1:] +} + +// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes +func ToGoName(name string) string { + lexems := newSplitter(withPostSplitInitialismCheck).split(name) + + result := "" + for _, lexem := range lexems { + goName := lexem.GetUnsafeGoName() + + // to support old behavior + if lexem.IsInitialism() { + goName = upper(goName) + } + result += goName + } + + if len(result) > 0 { + // Only prefix with X when the first character isn't an ascii letter + first := []rune(result)[0] + if !unicode.IsLetter(first) || (first > unicode.MaxASCII && !unicode.IsUpper(first)) { + if GoNamePrefixFunc == nil { + return "X" + result + } + result = GoNamePrefixFunc(name) + result + } + first = []rune(result)[0] + if unicode.IsLetter(first) && !unicode.IsUpper(first) { + result = string(append([]rune{unicode.ToUpper(first)}, []rune(result)[1:]...)) + } + } + + return result +} + +// ContainsStrings searches a slice of strings for a case-sensitive match +func ContainsStrings(coll []string, item string) bool { + for _, a := range coll { + if a == item { + return true + } + } + return false +} + +// ContainsStringsCI searches a slice of strings for a case-insensitive match +func ContainsStringsCI(coll []string, item string) bool { + for _, a := range coll { + if strings.EqualFold(a, item) { + return true + } + } + return false +} + +type zeroable interface { + IsZero() bool +} + +// IsZero returns true when the value passed into the function is a zero value. +// This allows for safer checking of interface values. +func IsZero(data interface{}) bool { + // check for things that have an IsZero method instead + if vv, ok := data.(zeroable); ok { + return vv.IsZero() + } + // continue with slightly more complex reflection + v := reflect.ValueOf(data) + switch v.Kind() { + case reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + case reflect.Struct, reflect.Array: + return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) + case reflect.Invalid: + return true + } + return false +} + +// AddInitialisms add additional initialisms +func AddInitialisms(words ...string) { + for _, word := range words { + // commonInitialisms[upper(word)] = true + commonInitialisms.add(upper(word)) + } + // sort again + initialisms = commonInitialisms.sorted() +} + +// CommandLineOptionsGroup represents a group of user-defined command line options +type CommandLineOptionsGroup struct { + ShortDescription string + LongDescription string + Options interface{} +} diff --git a/vendor/github.com/go-openapi/swag/yaml.go b/vendor/github.com/go-openapi/swag/yaml.go new file mode 100644 index 000000000..ec9691440 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/yaml.go @@ -0,0 +1,246 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swag + +import ( + "encoding/json" + "fmt" + "path/filepath" + "strconv" + + "github.com/mailru/easyjson/jlexer" + "github.com/mailru/easyjson/jwriter" + yaml "gopkg.in/yaml.v2" +) + +// YAMLMatcher matches yaml +func YAMLMatcher(path string) bool { + ext := filepath.Ext(path) + return ext == ".yaml" || ext == ".yml" +} + +// YAMLToJSON converts YAML unmarshaled data into json compatible data +func YAMLToJSON(data interface{}) (json.RawMessage, error) { + jm, err := transformData(data) + if err != nil { + return nil, err + } + b, err := WriteJSON(jm) + return json.RawMessage(b), err +} + +// BytesToYAMLDoc converts a byte slice into a YAML document +func BytesToYAMLDoc(data []byte) (interface{}, error) { + var canary map[interface{}]interface{} // validate this is an object and not a different type + if err := yaml.Unmarshal(data, &canary); err != nil { + return nil, err + } + + var document yaml.MapSlice // preserve order that is present in the document + if err := yaml.Unmarshal(data, &document); err != nil { + return nil, err + } + return document, nil +} + +// JSONMapSlice represent a JSON object, with the order of keys maintained +type JSONMapSlice []JSONMapItem + +// MarshalJSON renders a JSONMapSlice as JSON +func (s JSONMapSlice) MarshalJSON() ([]byte, error) { + w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} + s.MarshalEasyJSON(w) + return w.BuildBytes() +} + +// MarshalEasyJSON renders a JSONMapSlice as JSON, using easyJSON +func (s JSONMapSlice) MarshalEasyJSON(w *jwriter.Writer) { + w.RawByte('{') + + ln := len(s) + last := ln - 1 + for i := 0; i < ln; i++ { + s[i].MarshalEasyJSON(w) + if i != last { // last item + w.RawByte(',') + } + } + + w.RawByte('}') +} + +// UnmarshalJSON makes a JSONMapSlice from JSON +func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{Data: data} + s.UnmarshalEasyJSON(&l) + return l.Error() +} + +// UnmarshalEasyJSON makes a JSONMapSlice from JSON, using easyJSON +func (s *JSONMapSlice) UnmarshalEasyJSON(in *jlexer.Lexer) { + if in.IsNull() { + in.Skip() + return + } + + var result JSONMapSlice + in.Delim('{') + for !in.IsDelim('}') { + var mi JSONMapItem + mi.UnmarshalEasyJSON(in) + result = append(result, mi) + } + *s = result +} + +// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice +type JSONMapItem struct { + Key string + Value interface{} +} + +// MarshalJSON renders a JSONMapItem as JSON +func (s JSONMapItem) MarshalJSON() ([]byte, error) { + w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} + s.MarshalEasyJSON(w) + return w.BuildBytes() +} + +// MarshalEasyJSON renders a JSONMapItem as JSON, using easyJSON +func (s JSONMapItem) MarshalEasyJSON(w *jwriter.Writer) { + w.String(s.Key) + w.RawByte(':') + w.Raw(WriteJSON(s.Value)) +} + +// UnmarshalJSON makes a JSONMapItem from JSON +func (s *JSONMapItem) UnmarshalJSON(data []byte) error { + l := jlexer.Lexer{Data: data} + s.UnmarshalEasyJSON(&l) + return l.Error() +} + +// UnmarshalEasyJSON makes a JSONMapItem from JSON, using easyJSON +func (s *JSONMapItem) UnmarshalEasyJSON(in *jlexer.Lexer) { + key := in.UnsafeString() + in.WantColon() + value := in.Interface() + in.WantComma() + s.Key = key + s.Value = value +} + +func transformData(input interface{}) (out interface{}, err error) { + format := func(t interface{}) (string, error) { + switch k := t.(type) { + case string: + return k, nil + case uint: + return strconv.FormatUint(uint64(k), 10), nil + case uint8: + return strconv.FormatUint(uint64(k), 10), nil + case uint16: + return strconv.FormatUint(uint64(k), 10), nil + case uint32: + return strconv.FormatUint(uint64(k), 10), nil + case uint64: + return strconv.FormatUint(k, 10), nil + case int: + return strconv.Itoa(k), nil + case int8: + return strconv.FormatInt(int64(k), 10), nil + case int16: + return strconv.FormatInt(int64(k), 10), nil + case int32: + return strconv.FormatInt(int64(k), 10), nil + case int64: + return strconv.FormatInt(k, 10), nil + default: + return "", fmt.Errorf("unexpected map key type, got: %T", k) + } + } + + switch in := input.(type) { + case yaml.MapSlice: + + o := make(JSONMapSlice, len(in)) + for i, mi := range in { + var nmi JSONMapItem + if nmi.Key, err = format(mi.Key); err != nil { + return nil, err + } + + v, ert := transformData(mi.Value) + if ert != nil { + return nil, ert + } + nmi.Value = v + o[i] = nmi + } + return o, nil + case map[interface{}]interface{}: + o := make(JSONMapSlice, 0, len(in)) + for ke, va := range in { + var nmi JSONMapItem + if nmi.Key, err = format(ke); err != nil { + return nil, err + } + + v, ert := transformData(va) + if ert != nil { + return nil, ert + } + nmi.Value = v + o = append(o, nmi) + } + return o, nil + case []interface{}: + len1 := len(in) + o := make([]interface{}, len1) + for i := 0; i < len1; i++ { + o[i], err = transformData(in[i]) + if err != nil { + return nil, err + } + } + return o, nil + } + return input, nil +} + +// YAMLDoc loads a yaml document from either http or a file and converts it to json +func YAMLDoc(path string) (json.RawMessage, error) { + yamlDoc, err := YAMLData(path) + if err != nil { + return nil, err + } + + data, err := YAMLToJSON(yamlDoc) + if err != nil { + return nil, err + } + + return data, nil +} + +// YAMLData loads a yaml document from either http or a file +func YAMLData(path string) (interface{}, error) { + data, err := LoadFromFileOrHTTP(path) + if err != nil { + return nil, err + } + + return BytesToYAMLDoc(data) +} diff --git a/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/golang/protobuf/AUTHORS deleted file mode 100644 index 15167cd74..000000000 --- a/vendor/github.com/golang/protobuf/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/golang/protobuf/CONTRIBUTORS deleted file mode 100644 index 1c4577e96..000000000 --- a/vendor/github.com/golang/protobuf/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 0f646931a..000000000 --- a/vendor/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/golang/protobuf/proto/buffer.go b/vendor/github.com/golang/protobuf/proto/buffer.go deleted file mode 100644 index e810e6fea..000000000 --- a/vendor/github.com/golang/protobuf/proto/buffer.go +++ /dev/null @@ -1,324 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "errors" - "fmt" - - "google.golang.org/protobuf/encoding/prototext" - "google.golang.org/protobuf/encoding/protowire" - "google.golang.org/protobuf/runtime/protoimpl" -) - -const ( - WireVarint = 0 - WireFixed32 = 5 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 -) - -// EncodeVarint returns the varint encoded bytes of v. -func EncodeVarint(v uint64) []byte { - return protowire.AppendVarint(nil, v) -} - -// SizeVarint returns the length of the varint encoded bytes of v. -// This is equal to len(EncodeVarint(v)). -func SizeVarint(v uint64) int { - return protowire.SizeVarint(v) -} - -// DecodeVarint parses a varint encoded integer from b, -// returning the integer value and the length of the varint. -// It returns (0, 0) if there is a parse error. -func DecodeVarint(b []byte) (uint64, int) { - v, n := protowire.ConsumeVarint(b) - if n < 0 { - return 0, 0 - } - return v, n -} - -// Buffer is a buffer for encoding and decoding the protobuf wire format. -// It may be reused between invocations to reduce memory usage. -type Buffer struct { - buf []byte - idx int - deterministic bool -} - -// NewBuffer allocates a new Buffer initialized with buf, -// where the contents of buf are considered the unread portion of the buffer. -func NewBuffer(buf []byte) *Buffer { - return &Buffer{buf: buf} -} - -// SetDeterministic specifies whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexographical order. This is an implementation detail and -// subject to change. -func (b *Buffer) SetDeterministic(deterministic bool) { - b.deterministic = deterministic -} - -// SetBuf sets buf as the internal buffer, -// where the contents of buf are considered the unread portion of the buffer. -func (b *Buffer) SetBuf(buf []byte) { - b.buf = buf - b.idx = 0 -} - -// Reset clears the internal buffer of all written and unread data. -func (b *Buffer) Reset() { - b.buf = b.buf[:0] - b.idx = 0 -} - -// Bytes returns the internal buffer. -func (b *Buffer) Bytes() []byte { - return b.buf -} - -// Unread returns the unread portion of the buffer. -func (b *Buffer) Unread() []byte { - return b.buf[b.idx:] -} - -// Marshal appends the wire-format encoding of m to the buffer. -func (b *Buffer) Marshal(m Message) error { - var err error - b.buf, err = marshalAppend(b.buf, m, b.deterministic) - return err -} - -// Unmarshal parses the wire-format message in the buffer and -// places the decoded results in m. -// It does not reset m before unmarshaling. -func (b *Buffer) Unmarshal(m Message) error { - err := UnmarshalMerge(b.Unread(), m) - b.idx = len(b.buf) - return err -} - -type unknownFields struct{ XXX_unrecognized protoimpl.UnknownFields } - -func (m *unknownFields) String() string { panic("not implemented") } -func (m *unknownFields) Reset() { panic("not implemented") } -func (m *unknownFields) ProtoMessage() { panic("not implemented") } - -// DebugPrint dumps the encoded bytes of b with a header and footer including s -// to stdout. This is only intended for debugging. -func (*Buffer) DebugPrint(s string, b []byte) { - m := MessageReflect(new(unknownFields)) - m.SetUnknown(b) - b, _ = prototext.MarshalOptions{AllowPartial: true, Indent: "\t"}.Marshal(m.Interface()) - fmt.Printf("==== %s ====\n%s==== %s ====\n", s, b, s) -} - -// EncodeVarint appends an unsigned varint encoding to the buffer. -func (b *Buffer) EncodeVarint(v uint64) error { - b.buf = protowire.AppendVarint(b.buf, v) - return nil -} - -// EncodeZigzag32 appends a 32-bit zig-zag varint encoding to the buffer. -func (b *Buffer) EncodeZigzag32(v uint64) error { - return b.EncodeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) -} - -// EncodeZigzag64 appends a 64-bit zig-zag varint encoding to the buffer. -func (b *Buffer) EncodeZigzag64(v uint64) error { - return b.EncodeVarint(uint64((uint64(v) << 1) ^ uint64((int64(v) >> 63)))) -} - -// EncodeFixed32 appends a 32-bit little-endian integer to the buffer. -func (b *Buffer) EncodeFixed32(v uint64) error { - b.buf = protowire.AppendFixed32(b.buf, uint32(v)) - return nil -} - -// EncodeFixed64 appends a 64-bit little-endian integer to the buffer. -func (b *Buffer) EncodeFixed64(v uint64) error { - b.buf = protowire.AppendFixed64(b.buf, uint64(v)) - return nil -} - -// EncodeRawBytes appends a length-prefixed raw bytes to the buffer. -func (b *Buffer) EncodeRawBytes(v []byte) error { - b.buf = protowire.AppendBytes(b.buf, v) - return nil -} - -// EncodeStringBytes appends a length-prefixed raw bytes to the buffer. -// It does not validate whether v contains valid UTF-8. -func (b *Buffer) EncodeStringBytes(v string) error { - b.buf = protowire.AppendString(b.buf, v) - return nil -} - -// EncodeMessage appends a length-prefixed encoded message to the buffer. -func (b *Buffer) EncodeMessage(m Message) error { - var err error - b.buf = protowire.AppendVarint(b.buf, uint64(Size(m))) - b.buf, err = marshalAppend(b.buf, m, b.deterministic) - return err -} - -// DecodeVarint consumes an encoded unsigned varint from the buffer. -func (b *Buffer) DecodeVarint() (uint64, error) { - v, n := protowire.ConsumeVarint(b.buf[b.idx:]) - if n < 0 { - return 0, protowire.ParseError(n) - } - b.idx += n - return uint64(v), nil -} - -// DecodeZigzag32 consumes an encoded 32-bit zig-zag varint from the buffer. -func (b *Buffer) DecodeZigzag32() (uint64, error) { - v, err := b.DecodeVarint() - if err != nil { - return 0, err - } - return uint64((uint32(v) >> 1) ^ uint32((int32(v&1)<<31)>>31)), nil -} - -// DecodeZigzag64 consumes an encoded 64-bit zig-zag varint from the buffer. -func (b *Buffer) DecodeZigzag64() (uint64, error) { - v, err := b.DecodeVarint() - if err != nil { - return 0, err - } - return uint64((uint64(v) >> 1) ^ uint64((int64(v&1)<<63)>>63)), nil -} - -// DecodeFixed32 consumes a 32-bit little-endian integer from the buffer. -func (b *Buffer) DecodeFixed32() (uint64, error) { - v, n := protowire.ConsumeFixed32(b.buf[b.idx:]) - if n < 0 { - return 0, protowire.ParseError(n) - } - b.idx += n - return uint64(v), nil -} - -// DecodeFixed64 consumes a 64-bit little-endian integer from the buffer. -func (b *Buffer) DecodeFixed64() (uint64, error) { - v, n := protowire.ConsumeFixed64(b.buf[b.idx:]) - if n < 0 { - return 0, protowire.ParseError(n) - } - b.idx += n - return uint64(v), nil -} - -// DecodeRawBytes consumes a length-prefixed raw bytes from the buffer. -// If alloc is specified, it returns a copy the raw bytes -// rather than a sub-slice of the buffer. -func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) { - v, n := protowire.ConsumeBytes(b.buf[b.idx:]) - if n < 0 { - return nil, protowire.ParseError(n) - } - b.idx += n - if alloc { - v = append([]byte(nil), v...) - } - return v, nil -} - -// DecodeStringBytes consumes a length-prefixed raw bytes from the buffer. -// It does not validate whether the raw bytes contain valid UTF-8. -func (b *Buffer) DecodeStringBytes() (string, error) { - v, n := protowire.ConsumeString(b.buf[b.idx:]) - if n < 0 { - return "", protowire.ParseError(n) - } - b.idx += n - return v, nil -} - -// DecodeMessage consumes a length-prefixed message from the buffer. -// It does not reset m before unmarshaling. -func (b *Buffer) DecodeMessage(m Message) error { - v, err := b.DecodeRawBytes(false) - if err != nil { - return err - } - return UnmarshalMerge(v, m) -} - -// DecodeGroup consumes a message group from the buffer. -// It assumes that the start group marker has already been consumed and -// consumes all bytes until (and including the end group marker). -// It does not reset m before unmarshaling. -func (b *Buffer) DecodeGroup(m Message) error { - v, n, err := consumeGroup(b.buf[b.idx:]) - if err != nil { - return err - } - b.idx += n - return UnmarshalMerge(v, m) -} - -// consumeGroup parses b until it finds an end group marker, returning -// the raw bytes of the message (excluding the end group marker) and the -// the total length of the message (including the end group marker). -func consumeGroup(b []byte) ([]byte, int, error) { - b0 := b - depth := 1 // assume this follows a start group marker - for { - _, wtyp, tagLen := protowire.ConsumeTag(b) - if tagLen < 0 { - return nil, 0, protowire.ParseError(tagLen) - } - b = b[tagLen:] - - var valLen int - switch wtyp { - case protowire.VarintType: - _, valLen = protowire.ConsumeVarint(b) - case protowire.Fixed32Type: - _, valLen = protowire.ConsumeFixed32(b) - case protowire.Fixed64Type: - _, valLen = protowire.ConsumeFixed64(b) - case protowire.BytesType: - _, valLen = protowire.ConsumeBytes(b) - case protowire.StartGroupType: - depth++ - case protowire.EndGroupType: - depth-- - default: - return nil, 0, errors.New("proto: cannot parse reserved wire type") - } - if valLen < 0 { - return nil, 0, protowire.ParseError(valLen) - } - b = b[valLen:] - - if depth == 0 { - return b0[:len(b0)-len(b)-tagLen], len(b0) - len(b), nil - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/defaults.go b/vendor/github.com/golang/protobuf/proto/defaults.go deleted file mode 100644 index d399bf069..000000000 --- a/vendor/github.com/golang/protobuf/proto/defaults.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "google.golang.org/protobuf/reflect/protoreflect" -) - -// SetDefaults sets unpopulated scalar fields to their default values. -// Fields within a oneof are not set even if they have a default value. -// SetDefaults is recursively called upon any populated message fields. -func SetDefaults(m Message) { - if m != nil { - setDefaults(MessageReflect(m)) - } -} - -func setDefaults(m protoreflect.Message) { - fds := m.Descriptor().Fields() - for i := 0; i < fds.Len(); i++ { - fd := fds.Get(i) - if !m.Has(fd) { - if fd.HasDefault() && fd.ContainingOneof() == nil { - v := fd.Default() - if fd.Kind() == protoreflect.BytesKind { - v = protoreflect.ValueOf(append([]byte(nil), v.Bytes()...)) // copy the default bytes - } - m.Set(fd, v) - } - continue - } - } - - m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - switch { - // Handle singular message. - case fd.Cardinality() != protoreflect.Repeated: - if fd.Message() != nil { - setDefaults(m.Get(fd).Message()) - } - // Handle list of messages. - case fd.IsList(): - if fd.Message() != nil { - ls := m.Get(fd).List() - for i := 0; i < ls.Len(); i++ { - setDefaults(ls.Get(i).Message()) - } - } - // Handle map of messages. - case fd.IsMap(): - if fd.MapValue().Message() != nil { - ms := m.Get(fd).Map() - ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool { - setDefaults(v.Message()) - return true - }) - } - } - return true - }) -} diff --git a/vendor/github.com/golang/protobuf/proto/deprecated.go b/vendor/github.com/golang/protobuf/proto/deprecated.go deleted file mode 100644 index e8db57e09..000000000 --- a/vendor/github.com/golang/protobuf/proto/deprecated.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "encoding/json" - "errors" - "fmt" - "strconv" - - protoV2 "google.golang.org/protobuf/proto" -) - -var ( - // Deprecated: No longer returned. - ErrNil = errors.New("proto: Marshal called with nil") - - // Deprecated: No longer returned. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") - - // Deprecated: No longer returned. - ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") -) - -// Deprecated: Do not use. -type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } - -// Deprecated: Do not use. -func GetStats() Stats { return Stats{} } - -// Deprecated: Do not use. -func MarshalMessageSet(interface{}) ([]byte, error) { - return nil, errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func UnmarshalMessageSet([]byte, interface{}) error { - return errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func MarshalMessageSetJSON(interface{}) ([]byte, error) { - return nil, errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func UnmarshalMessageSetJSON([]byte, interface{}) error { - return errors.New("proto: not implemented") -} - -// Deprecated: Do not use. -func RegisterMessageSetType(Message, int32, string) {} - -// Deprecated: Do not use. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// Deprecated: Do not use. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// Deprecated: Do not use; this type existed for intenal-use only. -type InternalMessageInfo struct{} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) DiscardUnknown(m Message) { - DiscardUnknown(m) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Marshal(b []byte, m Message, deterministic bool) ([]byte, error) { - return protoV2.MarshalOptions{Deterministic: deterministic}.MarshalAppend(b, MessageV2(m)) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Merge(dst, src Message) { - protoV2.Merge(MessageV2(dst), MessageV2(src)) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Size(m Message) int { - return protoV2.Size(MessageV2(m)) -} - -// Deprecated: Do not use; this method existed for intenal-use only. -func (*InternalMessageInfo) Unmarshal(m Message, b []byte) error { - return protoV2.UnmarshalOptions{Merge: true}.Unmarshal(b, MessageV2(m)) -} diff --git a/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/golang/protobuf/proto/discard.go deleted file mode 100644 index 2187e877f..000000000 --- a/vendor/github.com/golang/protobuf/proto/discard.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "google.golang.org/protobuf/reflect/protoreflect" -) - -// DiscardUnknown recursively discards all unknown fields from this message -// and all embedded messages. -// -// When unmarshaling a message with unrecognized fields, the tags and values -// of such fields are preserved in the Message. This allows a later call to -// marshal to be able to produce a message that continues to have those -// unrecognized fields. To avoid this, DiscardUnknown is used to -// explicitly clear the unknown fields after unmarshaling. -func DiscardUnknown(m Message) { - if m != nil { - discardUnknown(MessageReflect(m)) - } -} - -func discardUnknown(m protoreflect.Message) { - m.Range(func(fd protoreflect.FieldDescriptor, val protoreflect.Value) bool { - switch { - // Handle singular message. - case fd.Cardinality() != protoreflect.Repeated: - if fd.Message() != nil { - discardUnknown(m.Get(fd).Message()) - } - // Handle list of messages. - case fd.IsList(): - if fd.Message() != nil { - ls := m.Get(fd).List() - for i := 0; i < ls.Len(); i++ { - discardUnknown(ls.Get(i).Message()) - } - } - // Handle map of messages. - case fd.IsMap(): - if fd.MapValue().Message() != nil { - ms := m.Get(fd).Map() - ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool { - discardUnknown(v.Message()) - return true - }) - } - } - return true - }) - - // Discard unknown fields. - if len(m.GetUnknown()) > 0 { - m.SetUnknown(nil) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index 42fc120c9..000000000 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "errors" - "fmt" - "reflect" - - "google.golang.org/protobuf/encoding/protowire" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - "google.golang.org/protobuf/runtime/protoiface" - "google.golang.org/protobuf/runtime/protoimpl" -) - -type ( - // ExtensionDesc represents an extension descriptor and - // is used to interact with an extension field in a message. - // - // Variables of this type are generated in code by protoc-gen-go. - ExtensionDesc = protoimpl.ExtensionInfo - - // ExtensionRange represents a range of message extensions. - // Used in code generated by protoc-gen-go. - ExtensionRange = protoiface.ExtensionRangeV1 - - // Deprecated: Do not use; this is an internal type. - Extension = protoimpl.ExtensionFieldV1 - - // Deprecated: Do not use; this is an internal type. - XXX_InternalExtensions = protoimpl.ExtensionFields -) - -// ErrMissingExtension reports whether the extension was not present. -var ErrMissingExtension = errors.New("proto: missing extension") - -var errNotExtendable = errors.New("proto: not an extendable proto.Message") - -// HasExtension reports whether the extension field is present in m -// either as an explicitly populated field or as an unknown field. -func HasExtension(m Message, xt *ExtensionDesc) (has bool) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return false - } - - // Check whether any populated known field matches the field number. - xtd := xt.TypeDescriptor() - if isValidExtension(mr.Descriptor(), xtd) { - has = mr.Has(xtd) - } else { - mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { - has = int32(fd.Number()) == xt.Field - return !has - }) - } - - // Check whether any unknown field matches the field number. - for b := mr.GetUnknown(); !has && len(b) > 0; { - num, _, n := protowire.ConsumeField(b) - has = int32(num) == xt.Field - b = b[n:] - } - return has -} - -// ClearExtension removes the extension field from m -// either as an explicitly populated field or as an unknown field. -func ClearExtension(m Message, xt *ExtensionDesc) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return - } - - xtd := xt.TypeDescriptor() - if isValidExtension(mr.Descriptor(), xtd) { - mr.Clear(xtd) - } else { - mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { - if int32(fd.Number()) == xt.Field { - mr.Clear(fd) - return false - } - return true - }) - } - clearUnknown(mr, fieldNum(xt.Field)) -} - -// ClearAllExtensions clears all extensions from m. -// This includes populated fields and unknown fields in the extension range. -func ClearAllExtensions(m Message) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return - } - - mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { - if fd.IsExtension() { - mr.Clear(fd) - } - return true - }) - clearUnknown(mr, mr.Descriptor().ExtensionRanges()) -} - -// GetExtension retrieves a proto2 extended field from m. -// -// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), -// then GetExtension parses the encoded field and returns a Go value of the specified type. -// If the field is not present, then the default value is returned (if one is specified), -// otherwise ErrMissingExtension is reported. -// -// If the descriptor is type incomplete (i.e., ExtensionDesc.ExtensionType is nil), -// then GetExtension returns the raw encoded bytes for the extension field. -func GetExtension(m Message, xt *ExtensionDesc) (interface{}, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { - return nil, errNotExtendable - } - - // Retrieve the unknown fields for this extension field. - var bo protoreflect.RawFields - for bi := mr.GetUnknown(); len(bi) > 0; { - num, _, n := protowire.ConsumeField(bi) - if int32(num) == xt.Field { - bo = append(bo, bi[:n]...) - } - bi = bi[n:] - } - - // For type incomplete descriptors, only retrieve the unknown fields. - if xt.ExtensionType == nil { - return []byte(bo), nil - } - - // If the extension field only exists as unknown fields, unmarshal it. - // This is rarely done since proto.Unmarshal eagerly unmarshals extensions. - xtd := xt.TypeDescriptor() - if !isValidExtension(mr.Descriptor(), xtd) { - return nil, fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m) - } - if !mr.Has(xtd) && len(bo) > 0 { - m2 := mr.New() - if err := (proto.UnmarshalOptions{ - Resolver: extensionResolver{xt}, - }.Unmarshal(bo, m2.Interface())); err != nil { - return nil, err - } - if m2.Has(xtd) { - mr.Set(xtd, m2.Get(xtd)) - clearUnknown(mr, fieldNum(xt.Field)) - } - } - - // Check whether the message has the extension field set or a default. - var pv protoreflect.Value - switch { - case mr.Has(xtd): - pv = mr.Get(xtd) - case xtd.HasDefault(): - pv = xtd.Default() - default: - return nil, ErrMissingExtension - } - - v := xt.InterfaceOf(pv) - rv := reflect.ValueOf(v) - if isScalarKind(rv.Kind()) { - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - v = rv2.Interface() - } - return v, nil -} - -// extensionResolver is a custom extension resolver that stores a single -// extension type that takes precedence over the global registry. -type extensionResolver struct{ xt protoreflect.ExtensionType } - -func (r extensionResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { - if xtd := r.xt.TypeDescriptor(); xtd.FullName() == field { - return r.xt, nil - } - return protoregistry.GlobalTypes.FindExtensionByName(field) -} - -func (r extensionResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { - if xtd := r.xt.TypeDescriptor(); xtd.ContainingMessage().FullName() == message && xtd.Number() == field { - return r.xt, nil - } - return protoregistry.GlobalTypes.FindExtensionByNumber(message, field) -} - -// GetExtensions returns a list of the extensions values present in m, -// corresponding with the provided list of extension descriptors, xts. -// If an extension is missing in m, the corresponding value is nil. -func GetExtensions(m Message, xts []*ExtensionDesc) ([]interface{}, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return nil, errNotExtendable - } - - vs := make([]interface{}, len(xts)) - for i, xt := range xts { - v, err := GetExtension(m, xt) - if err != nil { - if err == ErrMissingExtension { - continue - } - return vs, err - } - vs[i] = v - } - return vs, nil -} - -// SetExtension sets an extension field in m to the provided value. -func SetExtension(m Message, xt *ExtensionDesc, v interface{}) error { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { - return errNotExtendable - } - - rv := reflect.ValueOf(v) - if reflect.TypeOf(v) != reflect.TypeOf(xt.ExtensionType) { - return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", v, xt.ExtensionType) - } - if rv.Kind() == reflect.Ptr { - if rv.IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", v) - } - if isScalarKind(rv.Elem().Kind()) { - v = rv.Elem().Interface() - } - } - - xtd := xt.TypeDescriptor() - if !isValidExtension(mr.Descriptor(), xtd) { - return fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m) - } - mr.Set(xtd, xt.ValueOf(v)) - clearUnknown(mr, fieldNum(xt.Field)) - return nil -} - -// SetRawExtension inserts b into the unknown fields of m. -// -// Deprecated: Use Message.ProtoReflect.SetUnknown instead. -func SetRawExtension(m Message, fnum int32, b []byte) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return - } - - // Verify that the raw field is valid. - for b0 := b; len(b0) > 0; { - num, _, n := protowire.ConsumeField(b0) - if int32(num) != fnum { - panic(fmt.Sprintf("mismatching field number: got %d, want %d", num, fnum)) - } - b0 = b0[n:] - } - - ClearExtension(m, &ExtensionDesc{Field: fnum}) - mr.SetUnknown(append(mr.GetUnknown(), b...)) -} - -// ExtensionDescs returns a list of extension descriptors found in m, -// containing descriptors for both populated extension fields in m and -// also unknown fields of m that are in the extension range. -// For the later case, an type incomplete descriptor is provided where only -// the ExtensionDesc.Field field is populated. -// The order of the extension descriptors is undefined. -func ExtensionDescs(m Message) ([]*ExtensionDesc, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { - return nil, errNotExtendable - } - - // Collect a set of known extension descriptors. - extDescs := make(map[protoreflect.FieldNumber]*ExtensionDesc) - mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - if fd.IsExtension() { - xt := fd.(protoreflect.ExtensionTypeDescriptor) - if xd, ok := xt.Type().(*ExtensionDesc); ok { - extDescs[fd.Number()] = xd - } - } - return true - }) - - // Collect a set of unknown extension descriptors. - extRanges := mr.Descriptor().ExtensionRanges() - for b := mr.GetUnknown(); len(b) > 0; { - num, _, n := protowire.ConsumeField(b) - if extRanges.Has(num) && extDescs[num] == nil { - extDescs[num] = nil - } - b = b[n:] - } - - // Transpose the set of descriptors into a list. - var xts []*ExtensionDesc - for num, xt := range extDescs { - if xt == nil { - xt = &ExtensionDesc{Field: int32(num)} - } - xts = append(xts, xt) - } - return xts, nil -} - -// isValidExtension reports whether xtd is a valid extension descriptor for md. -func isValidExtension(md protoreflect.MessageDescriptor, xtd protoreflect.ExtensionTypeDescriptor) bool { - return xtd.ContainingMessage() == md && md.ExtensionRanges().Has(xtd.Number()) -} - -// isScalarKind reports whether k is a protobuf scalar kind (except bytes). -// This function exists for historical reasons since the representation of -// scalars differs between v1 and v2, where v1 uses *T and v2 uses T. -func isScalarKind(k reflect.Kind) bool { - switch k { - case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: - return true - default: - return false - } -} - -// clearUnknown removes unknown fields from m where remover.Has reports true. -func clearUnknown(m protoreflect.Message, remover interface { - Has(protoreflect.FieldNumber) bool -}) { - var bo protoreflect.RawFields - for bi := m.GetUnknown(); len(bi) > 0; { - num, _, n := protowire.ConsumeField(bi) - if !remover.Has(num) { - bo = append(bo, bi[:n]...) - } - bi = bi[n:] - } - if bi := m.GetUnknown(); len(bi) != len(bo) { - m.SetUnknown(bo) - } -} - -type fieldNum protoreflect.FieldNumber - -func (n1 fieldNum) Has(n2 protoreflect.FieldNumber) bool { - return protoreflect.FieldNumber(n1) == n2 -} diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index dcdc2202f..000000000 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "fmt" - "reflect" - "strconv" - "strings" - "sync" - - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/runtime/protoimpl" -) - -// StructProperties represents protocol buffer type information for a -// generated protobuf message in the open-struct API. -// -// Deprecated: Do not use. -type StructProperties struct { - // Prop are the properties for each field. - // - // Fields belonging to a oneof are stored in OneofTypes instead, with a - // single Properties representing the parent oneof held here. - // - // The order of Prop matches the order of fields in the Go struct. - // Struct fields that are not related to protobufs have a "XXX_" prefix - // in the Properties.Name and must be ignored by the user. - Prop []*Properties - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the protobuf field name. - OneofTypes map[string]*OneofProperties -} - -// Properties represents the type information for a protobuf message field. -// -// Deprecated: Do not use. -type Properties struct { - // Name is a placeholder name with little meaningful semantic value. - // If the name has an "XXX_" prefix, the entire Properties must be ignored. - Name string - // OrigName is the protobuf field name or oneof name. - OrigName string - // JSONName is the JSON name for the protobuf field. - JSONName string - // Enum is a placeholder name for enums. - // For historical reasons, this is neither the Go name for the enum, - // nor the protobuf name for the enum. - Enum string // Deprecated: Do not use. - // Weak contains the full name of the weakly referenced message. - Weak string - // Wire is a string representation of the wire type. - Wire string - // WireType is the protobuf wire type for the field. - WireType int - // Tag is the protobuf field number. - Tag int - // Required reports whether this is a required field. - Required bool - // Optional reports whether this is a optional field. - Optional bool - // Repeated reports whether this is a repeated field. - Repeated bool - // Packed reports whether this is a packed repeated field of scalars. - Packed bool - // Proto3 reports whether this field operates under the proto3 syntax. - Proto3 bool - // Oneof reports whether this field belongs within a oneof. - Oneof bool - - // Default is the default value in string form. - Default string - // HasDefault reports whether the field has a default value. - HasDefault bool - - // MapKeyProp is the properties for the key field for a map field. - MapKeyProp *Properties - // MapValProp is the properties for the value field for a map field. - MapValProp *Properties -} - -// OneofProperties represents the type information for a protobuf oneof. -// -// Deprecated: Do not use. -type OneofProperties struct { - // Type is a pointer to the generated wrapper type for the field value. - // This is nil for messages that are not in the open-struct API. - Type reflect.Type - // Field is the index into StructProperties.Prop for the containing oneof. - Field int - // Prop is the properties for the field. - Prop *Properties -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s += "," + strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != "" { - s += ",json=" + p.JSONName - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if len(p.Weak) > 0 { - s += ",weak=" + p.Weak - } - if p.Proto3 { - s += ",proto3" - } - if p.Oneof { - s += ",oneof" - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(tag string) { - // For example: "bytes,49,opt,name=foo,def=hello!" - for len(tag) > 0 { - i := strings.IndexByte(tag, ',') - if i < 0 { - i = len(tag) - } - switch s := tag[:i]; { - case strings.HasPrefix(s, "name="): - p.OrigName = s[len("name="):] - case strings.HasPrefix(s, "json="): - p.JSONName = s[len("json="):] - case strings.HasPrefix(s, "enum="): - p.Enum = s[len("enum="):] - case strings.HasPrefix(s, "weak="): - p.Weak = s[len("weak="):] - case strings.Trim(s, "0123456789") == "": - n, _ := strconv.ParseUint(s, 10, 32) - p.Tag = int(n) - case s == "opt": - p.Optional = true - case s == "req": - p.Required = true - case s == "rep": - p.Repeated = true - case s == "varint" || s == "zigzag32" || s == "zigzag64": - p.Wire = s - p.WireType = WireVarint - case s == "fixed32": - p.Wire = s - p.WireType = WireFixed32 - case s == "fixed64": - p.Wire = s - p.WireType = WireFixed64 - case s == "bytes": - p.Wire = s - p.WireType = WireBytes - case s == "group": - p.Wire = s - p.WireType = WireStartGroup - case s == "packed": - p.Packed = true - case s == "proto3": - p.Proto3 = true - case s == "oneof": - p.Oneof = true - case strings.HasPrefix(s, "def="): - // The default tag is special in that everything afterwards is the - // default regardless of the presence of commas. - p.HasDefault = true - p.Default, i = tag[len("def="):], len(tag) - } - tag = strings.TrimPrefix(tag[i:], ",") - } -} - -// Init populates the properties from a protocol buffer struct tag. -// -// Deprecated: Do not use. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.Name = name - p.OrigName = name - if tag == "" { - return - } - p.Parse(tag) - - if typ != nil && typ.Kind() == reflect.Map { - p.MapKeyProp = new(Properties) - p.MapKeyProp.Init(nil, "Key", f.Tag.Get("protobuf_key"), nil) - p.MapValProp = new(Properties) - p.MapValProp.Init(nil, "Value", f.Tag.Get("protobuf_val"), nil) - } -} - -var propertiesCache sync.Map // map[reflect.Type]*StructProperties - -// GetProperties returns the list of properties for the type represented by t, -// which must be a generated protocol buffer message in the open-struct API, -// where protobuf message fields are represented by exported Go struct fields. -// -// Deprecated: Use protobuf reflection instead. -func GetProperties(t reflect.Type) *StructProperties { - if p, ok := propertiesCache.Load(t); ok { - return p.(*StructProperties) - } - p, _ := propertiesCache.LoadOrStore(t, newProperties(t)) - return p.(*StructProperties) -} - -func newProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t)) - } - - var hasOneof bool - prop := new(StructProperties) - - // Construct a list of properties for each field in the struct. - for i := 0; i < t.NumField(); i++ { - p := new(Properties) - f := t.Field(i) - tagField := f.Tag.Get("protobuf") - p.Init(f.Type, f.Name, tagField, &f) - - tagOneof := f.Tag.Get("protobuf_oneof") - if tagOneof != "" { - hasOneof = true - p.OrigName = tagOneof - } - - // Rename unrelated struct fields with the "XXX_" prefix since so much - // user code simply checks for this to exclude special fields. - if tagField == "" && tagOneof == "" && !strings.HasPrefix(p.Name, "XXX_") { - p.Name = "XXX_" + p.Name - p.OrigName = "XXX_" + p.OrigName - } else if p.Weak != "" { - p.Name = p.OrigName // avoid possible "XXX_" prefix on weak field - } - - prop.Prop = append(prop.Prop, p) - } - - // Construct a mapping of oneof field names to properties. - if hasOneof { - var oneofWrappers []interface{} - if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok { - oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{}) - } - if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok { - oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{}) - } - if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(protoreflect.ProtoMessage); ok { - if m, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *protoimpl.MessageInfo }); ok { - oneofWrappers = m.ProtoMessageInfo().OneofWrappers - } - } - - prop.OneofTypes = make(map[string]*OneofProperties) - for _, wrapper := range oneofWrappers { - p := &OneofProperties{ - Type: reflect.ValueOf(wrapper).Type(), // *T - Prop: new(Properties), - } - f := p.Type.Elem().Field(0) - p.Prop.Name = f.Name - p.Prop.Parse(f.Tag.Get("protobuf")) - - // Determine the struct field that contains this oneof. - // Each wrapper is assignable to exactly one parent field. - var foundOneof bool - for i := 0; i < t.NumField() && !foundOneof; i++ { - if p.Type.AssignableTo(t.Field(i).Type) { - p.Field = i - foundOneof = true - } - } - if !foundOneof { - panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t)) - } - prop.OneofTypes[p.Prop.OrigName] = p - } - } - - return prop -} - -func (sp *StructProperties) Len() int { return len(sp.Prop) } -func (sp *StructProperties) Less(i, j int) bool { return false } -func (sp *StructProperties) Swap(i, j int) { return } diff --git a/vendor/github.com/golang/protobuf/proto/proto.go b/vendor/github.com/golang/protobuf/proto/proto.go deleted file mode 100644 index 5aee89c32..000000000 --- a/vendor/github.com/golang/protobuf/proto/proto.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package proto provides functionality for handling protocol buffer messages. -// In particular, it provides marshaling and unmarshaling between a protobuf -// message and the binary wire format. -// -// See https://developers.google.com/protocol-buffers/docs/gotutorial for -// more information. -// -// Deprecated: Use the "google.golang.org/protobuf/proto" package instead. -package proto - -import ( - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/runtime/protoiface" - "google.golang.org/protobuf/runtime/protoimpl" -) - -const ( - ProtoPackageIsVersion1 = true - ProtoPackageIsVersion2 = true - ProtoPackageIsVersion3 = true - ProtoPackageIsVersion4 = true -) - -// GeneratedEnum is any enum type generated by protoc-gen-go -// which is a named int32 kind. -// This type exists for documentation purposes. -type GeneratedEnum interface{} - -// GeneratedMessage is any message type generated by protoc-gen-go -// which is a pointer to a named struct kind. -// This type exists for documentation purposes. -type GeneratedMessage interface{} - -// Message is a protocol buffer message. -// -// This is the v1 version of the message interface and is marginally better -// than an empty interface as it lacks any method to programatically interact -// with the contents of the message. -// -// A v2 message is declared in "google.golang.org/protobuf/proto".Message and -// exposes protobuf reflection as a first-class feature of the interface. -// -// To convert a v1 message to a v2 message, use the MessageV2 function. -// To convert a v2 message to a v1 message, use the MessageV1 function. -type Message = protoiface.MessageV1 - -// MessageV1 converts either a v1 or v2 message to a v1 message. -// It returns nil if m is nil. -func MessageV1(m GeneratedMessage) protoiface.MessageV1 { - return protoimpl.X.ProtoMessageV1Of(m) -} - -// MessageV2 converts either a v1 or v2 message to a v2 message. -// It returns nil if m is nil. -func MessageV2(m GeneratedMessage) protoV2.Message { - return protoimpl.X.ProtoMessageV2Of(m) -} - -// MessageReflect returns a reflective view for a message. -// It returns nil if m is nil. -func MessageReflect(m Message) protoreflect.Message { - return protoimpl.X.MessageOf(m) -} - -// Marshaler is implemented by messages that can marshal themselves. -// This interface is used by the following functions: Size, Marshal, -// Buffer.Marshal, and Buffer.EncodeMessage. -// -// Deprecated: Do not implement. -type Marshaler interface { - // Marshal formats the encoded bytes of the message. - // It should be deterministic and emit valid protobuf wire data. - // The caller takes ownership of the returned buffer. - Marshal() ([]byte, error) -} - -// Unmarshaler is implemented by messages that can unmarshal themselves. -// This interface is used by the following functions: Unmarshal, UnmarshalMerge, -// Buffer.Unmarshal, Buffer.DecodeMessage, and Buffer.DecodeGroup. -// -// Deprecated: Do not implement. -type Unmarshaler interface { - // Unmarshal parses the encoded bytes of the protobuf wire input. - // The provided buffer is only valid for during method call. - // It should not reset the receiver message. - Unmarshal([]byte) error -} - -// Merger is implemented by messages that can merge themselves. -// This interface is used by the following functions: Clone and Merge. -// -// Deprecated: Do not implement. -type Merger interface { - // Merge merges the contents of src into the receiver message. - // It clones all data structures in src such that it aliases no mutable - // memory referenced by src. - Merge(src Message) -} - -// RequiredNotSetError is an error type returned when -// marshaling or unmarshaling a message with missing required fields. -type RequiredNotSetError struct { - err error -} - -func (e *RequiredNotSetError) Error() string { - if e.err != nil { - return e.err.Error() - } - return "proto: required field not set" -} -func (e *RequiredNotSetError) RequiredNotSet() bool { - return true -} - -func checkRequiredNotSet(m protoV2.Message) error { - if err := protoV2.CheckInitialized(m); err != nil { - return &RequiredNotSetError{err: err} - } - return nil -} - -// Clone returns a deep copy of src. -func Clone(src Message) Message { - return MessageV1(protoV2.Clone(MessageV2(src))) -} - -// Merge merges src into dst, which must be messages of the same type. -// -// Populated scalar fields in src are copied to dst, while populated -// singular messages in src are merged into dst by recursively calling Merge. -// The elements of every list field in src is appended to the corresponded -// list fields in dst. The entries of every map field in src is copied into -// the corresponding map field in dst, possibly replacing existing entries. -// The unknown fields of src are appended to the unknown fields of dst. -func Merge(dst, src Message) { - protoV2.Merge(MessageV2(dst), MessageV2(src)) -} - -// Equal reports whether two messages are equal. -// If two messages marshal to the same bytes under deterministic serialization, -// then Equal is guaranteed to report true. -// -// Two messages are equal if they are the same protobuf message type, -// have the same set of populated known and extension field values, -// and the same set of unknown fields values. -// -// Scalar values are compared with the equivalent of the == operator in Go, -// except bytes values which are compared using bytes.Equal and -// floating point values which specially treat NaNs as equal. -// Message values are compared by recursively calling Equal. -// Lists are equal if each element value is also equal. -// Maps are equal if they have the same set of keys, where the pair of values -// for each key is also equal. -func Equal(x, y Message) bool { - return protoV2.Equal(MessageV2(x), MessageV2(y)) -} - -func isMessageSet(md protoreflect.MessageDescriptor) bool { - ms, ok := md.(interface{ IsMessageSet() bool }) - return ok && ms.IsMessageSet() -} diff --git a/vendor/github.com/golang/protobuf/proto/registry.go b/vendor/github.com/golang/protobuf/proto/registry.go deleted file mode 100644 index 066b4323b..000000000 --- a/vendor/github.com/golang/protobuf/proto/registry.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "bytes" - "compress/gzip" - "fmt" - "io/ioutil" - "reflect" - "strings" - "sync" - - "google.golang.org/protobuf/reflect/protodesc" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - "google.golang.org/protobuf/runtime/protoimpl" -) - -// filePath is the path to the proto source file. -type filePath = string // e.g., "google/protobuf/descriptor.proto" - -// fileDescGZIP is the compressed contents of the encoded FileDescriptorProto. -type fileDescGZIP = []byte - -var fileCache sync.Map // map[filePath]fileDescGZIP - -// RegisterFile is called from generated code to register the compressed -// FileDescriptorProto with the file path for a proto source file. -// -// Deprecated: Use protoregistry.GlobalFiles.RegisterFile instead. -func RegisterFile(s filePath, d fileDescGZIP) { - // Decompress the descriptor. - zr, err := gzip.NewReader(bytes.NewReader(d)) - if err != nil { - panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err)) - } - b, err := ioutil.ReadAll(zr) - if err != nil { - panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err)) - } - - // Construct a protoreflect.FileDescriptor from the raw descriptor. - // Note that DescBuilder.Build automatically registers the constructed - // file descriptor with the v2 registry. - protoimpl.DescBuilder{RawDescriptor: b}.Build() - - // Locally cache the raw descriptor form for the file. - fileCache.Store(s, d) -} - -// FileDescriptor returns the compressed FileDescriptorProto given the file path -// for a proto source file. It returns nil if not found. -// -// Deprecated: Use protoregistry.GlobalFiles.FindFileByPath instead. -func FileDescriptor(s filePath) fileDescGZIP { - if v, ok := fileCache.Load(s); ok { - return v.(fileDescGZIP) - } - - // Find the descriptor in the v2 registry. - var b []byte - if fd, _ := protoregistry.GlobalFiles.FindFileByPath(s); fd != nil { - b, _ = Marshal(protodesc.ToFileDescriptorProto(fd)) - } - - // Locally cache the raw descriptor form for the file. - if len(b) > 0 { - v, _ := fileCache.LoadOrStore(s, protoimpl.X.CompressGZIP(b)) - return v.(fileDescGZIP) - } - return nil -} - -// enumName is the name of an enum. For historical reasons, the enum name is -// neither the full Go name nor the full protobuf name of the enum. -// The name is the dot-separated combination of just the proto package that the -// enum is declared within followed by the Go type name of the generated enum. -type enumName = string // e.g., "my.proto.package.GoMessage_GoEnum" - -// enumsByName maps enum values by name to their numeric counterpart. -type enumsByName = map[string]int32 - -// enumsByNumber maps enum values by number to their name counterpart. -type enumsByNumber = map[int32]string - -var enumCache sync.Map // map[enumName]enumsByName -var numFilesCache sync.Map // map[protoreflect.FullName]int - -// RegisterEnum is called from the generated code to register the mapping of -// enum value names to enum numbers for the enum identified by s. -// -// Deprecated: Use protoregistry.GlobalTypes.RegisterEnum instead. -func RegisterEnum(s enumName, _ enumsByNumber, m enumsByName) { - if _, ok := enumCache.Load(s); ok { - panic("proto: duplicate enum registered: " + s) - } - enumCache.Store(s, m) - - // This does not forward registration to the v2 registry since this API - // lacks sufficient information to construct a complete v2 enum descriptor. -} - -// EnumValueMap returns the mapping from enum value names to enum numbers for -// the enum of the given name. It returns nil if not found. -// -// Deprecated: Use protoregistry.GlobalTypes.FindEnumByName instead. -func EnumValueMap(s enumName) enumsByName { - if v, ok := enumCache.Load(s); ok { - return v.(enumsByName) - } - - // Check whether the cache is stale. If the number of files in the current - // package differs, then it means that some enums may have been recently - // registered upstream that we do not know about. - var protoPkg protoreflect.FullName - if i := strings.LastIndexByte(s, '.'); i >= 0 { - protoPkg = protoreflect.FullName(s[:i]) - } - v, _ := numFilesCache.Load(protoPkg) - numFiles, _ := v.(int) - if protoregistry.GlobalFiles.NumFilesByPackage(protoPkg) == numFiles { - return nil // cache is up-to-date; was not found earlier - } - - // Update the enum cache for all enums declared in the given proto package. - numFiles = 0 - protoregistry.GlobalFiles.RangeFilesByPackage(protoPkg, func(fd protoreflect.FileDescriptor) bool { - walkEnums(fd, func(ed protoreflect.EnumDescriptor) { - name := protoimpl.X.LegacyEnumName(ed) - if _, ok := enumCache.Load(name); !ok { - m := make(enumsByName) - evs := ed.Values() - for i := evs.Len() - 1; i >= 0; i-- { - ev := evs.Get(i) - m[string(ev.Name())] = int32(ev.Number()) - } - enumCache.LoadOrStore(name, m) - } - }) - numFiles++ - return true - }) - numFilesCache.Store(protoPkg, numFiles) - - // Check cache again for enum map. - if v, ok := enumCache.Load(s); ok { - return v.(enumsByName) - } - return nil -} - -// walkEnums recursively walks all enums declared in d. -func walkEnums(d interface { - Enums() protoreflect.EnumDescriptors - Messages() protoreflect.MessageDescriptors -}, f func(protoreflect.EnumDescriptor)) { - eds := d.Enums() - for i := eds.Len() - 1; i >= 0; i-- { - f(eds.Get(i)) - } - mds := d.Messages() - for i := mds.Len() - 1; i >= 0; i-- { - walkEnums(mds.Get(i), f) - } -} - -// messageName is the full name of protobuf message. -type messageName = string - -var messageTypeCache sync.Map // map[messageName]reflect.Type - -// RegisterType is called from generated code to register the message Go type -// for a message of the given name. -// -// Deprecated: Use protoregistry.GlobalTypes.RegisterMessage instead. -func RegisterType(m Message, s messageName) { - mt := protoimpl.X.LegacyMessageTypeOf(m, protoreflect.FullName(s)) - if err := protoregistry.GlobalTypes.RegisterMessage(mt); err != nil { - panic(err) - } - messageTypeCache.Store(s, reflect.TypeOf(m)) -} - -// RegisterMapType is called from generated code to register the Go map type -// for a protobuf message representing a map entry. -// -// Deprecated: Do not use. -func RegisterMapType(m interface{}, s messageName) { - t := reflect.TypeOf(m) - if t.Kind() != reflect.Map { - panic(fmt.Sprintf("invalid map kind: %v", t)) - } - if _, ok := messageTypeCache.Load(s); ok { - panic(fmt.Errorf("proto: duplicate proto message registered: %s", s)) - } - messageTypeCache.Store(s, t) -} - -// MessageType returns the message type for a named message. -// It returns nil if not found. -// -// Deprecated: Use protoregistry.GlobalTypes.FindMessageByName instead. -func MessageType(s messageName) reflect.Type { - if v, ok := messageTypeCache.Load(s); ok { - return v.(reflect.Type) - } - - // Derive the message type from the v2 registry. - var t reflect.Type - if mt, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(s)); mt != nil { - t = messageGoType(mt) - } - - // If we could not get a concrete type, it is possible that it is a - // pseudo-message for a map entry. - if t == nil { - d, _ := protoregistry.GlobalFiles.FindDescriptorByName(protoreflect.FullName(s)) - if md, _ := d.(protoreflect.MessageDescriptor); md != nil && md.IsMapEntry() { - kt := goTypeForField(md.Fields().ByNumber(1)) - vt := goTypeForField(md.Fields().ByNumber(2)) - t = reflect.MapOf(kt, vt) - } - } - - // Locally cache the message type for the given name. - if t != nil { - v, _ := messageTypeCache.LoadOrStore(s, t) - return v.(reflect.Type) - } - return nil -} - -func goTypeForField(fd protoreflect.FieldDescriptor) reflect.Type { - switch k := fd.Kind(); k { - case protoreflect.EnumKind: - if et, _ := protoregistry.GlobalTypes.FindEnumByName(fd.Enum().FullName()); et != nil { - return enumGoType(et) - } - return reflect.TypeOf(protoreflect.EnumNumber(0)) - case protoreflect.MessageKind, protoreflect.GroupKind: - if mt, _ := protoregistry.GlobalTypes.FindMessageByName(fd.Message().FullName()); mt != nil { - return messageGoType(mt) - } - return reflect.TypeOf((*protoreflect.Message)(nil)).Elem() - default: - return reflect.TypeOf(fd.Default().Interface()) - } -} - -func enumGoType(et protoreflect.EnumType) reflect.Type { - return reflect.TypeOf(et.New(0)) -} - -func messageGoType(mt protoreflect.MessageType) reflect.Type { - return reflect.TypeOf(MessageV1(mt.Zero().Interface())) -} - -// MessageName returns the full protobuf name for the given message type. -// -// Deprecated: Use protoreflect.MessageDescriptor.FullName instead. -func MessageName(m Message) messageName { - if m == nil { - return "" - } - if m, ok := m.(interface{ XXX_MessageName() messageName }); ok { - return m.XXX_MessageName() - } - return messageName(protoimpl.X.MessageDescriptorOf(m).FullName()) -} - -// RegisterExtension is called from the generated code to register -// the extension descriptor. -// -// Deprecated: Use protoregistry.GlobalTypes.RegisterExtension instead. -func RegisterExtension(d *ExtensionDesc) { - if err := protoregistry.GlobalTypes.RegisterExtension(d); err != nil { - panic(err) - } -} - -type extensionsByNumber = map[int32]*ExtensionDesc - -var extensionCache sync.Map // map[messageName]extensionsByNumber - -// RegisteredExtensions returns a map of the registered extensions for the -// provided protobuf message, indexed by the extension field number. -// -// Deprecated: Use protoregistry.GlobalTypes.RangeExtensionsByMessage instead. -func RegisteredExtensions(m Message) extensionsByNumber { - // Check whether the cache is stale. If the number of extensions for - // the given message differs, then it means that some extensions were - // recently registered upstream that we do not know about. - s := MessageName(m) - v, _ := extensionCache.Load(s) - xs, _ := v.(extensionsByNumber) - if protoregistry.GlobalTypes.NumExtensionsByMessage(protoreflect.FullName(s)) == len(xs) { - return xs // cache is up-to-date - } - - // Cache is stale, re-compute the extensions map. - xs = make(extensionsByNumber) - protoregistry.GlobalTypes.RangeExtensionsByMessage(protoreflect.FullName(s), func(xt protoreflect.ExtensionType) bool { - if xd, ok := xt.(*ExtensionDesc); ok { - xs[int32(xt.TypeDescriptor().Number())] = xd - } else { - // TODO: This implies that the protoreflect.ExtensionType is a - // custom type not generated by protoc-gen-go. We could try and - // convert the type to an ExtensionDesc. - } - return true - }) - extensionCache.Store(s, xs) - return xs -} diff --git a/vendor/github.com/golang/protobuf/proto/text_decode.go b/vendor/github.com/golang/protobuf/proto/text_decode.go deleted file mode 100644 index 47eb3e445..000000000 --- a/vendor/github.com/golang/protobuf/proto/text_decode.go +++ /dev/null @@ -1,801 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" - - "google.golang.org/protobuf/encoding/prototext" - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" -) - -const wrapTextUnmarshalV2 = false - -// ParseError is returned by UnmarshalText. -type ParseError struct { - Message string - - // Deprecated: Do not use. - Line, Offset int -} - -func (e *ParseError) Error() string { - if wrapTextUnmarshalV2 { - return e.Message - } - if e.Line == 1 { - return fmt.Sprintf("line 1.%d: %v", e.Offset, e.Message) - } - return fmt.Sprintf("line %d: %v", e.Line, e.Message) -} - -// UnmarshalText parses a proto text formatted string into m. -func UnmarshalText(s string, m Message) error { - if u, ok := m.(encoding.TextUnmarshaler); ok { - return u.UnmarshalText([]byte(s)) - } - - m.Reset() - mi := MessageV2(m) - - if wrapTextUnmarshalV2 { - err := prototext.UnmarshalOptions{ - AllowPartial: true, - }.Unmarshal([]byte(s), mi) - if err != nil { - return &ParseError{Message: err.Error()} - } - return checkRequiredNotSet(mi) - } else { - if err := newTextParser(s).unmarshalMessage(mi.ProtoReflect(), ""); err != nil { - return err - } - return checkRequiredNotSet(mi) - } -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) unmarshalMessage(m protoreflect.Message, terminator string) (err error) { - md := m.Descriptor() - fds := md.Fields() - - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - seen := make(map[protoreflect.FieldNumber]bool) - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - if err := p.unmarshalExtensionOrAny(m, seen); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := protoreflect.Name(tok.value) - fd := fds.ByName(name) - switch { - case fd == nil: - gd := fds.ByName(protoreflect.Name(strings.ToLower(string(name)))) - if gd != nil && gd.Kind() == protoreflect.GroupKind && gd.Message().Name() == name { - fd = gd - } - case fd.Kind() == protoreflect.GroupKind && fd.Message().Name() != name: - fd = nil - case fd.IsWeak() && fd.Message().IsPlaceholder(): - fd = nil - } - if fd == nil { - typeName := string(md.FullName()) - if m, ok := m.Interface().(Message); ok { - t := reflect.TypeOf(m) - if t.Kind() == reflect.Ptr { - typeName = t.Elem().String() - } - } - return p.errorf("unknown field name %q in %v", name, typeName) - } - if od := fd.ContainingOneof(); od != nil && m.WhichOneof(od) != nil { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, od.Name()) - } - if fd.Cardinality() != protoreflect.Repeated && seen[fd.Number()] { - return p.errorf("non-repeated field %q was repeated", fd.Name()) - } - seen[fd.Number()] = true - - // Consume any colon. - if err := p.checkForColon(fd); err != nil { - return err - } - - // Parse into the field. - v := m.Get(fd) - if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) { - v = m.Mutable(fd) - } - if v, err = p.unmarshalValue(v, fd); err != nil { - return err - } - m.Set(fd, v) - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - } - return nil -} - -func (p *textParser) unmarshalExtensionOrAny(m protoreflect.Message, seen map[protoreflect.FieldNumber]bool) error { - name, err := p.consumeExtensionOrAnyName() - if err != nil { - return err - } - - // If it contains a slash, it's an Any type URL. - if slashIdx := strings.LastIndex(name, "/"); slashIdx >= 0 { - tok := p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - - mt, err := protoregistry.GlobalTypes.FindMessageByURL(name) - if err != nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", name[slashIdx+len("/"):]) - } - m2 := mt.New() - if err := p.unmarshalMessage(m2, terminator); err != nil { - return err - } - b, err := protoV2.Marshal(m2.Interface()) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", name[slashIdx+len("/"):], err) - } - - urlFD := m.Descriptor().Fields().ByName("type_url") - valFD := m.Descriptor().Fields().ByName("value") - if seen[urlFD.Number()] { - return p.errorf("Any message unpacked multiple times, or %q already set", urlFD.Name()) - } - if seen[valFD.Number()] { - return p.errorf("Any message unpacked multiple times, or %q already set", valFD.Name()) - } - m.Set(urlFD, protoreflect.ValueOfString(name)) - m.Set(valFD, protoreflect.ValueOfBytes(b)) - seen[urlFD.Number()] = true - seen[valFD.Number()] = true - return nil - } - - xname := protoreflect.FullName(name) - xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname) - if xt == nil && isMessageSet(m.Descriptor()) { - xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension")) - } - if xt == nil { - return p.errorf("unrecognized extension %q", name) - } - fd := xt.TypeDescriptor() - if fd.ContainingMessage().FullName() != m.Descriptor().FullName() { - return p.errorf("extension field %q does not extend message %q", name, m.Descriptor().FullName()) - } - - if err := p.checkForColon(fd); err != nil { - return err - } - - v := m.Get(fd) - if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) { - v = m.Mutable(fd) - } - v, err = p.unmarshalValue(v, fd) - if err != nil { - return err - } - m.Set(fd, v) - return p.consumeOptionalSeparator() -} - -func (p *textParser) unmarshalValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == "" { - return v, p.errorf("unexpected EOF") - } - - switch { - case fd.IsList(): - lv := v.List() - var err error - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - vv := lv.NewElement() - vv, err = p.unmarshalSingularValue(vv, fd) - if err != nil { - return v, err - } - lv.Append(vv) - - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return v, p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return v, nil - } - - // One value of the repeated field. - p.back() - vv := lv.NewElement() - vv, err = p.unmarshalSingularValue(vv, fd) - if err != nil { - return v, err - } - lv.Append(vv) - return v, nil - case fd.IsMap(): - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return v, p.errorf("expected '{' or '<', found %q", tok.value) - } - - keyFD := fd.MapKey() - valFD := fd.MapValue() - - mv := v.Map() - kv := keyFD.Default() - vv := mv.NewValue() - for { - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == terminator { - break - } - var err error - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return v, err - } - if kv, err = p.unmarshalSingularValue(kv, keyFD); err != nil { - return v, err - } - if err := p.consumeOptionalSeparator(); err != nil { - return v, err - } - case "value": - if err := p.checkForColon(valFD); err != nil { - return v, err - } - if vv, err = p.unmarshalSingularValue(vv, valFD); err != nil { - return v, err - } - if err := p.consumeOptionalSeparator(); err != nil { - return v, err - } - default: - p.back() - return v, p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - mv.Set(kv.MapKey(), vv) - return v, nil - default: - p.back() - return p.unmarshalSingularValue(v, fd) - } -} - -func (p *textParser) unmarshalSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { - tok := p.next() - if tok.err != nil { - return v, tok.err - } - if tok.value == "" { - return v, p.errorf("unexpected EOF") - } - - switch fd.Kind() { - case protoreflect.BoolKind: - switch tok.value { - case "true", "1", "t", "True": - return protoreflect.ValueOfBool(true), nil - case "false", "0", "f", "False": - return protoreflect.ValueOfBool(false), nil - } - case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfInt32(int32(x)), nil - } - - // The C++ parser accepts large positive hex numbers that uses - // two's complement arithmetic to represent negative numbers. - // This feature is here for backwards compatibility with C++. - if strings.HasPrefix(tok.value, "0x") { - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfInt32(int32(-(int64(^x) + 1))), nil - } - } - case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - return protoreflect.ValueOfInt64(int64(x)), nil - } - - // The C++ parser accepts large positive hex numbers that uses - // two's complement arithmetic to represent negative numbers. - // This feature is here for backwards compatibility with C++. - if strings.HasPrefix(tok.value, "0x") { - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - return protoreflect.ValueOfInt64(int64(-(int64(^x) + 1))), nil - } - } - case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfUint32(uint32(x)), nil - } - case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - return protoreflect.ValueOfUint64(uint64(x)), nil - } - case protoreflect.FloatKind: - // Ignore 'f' for compatibility with output generated by C++, - // but don't remove 'f' when the value is "-inf" or "inf". - v := tok.value - if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" { - v = v[:len(v)-len("f")] - } - if x, err := strconv.ParseFloat(v, 32); err == nil { - return protoreflect.ValueOfFloat32(float32(x)), nil - } - case protoreflect.DoubleKind: - // Ignore 'f' for compatibility with output generated by C++, - // but don't remove 'f' when the value is "-inf" or "inf". - v := tok.value - if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" { - v = v[:len(v)-len("f")] - } - if x, err := strconv.ParseFloat(v, 64); err == nil { - return protoreflect.ValueOfFloat64(float64(x)), nil - } - case protoreflect.StringKind: - if isQuote(tok.value[0]) { - return protoreflect.ValueOfString(tok.unquoted), nil - } - case protoreflect.BytesKind: - if isQuote(tok.value[0]) { - return protoreflect.ValueOfBytes([]byte(tok.unquoted)), nil - } - case protoreflect.EnumKind: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - return protoreflect.ValueOfEnum(protoreflect.EnumNumber(x)), nil - } - vd := fd.Enum().Values().ByName(protoreflect.Name(tok.value)) - if vd != nil { - return protoreflect.ValueOfEnum(vd.Number()), nil - } - case protoreflect.MessageKind, protoreflect.GroupKind: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return v, p.errorf("expected '{' or '<', found %q", tok.value) - } - err := p.unmarshalMessage(v.Message(), terminator) - return v, err - default: - panic(fmt.Sprintf("invalid kind %v", fd.Kind())) - } - return v, p.errorf("invalid %v: %v", fd.Kind(), tok.value) -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(fd protoreflect.FieldDescriptor) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - if fd.Message() == nil { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -// consumeExtensionOrAnyName consumes an extension name or an Any type URL and -// the following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtensionOrAnyName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in unmarshalMessage to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -var errBadUTF8 = errors.New("proto: bad UTF-8") - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(rune(i)), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} diff --git a/vendor/github.com/golang/protobuf/proto/text_encode.go b/vendor/github.com/golang/protobuf/proto/text_encode.go deleted file mode 100644 index a31134eeb..000000000 --- a/vendor/github.com/golang/protobuf/proto/text_encode.go +++ /dev/null @@ -1,560 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - "bytes" - "encoding" - "fmt" - "io" - "math" - "sort" - "strings" - - "google.golang.org/protobuf/encoding/prototext" - "google.golang.org/protobuf/encoding/protowire" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" -) - -const wrapTextMarshalV2 = false - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line) - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes the proto text format of m to w. -func (tm *TextMarshaler) Marshal(w io.Writer, m Message) error { - b, err := tm.marshal(m) - if len(b) > 0 { - if _, err := w.Write(b); err != nil { - return err - } - } - return err -} - -// Text returns a proto text formatted string of m. -func (tm *TextMarshaler) Text(m Message) string { - b, _ := tm.marshal(m) - return string(b) -} - -func (tm *TextMarshaler) marshal(m Message) ([]byte, error) { - mr := MessageReflect(m) - if mr == nil || !mr.IsValid() { - return []byte(""), nil - } - - if wrapTextMarshalV2 { - if m, ok := m.(encoding.TextMarshaler); ok { - return m.MarshalText() - } - - opts := prototext.MarshalOptions{ - AllowPartial: true, - EmitUnknown: true, - } - if !tm.Compact { - opts.Indent = " " - } - if !tm.ExpandAny { - opts.Resolver = (*protoregistry.Types)(nil) - } - return opts.Marshal(mr.Interface()) - } else { - w := &textWriter{ - compact: tm.Compact, - expandAny: tm.ExpandAny, - complete: true, - } - - if m, ok := m.(encoding.TextMarshaler); ok { - b, err := m.MarshalText() - if err != nil { - return nil, err - } - w.Write(b) - return w.buf, nil - } - - err := w.writeMessage(mr) - return w.buf, err - } -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// MarshalText writes the proto text format of m to w. -func MarshalText(w io.Writer, m Message) error { return defaultTextMarshaler.Marshal(w, m) } - -// MarshalTextString returns a proto text formatted string of m. -func MarshalTextString(m Message) string { return defaultTextMarshaler.Text(m) } - -// CompactText writes the compact proto text format of m to w. -func CompactText(w io.Writer, m Message) error { return compactTextMarshaler.Marshal(w, m) } - -// CompactTextString returns a compact proto text formatted string of m. -func CompactTextString(m Message) string { return compactTextMarshaler.Text(m) } - -var ( - newline = []byte("\n") - endBraceNewline = []byte("}\n") - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - compact bool // same as TextMarshaler.Compact - expandAny bool // same as TextMarshaler.ExpandAny - complete bool // whether the current position is a complete line - indent int // indentation level; never negative - buf []byte -} - -func (w *textWriter) Write(p []byte) (n int, _ error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - w.buf = append(w.buf, p...) - w.complete = false - return len(p), nil - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - w.buf = append(w.buf, ' ') - n++ - } - w.buf = append(w.buf, frag...) - n += len(frag) - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - w.buf = append(w.buf, frag...) - n += len(frag) - if i+1 < len(frags) { - w.buf = append(w.buf, '\n') - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - w.buf = append(w.buf, c) - w.complete = c == '\n' - return nil -} - -func (w *textWriter) writeName(fd protoreflect.FieldDescriptor) { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - - if fd.Kind() != protoreflect.GroupKind { - w.buf = append(w.buf, fd.Name()...) - w.WriteByte(':') - } else { - // Use message type name for group field name. - w.buf = append(w.buf, fd.Message().Name()...) - } - - if !w.compact { - w.WriteByte(' ') - } -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (w *textWriter) writeProto3Any(m protoreflect.Message) (bool, error) { - md := m.Descriptor() - fdURL := md.Fields().ByName("type_url") - fdVal := md.Fields().ByName("value") - - url := m.Get(fdURL).String() - mt, err := protoregistry.GlobalTypes.FindMessageByURL(url) - if err != nil { - return false, nil - } - - b := m.Get(fdVal).Bytes() - m2 := mt.New() - if err := proto.Unmarshal(b, m2.Interface()); err != nil { - return false, nil - } - w.Write([]byte("[")) - if requiresQuotes(url) { - w.writeQuotedString(url) - } else { - w.Write([]byte(url)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.indent++ - } - if err := w.writeMessage(m2); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.indent-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (w *textWriter) writeMessage(m protoreflect.Message) error { - md := m.Descriptor() - if w.expandAny && md.FullName() == "google.protobuf.Any" { - if canExpand, err := w.writeProto3Any(m); canExpand { - return err - } - } - - fds := md.Fields() - for i := 0; i < fds.Len(); { - fd := fds.Get(i) - if od := fd.ContainingOneof(); od != nil { - fd = m.WhichOneof(od) - i += od.Fields().Len() - } else { - i++ - } - if fd == nil || !m.Has(fd) { - continue - } - - switch { - case fd.IsList(): - lv := m.Get(fd).List() - for j := 0; j < lv.Len(); j++ { - w.writeName(fd) - v := lv.Get(j) - if err := w.writeSingularValue(v, fd); err != nil { - return err - } - w.WriteByte('\n') - } - case fd.IsMap(): - kfd := fd.MapKey() - vfd := fd.MapValue() - mv := m.Get(fd).Map() - - type entry struct{ key, val protoreflect.Value } - var entries []entry - mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { - entries = append(entries, entry{k.Value(), v}) - return true - }) - sort.Slice(entries, func(i, j int) bool { - switch kfd.Kind() { - case protoreflect.BoolKind: - return !entries[i].key.Bool() && entries[j].key.Bool() - case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: - return entries[i].key.Int() < entries[j].key.Int() - case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind: - return entries[i].key.Uint() < entries[j].key.Uint() - case protoreflect.StringKind: - return entries[i].key.String() < entries[j].key.String() - default: - panic("invalid kind") - } - }) - for _, entry := range entries { - w.writeName(fd) - w.WriteByte('<') - if !w.compact { - w.WriteByte('\n') - } - w.indent++ - w.writeName(kfd) - if err := w.writeSingularValue(entry.key, kfd); err != nil { - return err - } - w.WriteByte('\n') - w.writeName(vfd) - if err := w.writeSingularValue(entry.val, vfd); err != nil { - return err - } - w.WriteByte('\n') - w.indent-- - w.WriteByte('>') - w.WriteByte('\n') - } - default: - w.writeName(fd) - if err := w.writeSingularValue(m.Get(fd), fd); err != nil { - return err - } - w.WriteByte('\n') - } - } - - if b := m.GetUnknown(); len(b) > 0 { - w.writeUnknownFields(b) - } - return w.writeExtensions(m) -} - -func (w *textWriter) writeSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) error { - switch fd.Kind() { - case protoreflect.FloatKind, protoreflect.DoubleKind: - switch vf := v.Float(); { - case math.IsInf(vf, +1): - w.Write(posInf) - case math.IsInf(vf, -1): - w.Write(negInf) - case math.IsNaN(vf): - w.Write(nan) - default: - fmt.Fprint(w, v.Interface()) - } - case protoreflect.StringKind: - // NOTE: This does not validate UTF-8 for historical reasons. - w.writeQuotedString(string(v.String())) - case protoreflect.BytesKind: - w.writeQuotedString(string(v.Bytes())) - case protoreflect.MessageKind, protoreflect.GroupKind: - var bra, ket byte = '<', '>' - if fd.Kind() == protoreflect.GroupKind { - bra, ket = '{', '}' - } - w.WriteByte(bra) - if !w.compact { - w.WriteByte('\n') - } - w.indent++ - m := v.Message() - if m2, ok := m.Interface().(encoding.TextMarshaler); ok { - b, err := m2.MarshalText() - if err != nil { - return err - } - w.Write(b) - } else { - w.writeMessage(m) - } - w.indent-- - w.WriteByte(ket) - case protoreflect.EnumKind: - if ev := fd.Enum().Values().ByNumber(v.Enum()); ev != nil { - fmt.Fprint(w, ev.Name()) - } else { - fmt.Fprint(w, v.Enum()) - } - default: - fmt.Fprint(w, v.Interface()) - } - return nil -} - -// writeQuotedString writes a quoted string in the protocol buffer text format. -func (w *textWriter) writeQuotedString(s string) { - w.WriteByte('"') - for i := 0; i < len(s); i++ { - switch c := s[i]; c { - case '\n': - w.buf = append(w.buf, `\n`...) - case '\r': - w.buf = append(w.buf, `\r`...) - case '\t': - w.buf = append(w.buf, `\t`...) - case '"': - w.buf = append(w.buf, `\"`...) - case '\\': - w.buf = append(w.buf, `\\`...) - default: - if isPrint := c >= 0x20 && c < 0x7f; isPrint { - w.buf = append(w.buf, c) - } else { - w.buf = append(w.buf, fmt.Sprintf(`\%03o`, c)...) - } - } - } - w.WriteByte('"') -} - -func (w *textWriter) writeUnknownFields(b []byte) { - if !w.compact { - fmt.Fprintf(w, "/* %d unknown bytes */\n", len(b)) - } - - for len(b) > 0 { - num, wtyp, n := protowire.ConsumeTag(b) - if n < 0 { - return - } - b = b[n:] - - if wtyp == protowire.EndGroupType { - w.indent-- - w.Write(endBraceNewline) - continue - } - fmt.Fprint(w, num) - if wtyp != protowire.StartGroupType { - w.WriteByte(':') - } - if !w.compact || wtyp == protowire.StartGroupType { - w.WriteByte(' ') - } - switch wtyp { - case protowire.VarintType: - v, n := protowire.ConsumeVarint(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprint(w, v) - case protowire.Fixed32Type: - v, n := protowire.ConsumeFixed32(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprint(w, v) - case protowire.Fixed64Type: - v, n := protowire.ConsumeFixed64(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprint(w, v) - case protowire.BytesType: - v, n := protowire.ConsumeBytes(b) - if n < 0 { - return - } - b = b[n:] - fmt.Fprintf(w, "%q", v) - case protowire.StartGroupType: - w.WriteByte('{') - w.indent++ - default: - fmt.Fprintf(w, "/* unknown wire type %d */", wtyp) - } - w.WriteByte('\n') - } -} - -// writeExtensions writes all the extensions in m. -func (w *textWriter) writeExtensions(m protoreflect.Message) error { - md := m.Descriptor() - if md.ExtensionRanges().Len() == 0 { - return nil - } - - type ext struct { - desc protoreflect.FieldDescriptor - val protoreflect.Value - } - var exts []ext - m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - if fd.IsExtension() { - exts = append(exts, ext{fd, v}) - } - return true - }) - sort.Slice(exts, func(i, j int) bool { - return exts[i].desc.Number() < exts[j].desc.Number() - }) - - for _, ext := range exts { - // For message set, use the name of the message as the extension name. - name := string(ext.desc.FullName()) - if isMessageSet(ext.desc.ContainingMessage()) { - name = strings.TrimSuffix(name, ".message_set_extension") - } - - if !ext.desc.IsList() { - if err := w.writeSingularExtension(name, ext.val, ext.desc); err != nil { - return err - } - } else { - lv := ext.val.List() - for i := 0; i < lv.Len(); i++ { - if err := w.writeSingularExtension(name, lv.Get(i), ext.desc); err != nil { - return err - } - } - } - } - return nil -} - -func (w *textWriter) writeSingularExtension(name string, v protoreflect.Value, fd protoreflect.FieldDescriptor) error { - fmt.Fprintf(w, "[%s]:", name) - if !w.compact { - w.WriteByte(' ') - } - if err := w.writeSingularValue(v, fd); err != nil { - return err - } - w.WriteByte('\n') - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - for i := 0; i < w.indent*2; i++ { - w.buf = append(w.buf, ' ') - } - w.complete = false -} diff --git a/vendor/github.com/golang/protobuf/proto/wire.go b/vendor/github.com/golang/protobuf/proto/wire.go deleted file mode 100644 index d7c28da5a..000000000 --- a/vendor/github.com/golang/protobuf/proto/wire.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -import ( - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/runtime/protoiface" -) - -// Size returns the size in bytes of the wire-format encoding of m. -func Size(m Message) int { - if m == nil { - return 0 - } - mi := MessageV2(m) - return protoV2.Size(mi) -} - -// Marshal returns the wire-format encoding of m. -func Marshal(m Message) ([]byte, error) { - b, err := marshalAppend(nil, m, false) - if b == nil { - b = zeroBytes - } - return b, err -} - -var zeroBytes = make([]byte, 0, 0) - -func marshalAppend(buf []byte, m Message, deterministic bool) ([]byte, error) { - if m == nil { - return nil, ErrNil - } - mi := MessageV2(m) - nbuf, err := protoV2.MarshalOptions{ - Deterministic: deterministic, - AllowPartial: true, - }.MarshalAppend(buf, mi) - if err != nil { - return buf, err - } - if len(buf) == len(nbuf) { - if !mi.ProtoReflect().IsValid() { - return buf, ErrNil - } - } - return nbuf, checkRequiredNotSet(mi) -} - -// Unmarshal parses a wire-format message in b and places the decoded results in m. -// -// Unmarshal resets m before starting to unmarshal, so any existing data in m is always -// removed. Use UnmarshalMerge to preserve and append to existing data. -func Unmarshal(b []byte, m Message) error { - m.Reset() - return UnmarshalMerge(b, m) -} - -// UnmarshalMerge parses a wire-format message in b and places the decoded results in m. -func UnmarshalMerge(b []byte, m Message) error { - mi := MessageV2(m) - out, err := protoV2.UnmarshalOptions{ - AllowPartial: true, - Merge: true, - }.UnmarshalState(protoiface.UnmarshalInput{ - Buf: b, - Message: mi.ProtoReflect(), - }) - if err != nil { - return err - } - if out.Flags&protoiface.UnmarshalInitialized > 0 { - return nil - } - return checkRequiredNotSet(mi) -} diff --git a/vendor/github.com/golang/protobuf/proto/wrappers.go b/vendor/github.com/golang/protobuf/proto/wrappers.go deleted file mode 100644 index 398e34859..000000000 --- a/vendor/github.com/golang/protobuf/proto/wrappers.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proto - -// Bool stores v in a new bool value and returns a pointer to it. -func Bool(v bool) *bool { return &v } - -// Int stores v in a new int32 value and returns a pointer to it. -// -// Deprecated: Use Int32 instead. -func Int(v int) *int32 { return Int32(int32(v)) } - -// Int32 stores v in a new int32 value and returns a pointer to it. -func Int32(v int32) *int32 { return &v } - -// Int64 stores v in a new int64 value and returns a pointer to it. -func Int64(v int64) *int64 { return &v } - -// Uint32 stores v in a new uint32 value and returns a pointer to it. -func Uint32(v uint32) *uint32 { return &v } - -// Uint64 stores v in a new uint64 value and returns a pointer to it. -func Uint64(v uint64) *uint64 { return &v } - -// Float32 stores v in a new float32 value and returns a pointer to it. -func Float32(v float32) *float32 { return &v } - -// Float64 stores v in a new float64 value and returns a pointer to it. -func Float64(v float64) *float64 { return &v } - -// String stores v in a new string value and returns a pointer to it. -func String(v string) *string { return &v } diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md new file mode 100644 index 000000000..7ec5ac7ea --- /dev/null +++ b/vendor/github.com/google/uuid/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog + +## [1.6.0](https://github.com/google/uuid/compare/v1.5.0...v1.6.0) (2024-01-16) + + +### Features + +* add Max UUID constant ([#149](https://github.com/google/uuid/issues/149)) ([c58770e](https://github.com/google/uuid/commit/c58770eb495f55fe2ced6284f93c5158a62e53e3)) + + +### Bug Fixes + +* fix typo in version 7 uuid documentation ([#153](https://github.com/google/uuid/issues/153)) ([016b199](https://github.com/google/uuid/commit/016b199544692f745ffc8867b914129ecb47ef06)) +* Monotonicity in UUIDv7 ([#150](https://github.com/google/uuid/issues/150)) ([a2b2b32](https://github.com/google/uuid/commit/a2b2b32373ff0b1a312b7fdf6d38a977099698a6)) + +## [1.5.0](https://github.com/google/uuid/compare/v1.4.0...v1.5.0) (2023-12-12) + + +### Features + +* Validate UUID without creating new UUID ([#141](https://github.com/google/uuid/issues/141)) ([9ee7366](https://github.com/google/uuid/commit/9ee7366e66c9ad96bab89139418a713dc584ae29)) + +## [1.4.0](https://github.com/google/uuid/compare/v1.3.1...v1.4.0) (2023-10-26) + + +### Features + +* UUIDs slice type with Strings() convenience method ([#133](https://github.com/google/uuid/issues/133)) ([cd5fbbd](https://github.com/google/uuid/commit/cd5fbbdd02f3e3467ac18940e07e062be1f864b4)) + +### Fixes + +* Clarify that Parse's job is to parse but not necessarily validate strings. (Documents current behavior) + +## [1.3.1](https://github.com/google/uuid/compare/v1.3.0...v1.3.1) (2023-08-18) + + +### Bug Fixes + +* Use .EqualFold() to parse urn prefixed UUIDs ([#118](https://github.com/google/uuid/issues/118)) ([574e687](https://github.com/google/uuid/commit/574e6874943741fb99d41764c705173ada5293f0)) + +## Changelog diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md new file mode 100644 index 000000000..a502fdc51 --- /dev/null +++ b/vendor/github.com/google/uuid/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# How to contribute + +We definitely welcome patches and contribution to this project! + +### Tips + +Commits must be formatted according to the [Conventional Commits Specification](https://www.conventionalcommits.org). + +Always try to include a test case! If it is not possible or not necessary, +please explain why in the pull request description. + +### Releasing + +Commits that would precipitate a SemVer change, as described in the Conventional +Commits Specification, will trigger [`release-please`](https://github.com/google-github-actions/release-please-action) +to create a release candidate pull request. Once submitted, `release-please` +will create a release. + +For tips on how to work with `release-please`, see its documentation. + +### Legal requirements + +In order to protect both you and ourselves, you will need to sign the +[Contributor License Agreement](https://cla.developers.google.com/clas). + +You may have already signed it for other Google projects. diff --git a/vendor/github.com/google/uuid/CONTRIBUTORS b/vendor/github.com/google/uuid/CONTRIBUTORS new file mode 100644 index 000000000..b4bb97f6b --- /dev/null +++ b/vendor/github.com/google/uuid/CONTRIBUTORS @@ -0,0 +1,9 @@ +Paul Borman +bmatsuo +shawnps +theory +jboverfelt +dsymonds +cd1 +wallclockbuilder +dansouza diff --git a/vendor/github.com/google/uuid/LICENSE b/vendor/github.com/google/uuid/LICENSE new file mode 100644 index 000000000..5dc68268d --- /dev/null +++ b/vendor/github.com/google/uuid/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009,2014 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/google/uuid/README.md b/vendor/github.com/google/uuid/README.md new file mode 100644 index 000000000..3e9a61889 --- /dev/null +++ b/vendor/github.com/google/uuid/README.md @@ -0,0 +1,21 @@ +# uuid +The uuid package generates and inspects UUIDs based on +[RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) +and DCE 1.1: Authentication and Security Services. + +This package is based on the github.com/pborman/uuid package (previously named +code.google.com/p/go-uuid). It differs from these earlier packages in that +a UUID is a 16 byte array rather than a byte slice. One loss due to this +change is the ability to represent an invalid UUID (vs a NIL UUID). + +###### Install +```sh +go get github.com/google/uuid +``` + +###### Documentation +[![Go Reference](https://pkg.go.dev/badge/github.com/google/uuid.svg)](https://pkg.go.dev/github.com/google/uuid) + +Full `go doc` style documentation for the package can be viewed online without +installing this package by using the GoDoc site here: +http://pkg.go.dev/github.com/google/uuid diff --git a/vendor/github.com/google/uuid/dce.go b/vendor/github.com/google/uuid/dce.go new file mode 100644 index 000000000..fa820b9d3 --- /dev/null +++ b/vendor/github.com/google/uuid/dce.go @@ -0,0 +1,80 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" + "fmt" + "os" +) + +// A Domain represents a Version 2 domain +type Domain byte + +// Domain constants for DCE Security (Version 2) UUIDs. +const ( + Person = Domain(0) + Group = Domain(1) + Org = Domain(2) +) + +// NewDCESecurity returns a DCE Security (Version 2) UUID. +// +// The domain should be one of Person, Group or Org. +// On a POSIX system the id should be the users UID for the Person +// domain and the users GID for the Group. The meaning of id for +// the domain Org or on non-POSIX systems is site defined. +// +// For a given domain/id pair the same token may be returned for up to +// 7 minutes and 10 seconds. +func NewDCESecurity(domain Domain, id uint32) (UUID, error) { + uuid, err := NewUUID() + if err == nil { + uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 + uuid[9] = byte(domain) + binary.BigEndian.PutUint32(uuid[0:], id) + } + return uuid, err +} + +// NewDCEPerson returns a DCE Security (Version 2) UUID in the person +// domain with the id returned by os.Getuid. +// +// NewDCESecurity(Person, uint32(os.Getuid())) +func NewDCEPerson() (UUID, error) { + return NewDCESecurity(Person, uint32(os.Getuid())) +} + +// NewDCEGroup returns a DCE Security (Version 2) UUID in the group +// domain with the id returned by os.Getgid. +// +// NewDCESecurity(Group, uint32(os.Getgid())) +func NewDCEGroup() (UUID, error) { + return NewDCESecurity(Group, uint32(os.Getgid())) +} + +// Domain returns the domain for a Version 2 UUID. Domains are only defined +// for Version 2 UUIDs. +func (uuid UUID) Domain() Domain { + return Domain(uuid[9]) +} + +// ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 +// UUIDs. +func (uuid UUID) ID() uint32 { + return binary.BigEndian.Uint32(uuid[0:4]) +} + +func (d Domain) String() string { + switch d { + case Person: + return "Person" + case Group: + return "Group" + case Org: + return "Org" + } + return fmt.Sprintf("Domain%d", int(d)) +} diff --git a/vendor/github.com/google/uuid/doc.go b/vendor/github.com/google/uuid/doc.go new file mode 100644 index 000000000..5b8a4b9af --- /dev/null +++ b/vendor/github.com/google/uuid/doc.go @@ -0,0 +1,12 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package uuid generates and inspects UUIDs. +// +// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security +// Services. +// +// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to +// maps or compared directly. +package uuid diff --git a/vendor/github.com/google/uuid/hash.go b/vendor/github.com/google/uuid/hash.go new file mode 100644 index 000000000..dc60082d3 --- /dev/null +++ b/vendor/github.com/google/uuid/hash.go @@ -0,0 +1,59 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "crypto/md5" + "crypto/sha1" + "hash" +) + +// Well known namespace IDs and UUIDs +var ( + NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) + NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) + NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) + NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) + Nil UUID // empty UUID, all zeros + + // The Max UUID is special form of UUID that is specified to have all 128 bits set to 1. + Max = UUID{ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + } +) + +// NewHash returns a new UUID derived from the hash of space concatenated with +// data generated by h. The hash should be at least 16 byte in length. The +// first 16 bytes of the hash are used to form the UUID. The version of the +// UUID will be the lower 4 bits of version. NewHash is used to implement +// NewMD5 and NewSHA1. +func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { + h.Reset() + h.Write(space[:]) //nolint:errcheck + h.Write(data) //nolint:errcheck + s := h.Sum(nil) + var uuid UUID + copy(uuid[:], s) + uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) + uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant + return uuid +} + +// NewMD5 returns a new MD5 (Version 3) UUID based on the +// supplied name space and data. It is the same as calling: +// +// NewHash(md5.New(), space, data, 3) +func NewMD5(space UUID, data []byte) UUID { + return NewHash(md5.New(), space, data, 3) +} + +// NewSHA1 returns a new SHA1 (Version 5) UUID based on the +// supplied name space and data. It is the same as calling: +// +// NewHash(sha1.New(), space, data, 5) +func NewSHA1(space UUID, data []byte) UUID { + return NewHash(sha1.New(), space, data, 5) +} diff --git a/vendor/github.com/google/uuid/marshal.go b/vendor/github.com/google/uuid/marshal.go new file mode 100644 index 000000000..14bd34072 --- /dev/null +++ b/vendor/github.com/google/uuid/marshal.go @@ -0,0 +1,38 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "fmt" + +// MarshalText implements encoding.TextMarshaler. +func (uuid UUID) MarshalText() ([]byte, error) { + var js [36]byte + encodeHex(js[:], uuid) + return js[:], nil +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (uuid *UUID) UnmarshalText(data []byte) error { + id, err := ParseBytes(data) + if err != nil { + return err + } + *uuid = id + return nil +} + +// MarshalBinary implements encoding.BinaryMarshaler. +func (uuid UUID) MarshalBinary() ([]byte, error) { + return uuid[:], nil +} + +// UnmarshalBinary implements encoding.BinaryUnmarshaler. +func (uuid *UUID) UnmarshalBinary(data []byte) error { + if len(data) != 16 { + return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) + } + copy(uuid[:], data) + return nil +} diff --git a/vendor/github.com/google/uuid/node.go b/vendor/github.com/google/uuid/node.go new file mode 100644 index 000000000..d651a2b06 --- /dev/null +++ b/vendor/github.com/google/uuid/node.go @@ -0,0 +1,90 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "sync" +) + +var ( + nodeMu sync.Mutex + ifname string // name of interface being used + nodeID [6]byte // hardware for version 1 UUIDs + zeroID [6]byte // nodeID with only 0's +) + +// NodeInterface returns the name of the interface from which the NodeID was +// derived. The interface "user" is returned if the NodeID was set by +// SetNodeID. +func NodeInterface() string { + defer nodeMu.Unlock() + nodeMu.Lock() + return ifname +} + +// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. +// If name is "" then the first usable interface found will be used or a random +// Node ID will be generated. If a named interface cannot be found then false +// is returned. +// +// SetNodeInterface never fails when name is "". +func SetNodeInterface(name string) bool { + defer nodeMu.Unlock() + nodeMu.Lock() + return setNodeInterface(name) +} + +func setNodeInterface(name string) bool { + iname, addr := getHardwareInterface(name) // null implementation for js + if iname != "" && addr != nil { + ifname = iname + copy(nodeID[:], addr) + return true + } + + // We found no interfaces with a valid hardware address. If name + // does not specify a specific interface generate a random Node ID + // (section 4.1.6) + if name == "" { + ifname = "random" + randomBits(nodeID[:]) + return true + } + return false +} + +// NodeID returns a slice of a copy of the current Node ID, setting the Node ID +// if not already set. +func NodeID() []byte { + defer nodeMu.Unlock() + nodeMu.Lock() + if nodeID == zeroID { + setNodeInterface("") + } + nid := nodeID + return nid[:] +} + +// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes +// of id are used. If id is less than 6 bytes then false is returned and the +// Node ID is not set. +func SetNodeID(id []byte) bool { + if len(id) < 6 { + return false + } + defer nodeMu.Unlock() + nodeMu.Lock() + copy(nodeID[:], id) + ifname = "user" + return true +} + +// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is +// not valid. The NodeID is only well defined for version 1 and 2 UUIDs. +func (uuid UUID) NodeID() []byte { + var node [6]byte + copy(node[:], uuid[10:]) + return node[:] +} diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go new file mode 100644 index 000000000..b2a0bc871 --- /dev/null +++ b/vendor/github.com/google/uuid/node_js.go @@ -0,0 +1,12 @@ +// Copyright 2017 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build js + +package uuid + +// getHardwareInterface returns nil values for the JS version of the code. +// This removes the "net" dependency, because it is not used in the browser. +// Using the "net" library inflates the size of the transpiled JS code by 673k bytes. +func getHardwareInterface(name string) (string, []byte) { return "", nil } diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go new file mode 100644 index 000000000..0cbbcddbd --- /dev/null +++ b/vendor/github.com/google/uuid/node_net.go @@ -0,0 +1,33 @@ +// Copyright 2017 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !js + +package uuid + +import "net" + +var interfaces []net.Interface // cached list of interfaces + +// getHardwareInterface returns the name and hardware address of interface name. +// If name is "" then the name and hardware address of one of the system's +// interfaces is returned. If no interfaces are found (name does not exist or +// there are no interfaces) then "", nil is returned. +// +// Only addresses of at least 6 bytes are returned. +func getHardwareInterface(name string) (string, []byte) { + if interfaces == nil { + var err error + interfaces, err = net.Interfaces() + if err != nil { + return "", nil + } + } + for _, ifs := range interfaces { + if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { + return ifs.Name, ifs.HardwareAddr + } + } + return "", nil +} diff --git a/vendor/github.com/google/uuid/null.go b/vendor/github.com/google/uuid/null.go new file mode 100644 index 000000000..d7fcbf286 --- /dev/null +++ b/vendor/github.com/google/uuid/null.go @@ -0,0 +1,118 @@ +// Copyright 2021 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "bytes" + "database/sql/driver" + "encoding/json" + "fmt" +) + +var jsonNull = []byte("null") + +// NullUUID represents a UUID that may be null. +// NullUUID implements the SQL driver.Scanner interface so +// it can be used as a scan destination: +// +// var u uuid.NullUUID +// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u) +// ... +// if u.Valid { +// // use u.UUID +// } else { +// // NULL value +// } +// +type NullUUID struct { + UUID UUID + Valid bool // Valid is true if UUID is not NULL +} + +// Scan implements the SQL driver.Scanner interface. +func (nu *NullUUID) Scan(value interface{}) error { + if value == nil { + nu.UUID, nu.Valid = Nil, false + return nil + } + + err := nu.UUID.Scan(value) + if err != nil { + nu.Valid = false + return err + } + + nu.Valid = true + return nil +} + +// Value implements the driver Valuer interface. +func (nu NullUUID) Value() (driver.Value, error) { + if !nu.Valid { + return nil, nil + } + // Delegate to UUID Value function + return nu.UUID.Value() +} + +// MarshalBinary implements encoding.BinaryMarshaler. +func (nu NullUUID) MarshalBinary() ([]byte, error) { + if nu.Valid { + return nu.UUID[:], nil + } + + return []byte(nil), nil +} + +// UnmarshalBinary implements encoding.BinaryUnmarshaler. +func (nu *NullUUID) UnmarshalBinary(data []byte) error { + if len(data) != 16 { + return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) + } + copy(nu.UUID[:], data) + nu.Valid = true + return nil +} + +// MarshalText implements encoding.TextMarshaler. +func (nu NullUUID) MarshalText() ([]byte, error) { + if nu.Valid { + return nu.UUID.MarshalText() + } + + return jsonNull, nil +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (nu *NullUUID) UnmarshalText(data []byte) error { + id, err := ParseBytes(data) + if err != nil { + nu.Valid = false + return err + } + nu.UUID = id + nu.Valid = true + return nil +} + +// MarshalJSON implements json.Marshaler. +func (nu NullUUID) MarshalJSON() ([]byte, error) { + if nu.Valid { + return json.Marshal(nu.UUID) + } + + return jsonNull, nil +} + +// UnmarshalJSON implements json.Unmarshaler. +func (nu *NullUUID) UnmarshalJSON(data []byte) error { + if bytes.Equal(data, jsonNull) { + *nu = NullUUID{} + return nil // valid null UUID + } + err := json.Unmarshal(data, &nu.UUID) + nu.Valid = err == nil + return err +} diff --git a/vendor/github.com/google/uuid/sql.go b/vendor/github.com/google/uuid/sql.go new file mode 100644 index 000000000..2e02ec06c --- /dev/null +++ b/vendor/github.com/google/uuid/sql.go @@ -0,0 +1,59 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "database/sql/driver" + "fmt" +) + +// Scan implements sql.Scanner so UUIDs can be read from databases transparently. +// Currently, database types that map to string and []byte are supported. Please +// consult database-specific driver documentation for matching types. +func (uuid *UUID) Scan(src interface{}) error { + switch src := src.(type) { + case nil: + return nil + + case string: + // if an empty UUID comes from a table, we return a null UUID + if src == "" { + return nil + } + + // see Parse for required string format + u, err := Parse(src) + if err != nil { + return fmt.Errorf("Scan: %v", err) + } + + *uuid = u + + case []byte: + // if an empty UUID comes from a table, we return a null UUID + if len(src) == 0 { + return nil + } + + // assumes a simple slice of bytes if 16 bytes + // otherwise attempts to parse + if len(src) != 16 { + return uuid.Scan(string(src)) + } + copy((*uuid)[:], src) + + default: + return fmt.Errorf("Scan: unable to scan type %T into UUID", src) + } + + return nil +} + +// Value implements sql.Valuer so that UUIDs can be written to databases +// transparently. Currently, UUIDs map to strings. Please consult +// database-specific driver documentation for matching types. +func (uuid UUID) Value() (driver.Value, error) { + return uuid.String(), nil +} diff --git a/vendor/github.com/google/uuid/time.go b/vendor/github.com/google/uuid/time.go new file mode 100644 index 000000000..c35112927 --- /dev/null +++ b/vendor/github.com/google/uuid/time.go @@ -0,0 +1,134 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" + "sync" + "time" +) + +// A Time represents a time as the number of 100's of nanoseconds since 15 Oct +// 1582. +type Time int64 + +const ( + lillian = 2299160 // Julian day of 15 Oct 1582 + unix = 2440587 // Julian day of 1 Jan 1970 + epoch = unix - lillian // Days between epochs + g1582 = epoch * 86400 // seconds between epochs + g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs +) + +var ( + timeMu sync.Mutex + lasttime uint64 // last time we returned + clockSeq uint16 // clock sequence for this run + + timeNow = time.Now // for testing +) + +// UnixTime converts t the number of seconds and nanoseconds using the Unix +// epoch of 1 Jan 1970. +func (t Time) UnixTime() (sec, nsec int64) { + sec = int64(t - g1582ns100) + nsec = (sec % 10000000) * 100 + sec /= 10000000 + return sec, nsec +} + +// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and +// clock sequence as well as adjusting the clock sequence as needed. An error +// is returned if the current time cannot be determined. +func GetTime() (Time, uint16, error) { + defer timeMu.Unlock() + timeMu.Lock() + return getTime() +} + +func getTime() (Time, uint16, error) { + t := timeNow() + + // If we don't have a clock sequence already, set one. + if clockSeq == 0 { + setClockSequence(-1) + } + now := uint64(t.UnixNano()/100) + g1582ns100 + + // If time has gone backwards with this clock sequence then we + // increment the clock sequence + if now <= lasttime { + clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 + } + lasttime = now + return Time(now), clockSeq, nil +} + +// ClockSequence returns the current clock sequence, generating one if not +// already set. The clock sequence is only used for Version 1 UUIDs. +// +// The uuid package does not use global static storage for the clock sequence or +// the last time a UUID was generated. Unless SetClockSequence is used, a new +// random clock sequence is generated the first time a clock sequence is +// requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) +func ClockSequence() int { + defer timeMu.Unlock() + timeMu.Lock() + return clockSequence() +} + +func clockSequence() int { + if clockSeq == 0 { + setClockSequence(-1) + } + return int(clockSeq & 0x3fff) +} + +// SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to +// -1 causes a new sequence to be generated. +func SetClockSequence(seq int) { + defer timeMu.Unlock() + timeMu.Lock() + setClockSequence(seq) +} + +func setClockSequence(seq int) { + if seq == -1 { + var b [2]byte + randomBits(b[:]) // clock sequence + seq = int(b[0])<<8 | int(b[1]) + } + oldSeq := clockSeq + clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant + if oldSeq != clockSeq { + lasttime = 0 + } +} + +// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in +// uuid. The time is only defined for version 1, 2, 6 and 7 UUIDs. +func (uuid UUID) Time() Time { + var t Time + switch uuid.Version() { + case 6: + time := binary.BigEndian.Uint64(uuid[:8]) // Ignore uuid[6] version b0110 + t = Time(time) + case 7: + time := binary.BigEndian.Uint64(uuid[:8]) + t = Time((time>>16)*10000 + g1582ns100) + default: // forward compatible + time := int64(binary.BigEndian.Uint32(uuid[0:4])) + time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 + time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 + t = Time(time) + } + return t +} + +// ClockSequence returns the clock sequence encoded in uuid. +// The clock sequence is only well defined for version 1 and 2 UUIDs. +func (uuid UUID) ClockSequence() int { + return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff +} diff --git a/vendor/github.com/google/uuid/util.go b/vendor/github.com/google/uuid/util.go new file mode 100644 index 000000000..5ea6c7378 --- /dev/null +++ b/vendor/github.com/google/uuid/util.go @@ -0,0 +1,43 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "io" +) + +// randomBits completely fills slice b with random data. +func randomBits(b []byte) { + if _, err := io.ReadFull(rander, b); err != nil { + panic(err.Error()) // rand should never fail + } +} + +// xvalues returns the value of a byte as a hexadecimal digit or 255. +var xvalues = [256]byte{ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, + 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, +} + +// xtob converts hex characters x1 and x2 into a byte. +func xtob(x1, x2 byte) (byte, bool) { + b1 := xvalues[x1] + b2 := xvalues[x2] + return (b1 << 4) | b2, b1 != 255 && b2 != 255 +} diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go new file mode 100644 index 000000000..5232b4867 --- /dev/null +++ b/vendor/github.com/google/uuid/uuid.go @@ -0,0 +1,365 @@ +// Copyright 2018 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "strings" + "sync" +) + +// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC +// 4122. +type UUID [16]byte + +// A Version represents a UUID's version. +type Version byte + +// A Variant represents a UUID's variant. +type Variant byte + +// Constants returned by Variant. +const ( + Invalid = Variant(iota) // Invalid UUID + RFC4122 // The variant specified in RFC4122 + Reserved // Reserved, NCS backward compatibility. + Microsoft // Reserved, Microsoft Corporation backward compatibility. + Future // Reserved for future definition. +) + +const randPoolSize = 16 * 16 + +var ( + rander = rand.Reader // random function + poolEnabled = false + poolMu sync.Mutex + poolPos = randPoolSize // protected with poolMu + pool [randPoolSize]byte // protected with poolMu +) + +type invalidLengthError struct{ len int } + +func (err invalidLengthError) Error() string { + return fmt.Sprintf("invalid UUID length: %d", err.len) +} + +// IsInvalidLengthError is matcher function for custom error invalidLengthError +func IsInvalidLengthError(err error) bool { + _, ok := err.(invalidLengthError) + return ok +} + +// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both +// the standard UUID forms defined in RFC 4122 +// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, +// Parse accepts non-standard strings such as the raw hex encoding +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, +// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are +// examined in the latter case. Parse should not be used to validate strings as +// it parses non-standard encodings as indicated above. +func Parse(s string) (UUID, error) { + var uuid UUID + switch len(s) { + // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 36: + + // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 36 + 9: + if !strings.EqualFold(s[:9], "urn:uuid:") { + return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) + } + s = s[9:] + + // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + case 36 + 2: + s = s[1:] + + // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + case 32: + var ok bool + for i := range uuid { + uuid[i], ok = xtob(s[i*2], s[i*2+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + } + return uuid, nil + default: + return uuid, invalidLengthError{len(s)} + } + // s is now at least 36 bytes long + // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return uuid, errors.New("invalid UUID format") + } + for i, x := range [16]int{ + 0, 2, 4, 6, + 9, 11, + 14, 16, + 19, 21, + 24, 26, 28, 30, 32, 34, + } { + v, ok := xtob(s[x], s[x+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + uuid[i] = v + } + return uuid, nil +} + +// ParseBytes is like Parse, except it parses a byte slice instead of a string. +func ParseBytes(b []byte) (UUID, error) { + var uuid UUID + switch len(b) { + case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) { + return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) + } + b = b[9:] + case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + b = b[1:] + case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + var ok bool + for i := 0; i < 32; i += 2 { + uuid[i/2], ok = xtob(b[i], b[i+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + } + return uuid, nil + default: + return uuid, invalidLengthError{len(b)} + } + // s is now at least 36 bytes long + // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { + return uuid, errors.New("invalid UUID format") + } + for i, x := range [16]int{ + 0, 2, 4, 6, + 9, 11, + 14, 16, + 19, 21, + 24, 26, 28, 30, 32, 34, + } { + v, ok := xtob(b[x], b[x+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + uuid[i] = v + } + return uuid, nil +} + +// MustParse is like Parse but panics if the string cannot be parsed. +// It simplifies safe initialization of global variables holding compiled UUIDs. +func MustParse(s string) UUID { + uuid, err := Parse(s) + if err != nil { + panic(`uuid: Parse(` + s + `): ` + err.Error()) + } + return uuid +} + +// FromBytes creates a new UUID from a byte slice. Returns an error if the slice +// does not have a length of 16. The bytes are copied from the slice. +func FromBytes(b []byte) (uuid UUID, err error) { + err = uuid.UnmarshalBinary(b) + return uuid, err +} + +// Must returns uuid if err is nil and panics otherwise. +func Must(uuid UUID, err error) UUID { + if err != nil { + panic(err) + } + return uuid +} + +// Validate returns an error if s is not a properly formatted UUID in one of the following formats: +// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} +// It returns an error if the format is invalid, otherwise nil. +func Validate(s string) error { + switch len(s) { + // Standard UUID format + case 36: + + // UUID with "urn:uuid:" prefix + case 36 + 9: + if !strings.EqualFold(s[:9], "urn:uuid:") { + return fmt.Errorf("invalid urn prefix: %q", s[:9]) + } + s = s[9:] + + // UUID enclosed in braces + case 36 + 2: + if s[0] != '{' || s[len(s)-1] != '}' { + return fmt.Errorf("invalid bracketed UUID format") + } + s = s[1 : len(s)-1] + + // UUID without hyphens + case 32: + for i := 0; i < len(s); i += 2 { + _, ok := xtob(s[i], s[i+1]) + if !ok { + return errors.New("invalid UUID format") + } + } + + default: + return invalidLengthError{len(s)} + } + + // Check for standard UUID format + if len(s) == 36 { + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return errors.New("invalid UUID format") + } + for _, x := range []int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { + if _, ok := xtob(s[x], s[x+1]); !ok { + return errors.New("invalid UUID format") + } + } + } + + return nil +} + +// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// , or "" if uuid is invalid. +func (uuid UUID) String() string { + var buf [36]byte + encodeHex(buf[:], uuid) + return string(buf[:]) +} + +// URN returns the RFC 2141 URN form of uuid, +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. +func (uuid UUID) URN() string { + var buf [36 + 9]byte + copy(buf[:], "urn:uuid:") + encodeHex(buf[9:], uuid) + return string(buf[:]) +} + +func encodeHex(dst []byte, uuid UUID) { + hex.Encode(dst, uuid[:4]) + dst[8] = '-' + hex.Encode(dst[9:13], uuid[4:6]) + dst[13] = '-' + hex.Encode(dst[14:18], uuid[6:8]) + dst[18] = '-' + hex.Encode(dst[19:23], uuid[8:10]) + dst[23] = '-' + hex.Encode(dst[24:], uuid[10:]) +} + +// Variant returns the variant encoded in uuid. +func (uuid UUID) Variant() Variant { + switch { + case (uuid[8] & 0xc0) == 0x80: + return RFC4122 + case (uuid[8] & 0xe0) == 0xc0: + return Microsoft + case (uuid[8] & 0xe0) == 0xe0: + return Future + default: + return Reserved + } +} + +// Version returns the version of uuid. +func (uuid UUID) Version() Version { + return Version(uuid[6] >> 4) +} + +func (v Version) String() string { + if v > 15 { + return fmt.Sprintf("BAD_VERSION_%d", v) + } + return fmt.Sprintf("VERSION_%d", v) +} + +func (v Variant) String() string { + switch v { + case RFC4122: + return "RFC4122" + case Reserved: + return "Reserved" + case Microsoft: + return "Microsoft" + case Future: + return "Future" + case Invalid: + return "Invalid" + } + return fmt.Sprintf("BadVariant%d", int(v)) +} + +// SetRand sets the random number generator to r, which implements io.Reader. +// If r.Read returns an error when the package requests random data then +// a panic will be issued. +// +// Calling SetRand with nil sets the random number generator to the default +// generator. +func SetRand(r io.Reader) { + if r == nil { + rander = rand.Reader + return + } + rander = r +} + +// EnableRandPool enables internal randomness pool used for Random +// (Version 4) UUID generation. The pool contains random bytes read from +// the random number generator on demand in batches. Enabling the pool +// may improve the UUID generation throughput significantly. +// +// Since the pool is stored on the Go heap, this feature may be a bad fit +// for security sensitive applications. +// +// Both EnableRandPool and DisableRandPool are not thread-safe and should +// only be called when there is no possibility that New or any other +// UUID Version 4 generation function will be called concurrently. +func EnableRandPool() { + poolEnabled = true +} + +// DisableRandPool disables the randomness pool if it was previously +// enabled with EnableRandPool. +// +// Both EnableRandPool and DisableRandPool are not thread-safe and should +// only be called when there is no possibility that New or any other +// UUID Version 4 generation function will be called concurrently. +func DisableRandPool() { + poolEnabled = false + defer poolMu.Unlock() + poolMu.Lock() + poolPos = randPoolSize +} + +// UUIDs is a slice of UUID types. +type UUIDs []UUID + +// Strings returns a string slice containing the string form of each UUID in uuids. +func (uuids UUIDs) Strings() []string { + var uuidStrs = make([]string, len(uuids)) + for i, uuid := range uuids { + uuidStrs[i] = uuid.String() + } + return uuidStrs +} diff --git a/vendor/github.com/google/uuid/version1.go b/vendor/github.com/google/uuid/version1.go new file mode 100644 index 000000000..463109629 --- /dev/null +++ b/vendor/github.com/google/uuid/version1.go @@ -0,0 +1,44 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" +) + +// NewUUID returns a Version 1 UUID based on the current NodeID and clock +// sequence, and the current time. If the NodeID has not been set by SetNodeID +// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// be set NewUUID returns nil. If clock sequence has not been set by +// SetClockSequence then it will be set automatically. If GetTime fails to +// return the current NewUUID returns nil and an error. +// +// In most cases, New should be used. +func NewUUID() (UUID, error) { + var uuid UUID + now, seq, err := GetTime() + if err != nil { + return uuid, err + } + + timeLow := uint32(now & 0xffffffff) + timeMid := uint16((now >> 32) & 0xffff) + timeHi := uint16((now >> 48) & 0x0fff) + timeHi |= 0x1000 // Version 1 + + binary.BigEndian.PutUint32(uuid[0:], timeLow) + binary.BigEndian.PutUint16(uuid[4:], timeMid) + binary.BigEndian.PutUint16(uuid[6:], timeHi) + binary.BigEndian.PutUint16(uuid[8:], seq) + + nodeMu.Lock() + if nodeID == zeroID { + setNodeInterface("") + } + copy(uuid[10:], nodeID[:]) + nodeMu.Unlock() + + return uuid, nil +} diff --git a/vendor/github.com/google/uuid/version4.go b/vendor/github.com/google/uuid/version4.go new file mode 100644 index 000000000..7697802e4 --- /dev/null +++ b/vendor/github.com/google/uuid/version4.go @@ -0,0 +1,76 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "io" + +// New creates a new random UUID or panics. New is equivalent to +// the expression +// +// uuid.Must(uuid.NewRandom()) +func New() UUID { + return Must(NewRandom()) +} + +// NewString creates a new random UUID and returns it as a string or panics. +// NewString is equivalent to the expression +// +// uuid.New().String() +func NewString() string { + return Must(NewRandom()).String() +} + +// NewRandom returns a Random (Version 4) UUID. +// +// The strength of the UUIDs is based on the strength of the crypto/rand +// package. +// +// Uses the randomness pool if it was enabled with EnableRandPool. +// +// A note about uniqueness derived from the UUID Wikipedia entry: +// +// Randomly generated UUIDs have 122 random bits. One's annual risk of being +// hit by a meteorite is estimated to be one chance in 17 billion, that +// means the probability is about 0.00000000006 (6 × 10−11), +// equivalent to the odds of creating a few tens of trillions of UUIDs in a +// year and having one duplicate. +func NewRandom() (UUID, error) { + if !poolEnabled { + return NewRandomFromReader(rander) + } + return newRandomFromPool() +} + +// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader. +func NewRandomFromReader(r io.Reader) (UUID, error) { + var uuid UUID + _, err := io.ReadFull(r, uuid[:]) + if err != nil { + return Nil, err + } + uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 + uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 + return uuid, nil +} + +func newRandomFromPool() (UUID, error) { + var uuid UUID + poolMu.Lock() + if poolPos == randPoolSize { + _, err := io.ReadFull(rander, pool[:]) + if err != nil { + poolMu.Unlock() + return Nil, err + } + poolPos = 0 + } + copy(uuid[:], pool[poolPos:(poolPos+16)]) + poolPos += 16 + poolMu.Unlock() + + uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 + uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 + return uuid, nil +} diff --git a/vendor/github.com/google/uuid/version6.go b/vendor/github.com/google/uuid/version6.go new file mode 100644 index 000000000..339a959a7 --- /dev/null +++ b/vendor/github.com/google/uuid/version6.go @@ -0,0 +1,56 @@ +// Copyright 2023 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "encoding/binary" + +// UUID version 6 is a field-compatible version of UUIDv1, reordered for improved DB locality. +// It is expected that UUIDv6 will primarily be used in contexts where there are existing v1 UUIDs. +// Systems that do not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead. +// +// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#uuidv6 +// +// NewV6 returns a Version 6 UUID based on the current NodeID and clock +// sequence, and the current time. If the NodeID has not been set by SetNodeID +// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// be set NewV6 set NodeID is random bits automatically . If clock sequence has not been set by +// SetClockSequence then it will be set automatically. If GetTime fails to +// return the current NewV6 returns Nil and an error. +func NewV6() (UUID, error) { + var uuid UUID + now, seq, err := GetTime() + if err != nil { + return uuid, err + } + + /* + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_high | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_mid | time_low_and_version | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |clk_seq_hi_res | clk_seq_low | node (0-1) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | node (2-5) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + + binary.BigEndian.PutUint64(uuid[0:], uint64(now)) + binary.BigEndian.PutUint16(uuid[8:], seq) + + uuid[6] = 0x60 | (uuid[6] & 0x0F) + uuid[8] = 0x80 | (uuid[8] & 0x3F) + + nodeMu.Lock() + if nodeID == zeroID { + setNodeInterface("") + } + copy(uuid[10:], nodeID[:]) + nodeMu.Unlock() + + return uuid, nil +} diff --git a/vendor/github.com/google/uuid/version7.go b/vendor/github.com/google/uuid/version7.go new file mode 100644 index 000000000..3167b643d --- /dev/null +++ b/vendor/github.com/google/uuid/version7.go @@ -0,0 +1,104 @@ +// Copyright 2023 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "io" +) + +// UUID version 7 features a time-ordered value field derived from the widely +// implemented and well known Unix Epoch timestamp source, +// the number of milliseconds seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. +// As well as improved entropy characteristics over versions 1 or 6. +// +// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#name-uuid-version-7 +// +// Implementations SHOULD utilize UUID version 7 over UUID version 1 and 6 if possible. +// +// NewV7 returns a Version 7 UUID based on the current time(Unix Epoch). +// Uses the randomness pool if it was enabled with EnableRandPool. +// On error, NewV7 returns Nil and an error +func NewV7() (UUID, error) { + uuid, err := NewRandom() + if err != nil { + return uuid, err + } + makeV7(uuid[:]) + return uuid, nil +} + +// NewV7FromReader returns a Version 7 UUID based on the current time(Unix Epoch). +// it use NewRandomFromReader fill random bits. +// On error, NewV7FromReader returns Nil and an error. +func NewV7FromReader(r io.Reader) (UUID, error) { + uuid, err := NewRandomFromReader(r) + if err != nil { + return uuid, err + } + + makeV7(uuid[:]) + return uuid, nil +} + +// makeV7 fill 48 bits time (uuid[0] - uuid[5]), set version b0111 (uuid[6]) +// uuid[8] already has the right version number (Variant is 10) +// see function NewV7 and NewV7FromReader +func makeV7(uuid []byte) { + /* + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | unix_ts_ms | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | unix_ts_ms | ver | rand_a (12 bit seq) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |var| rand_b | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | rand_b | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + _ = uuid[15] // bounds check + + t, s := getV7Time() + + uuid[0] = byte(t >> 40) + uuid[1] = byte(t >> 32) + uuid[2] = byte(t >> 24) + uuid[3] = byte(t >> 16) + uuid[4] = byte(t >> 8) + uuid[5] = byte(t) + + uuid[6] = 0x70 | (0x0F & byte(s>>8)) + uuid[7] = byte(s) +} + +// lastV7time is the last time we returned stored as: +// +// 52 bits of time in milliseconds since epoch +// 12 bits of (fractional nanoseconds) >> 8 +var lastV7time int64 + +const nanoPerMilli = 1000000 + +// getV7Time returns the time in milliseconds and nanoseconds / 256. +// The returned (milli << 12 + seq) is guarenteed to be greater than +// (milli << 12 + seq) returned by any previous call to getV7Time. +func getV7Time() (milli, seq int64) { + timeMu.Lock() + defer timeMu.Unlock() + + nano := timeNow().UnixNano() + milli = nano / nanoPerMilli + // Sequence number is between 0 and 3906 (nanoPerMilli>>8) + seq = (nano - milli*nanoPerMilli) >> 8 + now := milli<<12 + seq + if now <= lastV7time { + now = lastV7time + 1 + milli = now >> 12 + seq = now & 0xfff + } + lastV7time = now + return milli, seq +} diff --git a/vendor/github.com/iancoleman/strcase/.travis.yml b/vendor/github.com/iancoleman/strcase/.travis.yml new file mode 100644 index 000000000..79ebc5693 --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/.travis.yml @@ -0,0 +1,10 @@ +sudo: false +language: go +go: + - 1.10.x + - 1.11.x + - 1.12.x + - 1.13.x + - 1.14.x + - 1.15.x + - master diff --git a/vendor/github.com/iancoleman/strcase/LICENSE b/vendor/github.com/iancoleman/strcase/LICENSE new file mode 100644 index 000000000..3e87ff70e --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Ian Coleman +Copyright (c) 2018 Ma_124, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, Subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or Substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/iancoleman/strcase/README.md b/vendor/github.com/iancoleman/strcase/README.md new file mode 100644 index 000000000..e72d9e97c --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/README.md @@ -0,0 +1,59 @@ +# strcase +[![Godoc Reference](https://godoc.org/github.com/iancoleman/strcase?status.svg)](http://godoc.org/github.com/iancoleman/strcase) +[![Build Status](https://travis-ci.com/iancoleman/strcase.svg)](https://travis-ci.com/iancoleman/strcase) +[![Coverage](http://gocover.io/_badge/github.com/iancoleman/strcase?0)](http://gocover.io/github.com/iancoleman/strcase) +[![Go Report Card](https://goreportcard.com/badge/github.com/iancoleman/strcase)](https://goreportcard.com/report/github.com/iancoleman/strcase) + +strcase is a go package for converting string case to various cases (e.g. [snake case](https://en.wikipedia.org/wiki/Snake_case) or [camel case](https://en.wikipedia.org/wiki/CamelCase)) to see the full conversion table below. + +## Example + +```go +s := "AnyKind of_string" +``` + +| Function | Result | +|-------------------------------------------|----------------------| +| `ToSnake(s)` | `any_kind_of_string` | +| `ToSnakeWithIgnore(s, '.')` | `any_kind.of_string` | +| `ToScreamingSnake(s)` | `ANY_KIND_OF_STRING` | +| `ToKebab(s)` | `any-kind-of-string` | +| `ToScreamingKebab(s)` | `ANY-KIND-OF-STRING` | +| `ToDelimited(s, '.')` | `any.kind.of.string` | +| `ToScreamingDelimited(s, '.', '', true)` | `ANY.KIND.OF.STRING` | +| `ToScreamingDelimited(s, '.', ' ', true)` | `ANY.KIND OF.STRING` | +| `ToCamel(s)` | `AnyKindOfString` | +| `ToLowerCamel(s)` | `anyKindOfString` | + + +## Install + +```bash +go get -u github.com/iancoleman/strcase +``` + +## Custom Acronyms for ToCamel && ToLowerCamel + +Often times text can contain specific acronyms which you need to be handled a certain way. +Out of the box `strcase` treats the string "ID" as "Id" or "id" but there is no way to cater +for every case in the wild. + +To configure your custom acronym globally you can use the following before running any conversion + +```go +import ( + "github.com/iancoleman/strcase" +) + +func init() { + // results in "Api" using ToCamel("API") + // results in "api" using ToLowerCamel("API") + strcase.ConfigureAcronym("API", "api") + + // results in "PostgreSQL" using ToCamel("PostgreSQL") + // results in "postgreSQL" using ToLowerCamel("PostgreSQL") + strcase.ConfigureAcronym("PostgreSQL", "PostgreSQL") + +} + +``` diff --git a/vendor/github.com/iancoleman/strcase/acronyms.go b/vendor/github.com/iancoleman/strcase/acronyms.go new file mode 100644 index 000000000..7a2fb09ea --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/acronyms.go @@ -0,0 +1,13 @@ +package strcase + +import ( + "sync" +) + +var uppercaseAcronym = sync.Map{} + //"ID": "id", + +// ConfigureAcronym allows you to add additional words which will be considered acronyms +func ConfigureAcronym(key, val string) { + uppercaseAcronym.Store(key, val) +} diff --git a/vendor/github.com/iancoleman/strcase/camel.go b/vendor/github.com/iancoleman/strcase/camel.go new file mode 100644 index 000000000..6b886894a --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/camel.go @@ -0,0 +1,87 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ian Coleman + * Copyright (c) 2018 Ma_124, + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, Subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or Substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package strcase + +import ( + "strings" +) + +// Converts a string to CamelCase +func toCamelInitCase(s string, initCase bool) string { + s = strings.TrimSpace(s) + if s == "" { + return s + } + a, hasAcronym := uppercaseAcronym.Load(s) + if hasAcronym { + s = a.(string) + } + + n := strings.Builder{} + n.Grow(len(s)) + capNext := initCase + prevIsCap := false + for i, v := range []byte(s) { + vIsCap := v >= 'A' && v <= 'Z' + vIsLow := v >= 'a' && v <= 'z' + if capNext { + if vIsLow { + v += 'A' + v -= 'a' + } + } else if i == 0 { + if vIsCap { + v += 'a' + v -= 'A' + } + } else if prevIsCap && vIsCap && !hasAcronym { + v += 'a' + v -= 'A' + } + prevIsCap = vIsCap + + if vIsCap || vIsLow { + n.WriteByte(v) + capNext = false + } else if vIsNum := v >= '0' && v <= '9'; vIsNum { + n.WriteByte(v) + capNext = true + } else { + capNext = v == '_' || v == ' ' || v == '-' || v == '.' + } + } + return n.String() +} + +// ToCamel converts a string to CamelCase +func ToCamel(s string) string { + return toCamelInitCase(s, true) +} + +// ToLowerCamel converts a string to lowerCamelCase +func ToLowerCamel(s string) string { + return toCamelInitCase(s, false) +} diff --git a/vendor/github.com/iancoleman/strcase/doc.go b/vendor/github.com/iancoleman/strcase/doc.go new file mode 100644 index 000000000..5e1825b9e --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/doc.go @@ -0,0 +1,12 @@ +// Package strcase converts strings to various cases. See the conversion table below: +// | Function | Result | +// |---------------------------------|--------------------| +// | ToSnake(s) | any_kind_of_string | +// | ToScreamingSnake(s) | ANY_KIND_OF_STRING | +// | ToKebab(s) | any-kind-of-string | +// | ToScreamingKebab(s) | ANY-KIND-OF-STRING | +// | ToDelimited(s, '.') | any.kind.of.string | +// | ToScreamingDelimited(s, '.') | ANY.KIND.OF.STRING | +// | ToCamel(s) | AnyKindOfString | +// | ToLowerCamel(s) | anyKindOfString | +package strcase diff --git a/vendor/github.com/iancoleman/strcase/snake.go b/vendor/github.com/iancoleman/strcase/snake.go new file mode 100644 index 000000000..df018bc7a --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/snake.go @@ -0,0 +1,115 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ian Coleman + * Copyright (c) 2018 Ma_124, + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, Subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or Substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package strcase + +import ( + "strings" +) + +// ToSnake converts a string to snake_case +func ToSnake(s string) string { + return ToDelimited(s, '_') +} + +func ToSnakeWithIgnore(s string, ignore string) string { + return ToScreamingDelimited(s, '_', ignore, false) +} + +// ToScreamingSnake converts a string to SCREAMING_SNAKE_CASE +func ToScreamingSnake(s string) string { + return ToScreamingDelimited(s, '_', "", true) +} + +// ToKebab converts a string to kebab-case +func ToKebab(s string) string { + return ToDelimited(s, '-') +} + +// ToScreamingKebab converts a string to SCREAMING-KEBAB-CASE +func ToScreamingKebab(s string) string { + return ToScreamingDelimited(s, '-', "", true) +} + +// ToDelimited converts a string to delimited.snake.case +// (in this case `delimiter = '.'`) +func ToDelimited(s string, delimiter uint8) string { + return ToScreamingDelimited(s, delimiter, "", false) +} + +// ToScreamingDelimited converts a string to SCREAMING.DELIMITED.SNAKE.CASE +// (in this case `delimiter = '.'; screaming = true`) +// or delimited.snake.case +// (in this case `delimiter = '.'; screaming = false`) +func ToScreamingDelimited(s string, delimiter uint8, ignore string, screaming bool) string { + s = strings.TrimSpace(s) + n := strings.Builder{} + n.Grow(len(s) + 2) // nominal 2 bytes of extra space for inserted delimiters + for i, v := range []byte(s) { + vIsCap := v >= 'A' && v <= 'Z' + vIsLow := v >= 'a' && v <= 'z' + if vIsLow && screaming { + v += 'A' + v -= 'a' + } else if vIsCap && !screaming { + v += 'a' + v -= 'A' + } + + // treat acronyms as words, eg for JSONData -> JSON is a whole word + if i+1 < len(s) { + next := s[i+1] + vIsNum := v >= '0' && v <= '9' + nextIsCap := next >= 'A' && next <= 'Z' + nextIsLow := next >= 'a' && next <= 'z' + nextIsNum := next >= '0' && next <= '9' + // add underscore if next letter case type is changed + if (vIsCap && (nextIsLow || nextIsNum)) || (vIsLow && (nextIsCap || nextIsNum)) || (vIsNum && (nextIsCap || nextIsLow)) { + prevIgnore := ignore != "" && i > 0 && strings.ContainsAny(string(s[i-1]), ignore) + if !prevIgnore { + if vIsCap && nextIsLow { + if prevIsCap := i > 0 && s[i-1] >= 'A' && s[i-1] <= 'Z'; prevIsCap { + n.WriteByte(delimiter) + } + } + n.WriteByte(v) + if vIsLow || vIsNum || nextIsNum { + n.WriteByte(delimiter) + } + continue + } + } + } + + if (v == ' ' || v == '_' || v == '-' || v == '.') && !strings.ContainsAny(string(v), ignore) { + // replace space/underscore/hyphen/dot with delimiter + n.WriteByte(delimiter) + } else { + n.WriteByte(v) + } + } + + return n.String() +} diff --git a/vendor/github.com/josharian/intern/README.md b/vendor/github.com/josharian/intern/README.md new file mode 100644 index 000000000..ffc44b219 --- /dev/null +++ b/vendor/github.com/josharian/intern/README.md @@ -0,0 +1,5 @@ +Docs: https://godoc.org/github.com/josharian/intern + +See also [Go issue 5160](https://golang.org/issue/5160). + +License: MIT diff --git a/vendor/github.com/josharian/intern/intern.go b/vendor/github.com/josharian/intern/intern.go new file mode 100644 index 000000000..7acb1fe90 --- /dev/null +++ b/vendor/github.com/josharian/intern/intern.go @@ -0,0 +1,44 @@ +// Package intern interns strings. +// Interning is best effort only. +// Interned strings may be removed automatically +// at any time without notification. +// All functions may be called concurrently +// with themselves and each other. +package intern + +import "sync" + +var ( + pool sync.Pool = sync.Pool{ + New: func() interface{} { + return make(map[string]string) + }, + } +) + +// String returns s, interned. +func String(s string) string { + m := pool.Get().(map[string]string) + c, ok := m[s] + if ok { + pool.Put(m) + return c + } + m[s] = s + pool.Put(m) + return s +} + +// Bytes returns b converted to a string, interned. +func Bytes(b []byte) string { + m := pool.Get().(map[string]string) + c, ok := m[string(b)] + if ok { + pool.Put(m) + return c + } + s := string(b) + m[s] = s + pool.Put(m) + return s +} diff --git a/vendor/github.com/josharian/intern/license.md b/vendor/github.com/josharian/intern/license.md new file mode 100644 index 000000000..353d3055f --- /dev/null +++ b/vendor/github.com/josharian/intern/license.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Josh Bleecher Snyder + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/json-iterator/go/.codecov.yml b/vendor/github.com/json-iterator/go/.codecov.yml new file mode 100644 index 000000000..955dc0be5 --- /dev/null +++ b/vendor/github.com/json-iterator/go/.codecov.yml @@ -0,0 +1,3 @@ +ignore: + - "output_tests/.*" + diff --git a/vendor/github.com/json-iterator/go/.gitignore b/vendor/github.com/json-iterator/go/.gitignore new file mode 100644 index 000000000..15556530a --- /dev/null +++ b/vendor/github.com/json-iterator/go/.gitignore @@ -0,0 +1,4 @@ +/vendor +/bug_test.go +/coverage.txt +/.idea diff --git a/vendor/github.com/json-iterator/go/.travis.yml b/vendor/github.com/json-iterator/go/.travis.yml new file mode 100644 index 000000000..449e67cd0 --- /dev/null +++ b/vendor/github.com/json-iterator/go/.travis.yml @@ -0,0 +1,14 @@ +language: go + +go: + - 1.8.x + - 1.x + +before_install: + - go get -t -v ./... + +script: + - ./test.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/json-iterator/go/Gopkg.lock b/vendor/github.com/json-iterator/go/Gopkg.lock new file mode 100644 index 000000000..c8a9fbb38 --- /dev/null +++ b/vendor/github.com/json-iterator/go/Gopkg.lock @@ -0,0 +1,21 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/modern-go/concurrent" + packages = ["."] + revision = "e0a39a4cb4216ea8db28e22a69f4ec25610d513a" + version = "1.0.0" + +[[projects]] + name = "github.com/modern-go/reflect2" + packages = ["."] + revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" + version = "1.0.1" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "ea54a775e5a354cb015502d2e7aa4b74230fc77e894f34a838b268c25ec8eeb8" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/json-iterator/go/Gopkg.toml b/vendor/github.com/json-iterator/go/Gopkg.toml new file mode 100644 index 000000000..313a0f887 --- /dev/null +++ b/vendor/github.com/json-iterator/go/Gopkg.toml @@ -0,0 +1,26 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" + +ignored = ["github.com/davecgh/go-spew*","github.com/google/gofuzz*","github.com/stretchr/testify*"] + +[[constraint]] + name = "github.com/modern-go/reflect2" + version = "1.0.1" diff --git a/vendor/github.com/json-iterator/go/LICENSE b/vendor/github.com/json-iterator/go/LICENSE new file mode 100644 index 000000000..2cf4f5ab2 --- /dev/null +++ b/vendor/github.com/json-iterator/go/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 json-iterator + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/json-iterator/go/README.md b/vendor/github.com/json-iterator/go/README.md new file mode 100644 index 000000000..c589addf9 --- /dev/null +++ b/vendor/github.com/json-iterator/go/README.md @@ -0,0 +1,85 @@ +[![Sourcegraph](https://sourcegraph.com/github.com/json-iterator/go/-/badge.svg)](https://sourcegraph.com/github.com/json-iterator/go?badge) +[![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/json-iterator/go) +[![Build Status](https://travis-ci.org/json-iterator/go.svg?branch=master)](https://travis-ci.org/json-iterator/go) +[![codecov](https://codecov.io/gh/json-iterator/go/branch/master/graph/badge.svg)](https://codecov.io/gh/json-iterator/go) +[![rcard](https://goreportcard.com/badge/github.com/json-iterator/go)](https://goreportcard.com/report/github.com/json-iterator/go) +[![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/json-iterator/go/master/LICENSE) +[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby) + +A high-performance 100% compatible drop-in replacement of "encoding/json" + +# Benchmark + +![benchmark](http://jsoniter.com/benchmarks/go-benchmark.png) + +Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go + +Raw Result (easyjson requires static code generation) + +| | ns/op | allocation bytes | allocation times | +| --------------- | ----------- | ---------------- | ---------------- | +| std decode | 35510 ns/op | 1960 B/op | 99 allocs/op | +| easyjson decode | 8499 ns/op | 160 B/op | 4 allocs/op | +| jsoniter decode | 5623 ns/op | 160 B/op | 3 allocs/op | +| std encode | 2213 ns/op | 712 B/op | 5 allocs/op | +| easyjson encode | 883 ns/op | 576 B/op | 3 allocs/op | +| jsoniter encode | 837 ns/op | 384 B/op | 4 allocs/op | + +Always benchmark with your own workload. +The result depends heavily on the data input. + +# Usage + +100% compatibility with standard lib + +Replace + +```go +import "encoding/json" +json.Marshal(&data) +``` + +with + +```go +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigCompatibleWithStandardLibrary +json.Marshal(&data) +``` + +Replace + +```go +import "encoding/json" +json.Unmarshal(input, &data) +``` + +with + +```go +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigCompatibleWithStandardLibrary +json.Unmarshal(input, &data) +``` + +[More documentation](http://jsoniter.com/migrate-from-go-std.html) + +# How to get + +``` +go get github.com/json-iterator/go +``` + +# Contribution Welcomed ! + +Contributors + +- [thockin](https://github.com/thockin) +- [mattn](https://github.com/mattn) +- [cch123](https://github.com/cch123) +- [Oleg Shaldybin](https://github.com/olegshaldybin) +- [Jason Toffaletti](https://github.com/toffaletti) + +Report issue or pull request, or email taowen@gmail.com, or [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby) diff --git a/vendor/github.com/json-iterator/go/adapter.go b/vendor/github.com/json-iterator/go/adapter.go new file mode 100644 index 000000000..92d2cc4a3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/adapter.go @@ -0,0 +1,150 @@ +package jsoniter + +import ( + "bytes" + "io" +) + +// RawMessage to make replace json with jsoniter +type RawMessage []byte + +// Unmarshal adapts to json/encoding Unmarshal API +// +// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. +// Refer to https://godoc.org/encoding/json#Unmarshal for more information +func Unmarshal(data []byte, v interface{}) error { + return ConfigDefault.Unmarshal(data, v) +} + +// UnmarshalFromString is a convenient method to read from string instead of []byte +func UnmarshalFromString(str string, v interface{}) error { + return ConfigDefault.UnmarshalFromString(str, v) +} + +// Get quick method to get value from deeply nested JSON structure +func Get(data []byte, path ...interface{}) Any { + return ConfigDefault.Get(data, path...) +} + +// Marshal adapts to json/encoding Marshal API +// +// Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API +// Refer to https://godoc.org/encoding/json#Marshal for more information +func Marshal(v interface{}) ([]byte, error) { + return ConfigDefault.Marshal(v) +} + +// MarshalIndent same as json.MarshalIndent. Prefix is not supported. +func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + return ConfigDefault.MarshalIndent(v, prefix, indent) +} + +// MarshalToString convenient method to write as string instead of []byte +func MarshalToString(v interface{}) (string, error) { + return ConfigDefault.MarshalToString(v) +} + +// NewDecoder adapts to json/stream NewDecoder API. +// +// NewDecoder returns a new decoder that reads from r. +// +// Instead of a json/encoding Decoder, an Decoder is returned +// Refer to https://godoc.org/encoding/json#NewDecoder for more information +func NewDecoder(reader io.Reader) *Decoder { + return ConfigDefault.NewDecoder(reader) +} + +// Decoder reads and decodes JSON values from an input stream. +// Decoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress) +type Decoder struct { + iter *Iterator +} + +// Decode decode JSON into interface{} +func (adapter *Decoder) Decode(obj interface{}) error { + if adapter.iter.head == adapter.iter.tail && adapter.iter.reader != nil { + if !adapter.iter.loadMore() { + return io.EOF + } + } + adapter.iter.ReadVal(obj) + err := adapter.iter.Error + if err == io.EOF { + return nil + } + return adapter.iter.Error +} + +// More is there more? +func (adapter *Decoder) More() bool { + iter := adapter.iter + if iter.Error != nil { + return false + } + c := iter.nextToken() + if c == 0 { + return false + } + iter.unreadByte() + return c != ']' && c != '}' +} + +// Buffered remaining buffer +func (adapter *Decoder) Buffered() io.Reader { + remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail] + return bytes.NewReader(remaining) +} + +// UseNumber causes the Decoder to unmarshal a number into an interface{} as a +// Number instead of as a float64. +func (adapter *Decoder) UseNumber() { + cfg := adapter.iter.cfg.configBeforeFrozen + cfg.UseNumber = true + adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) +} + +// DisallowUnknownFields causes the Decoder to return an error when the destination +// is a struct and the input contains object keys which do not match any +// non-ignored, exported fields in the destination. +func (adapter *Decoder) DisallowUnknownFields() { + cfg := adapter.iter.cfg.configBeforeFrozen + cfg.DisallowUnknownFields = true + adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) +} + +// NewEncoder same as json.NewEncoder +func NewEncoder(writer io.Writer) *Encoder { + return ConfigDefault.NewEncoder(writer) +} + +// Encoder same as json.Encoder +type Encoder struct { + stream *Stream +} + +// Encode encode interface{} as JSON to io.Writer +func (adapter *Encoder) Encode(val interface{}) error { + adapter.stream.WriteVal(val) + adapter.stream.WriteRaw("\n") + adapter.stream.Flush() + return adapter.stream.Error +} + +// SetIndent set the indention. Prefix is not supported +func (adapter *Encoder) SetIndent(prefix, indent string) { + config := adapter.stream.cfg.configBeforeFrozen + config.IndentionStep = len(indent) + adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) +} + +// SetEscapeHTML escape html by default, set to false to disable +func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) { + config := adapter.stream.cfg.configBeforeFrozen + config.EscapeHTML = escapeHTML + adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) +} + +// Valid reports whether data is a valid JSON encoding. +func Valid(data []byte) bool { + return ConfigDefault.Valid(data) +} diff --git a/vendor/github.com/json-iterator/go/any.go b/vendor/github.com/json-iterator/go/any.go new file mode 100644 index 000000000..f6b8aeab0 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any.go @@ -0,0 +1,325 @@ +package jsoniter + +import ( + "errors" + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "strconv" + "unsafe" +) + +// Any generic object representation. +// The lazy json implementation holds []byte and parse lazily. +type Any interface { + LastError() error + ValueType() ValueType + MustBeValid() Any + ToBool() bool + ToInt() int + ToInt32() int32 + ToInt64() int64 + ToUint() uint + ToUint32() uint32 + ToUint64() uint64 + ToFloat32() float32 + ToFloat64() float64 + ToString() string + ToVal(val interface{}) + Get(path ...interface{}) Any + Size() int + Keys() []string + GetInterface() interface{} + WriteTo(stream *Stream) +} + +type baseAny struct{} + +func (any *baseAny) Get(path ...interface{}) Any { + return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} +} + +func (any *baseAny) Size() int { + return 0 +} + +func (any *baseAny) Keys() []string { + return []string{} +} + +func (any *baseAny) ToVal(obj interface{}) { + panic("not implemented") +} + +// WrapInt32 turn int32 into Any interface +func WrapInt32(val int32) Any { + return &int32Any{baseAny{}, val} +} + +// WrapInt64 turn int64 into Any interface +func WrapInt64(val int64) Any { + return &int64Any{baseAny{}, val} +} + +// WrapUint32 turn uint32 into Any interface +func WrapUint32(val uint32) Any { + return &uint32Any{baseAny{}, val} +} + +// WrapUint64 turn uint64 into Any interface +func WrapUint64(val uint64) Any { + return &uint64Any{baseAny{}, val} +} + +// WrapFloat64 turn float64 into Any interface +func WrapFloat64(val float64) Any { + return &floatAny{baseAny{}, val} +} + +// WrapString turn string into Any interface +func WrapString(val string) Any { + return &stringAny{baseAny{}, val} +} + +// Wrap turn a go object into Any interface +func Wrap(val interface{}) Any { + if val == nil { + return &nilAny{} + } + asAny, isAny := val.(Any) + if isAny { + return asAny + } + typ := reflect2.TypeOf(val) + switch typ.Kind() { + case reflect.Slice: + return wrapArray(val) + case reflect.Struct: + return wrapStruct(val) + case reflect.Map: + return wrapMap(val) + case reflect.String: + return WrapString(val.(string)) + case reflect.Int: + if strconv.IntSize == 32 { + return WrapInt32(int32(val.(int))) + } + return WrapInt64(int64(val.(int))) + case reflect.Int8: + return WrapInt32(int32(val.(int8))) + case reflect.Int16: + return WrapInt32(int32(val.(int16))) + case reflect.Int32: + return WrapInt32(val.(int32)) + case reflect.Int64: + return WrapInt64(val.(int64)) + case reflect.Uint: + if strconv.IntSize == 32 { + return WrapUint32(uint32(val.(uint))) + } + return WrapUint64(uint64(val.(uint))) + case reflect.Uintptr: + if ptrSize == 32 { + return WrapUint32(uint32(val.(uintptr))) + } + return WrapUint64(uint64(val.(uintptr))) + case reflect.Uint8: + return WrapUint32(uint32(val.(uint8))) + case reflect.Uint16: + return WrapUint32(uint32(val.(uint16))) + case reflect.Uint32: + return WrapUint32(uint32(val.(uint32))) + case reflect.Uint64: + return WrapUint64(val.(uint64)) + case reflect.Float32: + return WrapFloat64(float64(val.(float32))) + case reflect.Float64: + return WrapFloat64(val.(float64)) + case reflect.Bool: + if val.(bool) == true { + return &trueAny{} + } + return &falseAny{} + } + return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)} +} + +// ReadAny read next JSON element as an Any object. It is a better json.RawMessage. +func (iter *Iterator) ReadAny() Any { + return iter.readAny() +} + +func (iter *Iterator) readAny() Any { + c := iter.nextToken() + switch c { + case '"': + iter.unreadByte() + return &stringAny{baseAny{}, iter.ReadString()} + case 'n': + iter.skipThreeBytes('u', 'l', 'l') // null + return &nilAny{} + case 't': + iter.skipThreeBytes('r', 'u', 'e') // true + return &trueAny{} + case 'f': + iter.skipFourBytes('a', 'l', 's', 'e') // false + return &falseAny{} + case '{': + return iter.readObjectAny() + case '[': + return iter.readArrayAny() + case '-': + return iter.readNumberAny(false) + case 0: + return &invalidAny{baseAny{}, errors.New("input is empty")} + default: + return iter.readNumberAny(true) + } +} + +func (iter *Iterator) readNumberAny(positive bool) Any { + iter.startCapture(iter.head - 1) + iter.skipNumber() + lazyBuf := iter.stopCapture() + return &numberLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} +} + +func (iter *Iterator) readObjectAny() Any { + iter.startCapture(iter.head - 1) + iter.skipObject() + lazyBuf := iter.stopCapture() + return &objectLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} +} + +func (iter *Iterator) readArrayAny() Any { + iter.startCapture(iter.head - 1) + iter.skipArray() + lazyBuf := iter.stopCapture() + return &arrayLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} +} + +func locateObjectField(iter *Iterator, target string) []byte { + var found []byte + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + if field == target { + found = iter.SkipAndReturnBytes() + return false + } + iter.Skip() + return true + }) + return found +} + +func locateArrayElement(iter *Iterator, target int) []byte { + var found []byte + n := 0 + iter.ReadArrayCB(func(iter *Iterator) bool { + if n == target { + found = iter.SkipAndReturnBytes() + return false + } + iter.Skip() + n++ + return true + }) + return found +} + +func locatePath(iter *Iterator, path []interface{}) Any { + for i, pathKeyObj := range path { + switch pathKey := pathKeyObj.(type) { + case string: + valueBytes := locateObjectField(iter, pathKey) + if valueBytes == nil { + return newInvalidAny(path[i:]) + } + iter.ResetBytes(valueBytes) + case int: + valueBytes := locateArrayElement(iter, pathKey) + if valueBytes == nil { + return newInvalidAny(path[i:]) + } + iter.ResetBytes(valueBytes) + case int32: + if '*' == pathKey { + return iter.readAny().Get(path[i:]...) + } + return newInvalidAny(path[i:]) + default: + return newInvalidAny(path[i:]) + } + } + if iter.Error != nil && iter.Error != io.EOF { + return &invalidAny{baseAny{}, iter.Error} + } + return iter.readAny() +} + +var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem() + +func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ == anyType { + return &directAnyCodec{} + } + if typ.Implements(anyType) { + return &anyCodec{ + valType: typ, + } + } + return nil +} + +func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == anyType { + return &directAnyCodec{} + } + if typ.Implements(anyType) { + return &anyCodec{ + valType: typ, + } + } + return nil +} + +type anyCodec struct { + valType reflect2.Type +} + +func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + panic("not implemented") +} + +func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := codec.valType.UnsafeIndirect(ptr) + any := obj.(Any) + any.WriteTo(stream) +} + +func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool { + obj := codec.valType.UnsafeIndirect(ptr) + any := obj.(Any) + return any.Size() == 0 +} + +type directAnyCodec struct { +} + +func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *(*Any)(ptr) = iter.readAny() +} + +func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + any := *(*Any)(ptr) + if any == nil { + stream.WriteNil() + return + } + any.WriteTo(stream) +} + +func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool { + any := *(*Any)(ptr) + return any.Size() == 0 +} diff --git a/vendor/github.com/json-iterator/go/any_array.go b/vendor/github.com/json-iterator/go/any_array.go new file mode 100644 index 000000000..0449e9aa4 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_array.go @@ -0,0 +1,278 @@ +package jsoniter + +import ( + "reflect" + "unsafe" +) + +type arrayLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *arrayLazyAny) ValueType() ValueType { + return ArrayValue +} + +func (any *arrayLazyAny) MustBeValid() Any { + return any +} + +func (any *arrayLazyAny) LastError() error { + return any.err +} + +func (any *arrayLazyAny) ToBool() bool { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.ReadArray() +} + +func (any *arrayLazyAny) ToInt() int { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToInt32() int32 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToInt64() int64 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToUint() uint { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToUint32() uint32 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToUint64() uint64 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToFloat32() float32 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToFloat64() float64 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *arrayLazyAny) ToVal(val interface{}) { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadVal(val) +} + +func (any *arrayLazyAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case int: + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + valueBytes := locateArrayElement(iter, firstPath) + if valueBytes == nil { + return newInvalidAny(path) + } + iter.ResetBytes(valueBytes) + return locatePath(iter, path[1:]) + case int32: + if '*' == firstPath { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + arr := make([]Any, 0) + iter.ReadArrayCB(func(iter *Iterator) bool { + found := iter.readAny().Get(path[1:]...) + if found.ValueType() != InvalidValue { + arr = append(arr, found) + } + return true + }) + return wrapArray(arr) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *arrayLazyAny) Size() int { + size := 0 + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadArrayCB(func(iter *Iterator) bool { + size++ + iter.Skip() + return true + }) + return size +} + +func (any *arrayLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *arrayLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} + +type arrayAny struct { + baseAny + val reflect.Value +} + +func wrapArray(val interface{}) *arrayAny { + return &arrayAny{baseAny{}, reflect.ValueOf(val)} +} + +func (any *arrayAny) ValueType() ValueType { + return ArrayValue +} + +func (any *arrayAny) MustBeValid() Any { + return any +} + +func (any *arrayAny) LastError() error { + return nil +} + +func (any *arrayAny) ToBool() bool { + return any.val.Len() != 0 +} + +func (any *arrayAny) ToInt() int { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToInt32() int32 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToInt64() int64 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToUint() uint { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToUint32() uint32 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToUint64() uint64 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToFloat32() float32 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToFloat64() float64 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToString() string { + str, _ := MarshalToString(any.val.Interface()) + return str +} + +func (any *arrayAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case int: + if firstPath < 0 || firstPath >= any.val.Len() { + return newInvalidAny(path) + } + return Wrap(any.val.Index(firstPath).Interface()) + case int32: + if '*' == firstPath { + mappedAll := make([]Any, 0) + for i := 0; i < any.val.Len(); i++ { + mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll = append(mappedAll, mapped) + } + } + return wrapArray(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *arrayAny) Size() int { + return any.val.Len() +} + +func (any *arrayAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *arrayAny) GetInterface() interface{} { + return any.val.Interface() +} diff --git a/vendor/github.com/json-iterator/go/any_bool.go b/vendor/github.com/json-iterator/go/any_bool.go new file mode 100644 index 000000000..9452324af --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_bool.go @@ -0,0 +1,137 @@ +package jsoniter + +type trueAny struct { + baseAny +} + +func (any *trueAny) LastError() error { + return nil +} + +func (any *trueAny) ToBool() bool { + return true +} + +func (any *trueAny) ToInt() int { + return 1 +} + +func (any *trueAny) ToInt32() int32 { + return 1 +} + +func (any *trueAny) ToInt64() int64 { + return 1 +} + +func (any *trueAny) ToUint() uint { + return 1 +} + +func (any *trueAny) ToUint32() uint32 { + return 1 +} + +func (any *trueAny) ToUint64() uint64 { + return 1 +} + +func (any *trueAny) ToFloat32() float32 { + return 1 +} + +func (any *trueAny) ToFloat64() float64 { + return 1 +} + +func (any *trueAny) ToString() string { + return "true" +} + +func (any *trueAny) WriteTo(stream *Stream) { + stream.WriteTrue() +} + +func (any *trueAny) Parse() *Iterator { + return nil +} + +func (any *trueAny) GetInterface() interface{} { + return true +} + +func (any *trueAny) ValueType() ValueType { + return BoolValue +} + +func (any *trueAny) MustBeValid() Any { + return any +} + +type falseAny struct { + baseAny +} + +func (any *falseAny) LastError() error { + return nil +} + +func (any *falseAny) ToBool() bool { + return false +} + +func (any *falseAny) ToInt() int { + return 0 +} + +func (any *falseAny) ToInt32() int32 { + return 0 +} + +func (any *falseAny) ToInt64() int64 { + return 0 +} + +func (any *falseAny) ToUint() uint { + return 0 +} + +func (any *falseAny) ToUint32() uint32 { + return 0 +} + +func (any *falseAny) ToUint64() uint64 { + return 0 +} + +func (any *falseAny) ToFloat32() float32 { + return 0 +} + +func (any *falseAny) ToFloat64() float64 { + return 0 +} + +func (any *falseAny) ToString() string { + return "false" +} + +func (any *falseAny) WriteTo(stream *Stream) { + stream.WriteFalse() +} + +func (any *falseAny) Parse() *Iterator { + return nil +} + +func (any *falseAny) GetInterface() interface{} { + return false +} + +func (any *falseAny) ValueType() ValueType { + return BoolValue +} + +func (any *falseAny) MustBeValid() Any { + return any +} diff --git a/vendor/github.com/json-iterator/go/any_float.go b/vendor/github.com/json-iterator/go/any_float.go new file mode 100644 index 000000000..35fdb0949 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_float.go @@ -0,0 +1,83 @@ +package jsoniter + +import ( + "strconv" +) + +type floatAny struct { + baseAny + val float64 +} + +func (any *floatAny) Parse() *Iterator { + return nil +} + +func (any *floatAny) ValueType() ValueType { + return NumberValue +} + +func (any *floatAny) MustBeValid() Any { + return any +} + +func (any *floatAny) LastError() error { + return nil +} + +func (any *floatAny) ToBool() bool { + return any.ToFloat64() != 0 +} + +func (any *floatAny) ToInt() int { + return int(any.val) +} + +func (any *floatAny) ToInt32() int32 { + return int32(any.val) +} + +func (any *floatAny) ToInt64() int64 { + return int64(any.val) +} + +func (any *floatAny) ToUint() uint { + if any.val > 0 { + return uint(any.val) + } + return 0 +} + +func (any *floatAny) ToUint32() uint32 { + if any.val > 0 { + return uint32(any.val) + } + return 0 +} + +func (any *floatAny) ToUint64() uint64 { + if any.val > 0 { + return uint64(any.val) + } + return 0 +} + +func (any *floatAny) ToFloat32() float32 { + return float32(any.val) +} + +func (any *floatAny) ToFloat64() float64 { + return any.val +} + +func (any *floatAny) ToString() string { + return strconv.FormatFloat(any.val, 'E', -1, 64) +} + +func (any *floatAny) WriteTo(stream *Stream) { + stream.WriteFloat64(any.val) +} + +func (any *floatAny) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_int32.go b/vendor/github.com/json-iterator/go/any_int32.go new file mode 100644 index 000000000..1b56f3991 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_int32.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type int32Any struct { + baseAny + val int32 +} + +func (any *int32Any) LastError() error { + return nil +} + +func (any *int32Any) ValueType() ValueType { + return NumberValue +} + +func (any *int32Any) MustBeValid() Any { + return any +} + +func (any *int32Any) ToBool() bool { + return any.val != 0 +} + +func (any *int32Any) ToInt() int { + return int(any.val) +} + +func (any *int32Any) ToInt32() int32 { + return any.val +} + +func (any *int32Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *int32Any) ToUint() uint { + return uint(any.val) +} + +func (any *int32Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *int32Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *int32Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *int32Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *int32Any) ToString() string { + return strconv.FormatInt(int64(any.val), 10) +} + +func (any *int32Any) WriteTo(stream *Stream) { + stream.WriteInt32(any.val) +} + +func (any *int32Any) Parse() *Iterator { + return nil +} + +func (any *int32Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_int64.go b/vendor/github.com/json-iterator/go/any_int64.go new file mode 100644 index 000000000..c440d72b6 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_int64.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type int64Any struct { + baseAny + val int64 +} + +func (any *int64Any) LastError() error { + return nil +} + +func (any *int64Any) ValueType() ValueType { + return NumberValue +} + +func (any *int64Any) MustBeValid() Any { + return any +} + +func (any *int64Any) ToBool() bool { + return any.val != 0 +} + +func (any *int64Any) ToInt() int { + return int(any.val) +} + +func (any *int64Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *int64Any) ToInt64() int64 { + return any.val +} + +func (any *int64Any) ToUint() uint { + return uint(any.val) +} + +func (any *int64Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *int64Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *int64Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *int64Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *int64Any) ToString() string { + return strconv.FormatInt(any.val, 10) +} + +func (any *int64Any) WriteTo(stream *Stream) { + stream.WriteInt64(any.val) +} + +func (any *int64Any) Parse() *Iterator { + return nil +} + +func (any *int64Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_invalid.go b/vendor/github.com/json-iterator/go/any_invalid.go new file mode 100644 index 000000000..1d859eac3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_invalid.go @@ -0,0 +1,82 @@ +package jsoniter + +import "fmt" + +type invalidAny struct { + baseAny + err error +} + +func newInvalidAny(path []interface{}) *invalidAny { + return &invalidAny{baseAny{}, fmt.Errorf("%v not found", path)} +} + +func (any *invalidAny) LastError() error { + return any.err +} + +func (any *invalidAny) ValueType() ValueType { + return InvalidValue +} + +func (any *invalidAny) MustBeValid() Any { + panic(any.err) +} + +func (any *invalidAny) ToBool() bool { + return false +} + +func (any *invalidAny) ToInt() int { + return 0 +} + +func (any *invalidAny) ToInt32() int32 { + return 0 +} + +func (any *invalidAny) ToInt64() int64 { + return 0 +} + +func (any *invalidAny) ToUint() uint { + return 0 +} + +func (any *invalidAny) ToUint32() uint32 { + return 0 +} + +func (any *invalidAny) ToUint64() uint64 { + return 0 +} + +func (any *invalidAny) ToFloat32() float32 { + return 0 +} + +func (any *invalidAny) ToFloat64() float64 { + return 0 +} + +func (any *invalidAny) ToString() string { + return "" +} + +func (any *invalidAny) WriteTo(stream *Stream) { +} + +func (any *invalidAny) Get(path ...interface{}) Any { + if any.err == nil { + return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)} + } + return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)} +} + +func (any *invalidAny) Parse() *Iterator { + return nil +} + +func (any *invalidAny) GetInterface() interface{} { + return nil +} diff --git a/vendor/github.com/json-iterator/go/any_nil.go b/vendor/github.com/json-iterator/go/any_nil.go new file mode 100644 index 000000000..d04cb54c1 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_nil.go @@ -0,0 +1,69 @@ +package jsoniter + +type nilAny struct { + baseAny +} + +func (any *nilAny) LastError() error { + return nil +} + +func (any *nilAny) ValueType() ValueType { + return NilValue +} + +func (any *nilAny) MustBeValid() Any { + return any +} + +func (any *nilAny) ToBool() bool { + return false +} + +func (any *nilAny) ToInt() int { + return 0 +} + +func (any *nilAny) ToInt32() int32 { + return 0 +} + +func (any *nilAny) ToInt64() int64 { + return 0 +} + +func (any *nilAny) ToUint() uint { + return 0 +} + +func (any *nilAny) ToUint32() uint32 { + return 0 +} + +func (any *nilAny) ToUint64() uint64 { + return 0 +} + +func (any *nilAny) ToFloat32() float32 { + return 0 +} + +func (any *nilAny) ToFloat64() float64 { + return 0 +} + +func (any *nilAny) ToString() string { + return "" +} + +func (any *nilAny) WriteTo(stream *Stream) { + stream.WriteNil() +} + +func (any *nilAny) Parse() *Iterator { + return nil +} + +func (any *nilAny) GetInterface() interface{} { + return nil +} diff --git a/vendor/github.com/json-iterator/go/any_number.go b/vendor/github.com/json-iterator/go/any_number.go new file mode 100644 index 000000000..9d1e901a6 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_number.go @@ -0,0 +1,123 @@ +package jsoniter + +import ( + "io" + "unsafe" +) + +type numberLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *numberLazyAny) ValueType() ValueType { + return NumberValue +} + +func (any *numberLazyAny) MustBeValid() Any { + return any +} + +func (any *numberLazyAny) LastError() error { + return any.err +} + +func (any *numberLazyAny) ToBool() bool { + return any.ToFloat64() != 0 +} + +func (any *numberLazyAny) ToInt() int { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToInt32() int32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToInt64() int64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint() uint { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint32() uint32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint64() uint64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToFloat32() float32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadFloat32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToFloat64() float64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadFloat64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *numberLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *numberLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} diff --git a/vendor/github.com/json-iterator/go/any_object.go b/vendor/github.com/json-iterator/go/any_object.go new file mode 100644 index 000000000..c44ef5c98 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_object.go @@ -0,0 +1,374 @@ +package jsoniter + +import ( + "reflect" + "unsafe" +) + +type objectLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *objectLazyAny) ValueType() ValueType { + return ObjectValue +} + +func (any *objectLazyAny) MustBeValid() Any { + return any +} + +func (any *objectLazyAny) LastError() error { + return any.err +} + +func (any *objectLazyAny) ToBool() bool { + return true +} + +func (any *objectLazyAny) ToInt() int { + return 0 +} + +func (any *objectLazyAny) ToInt32() int32 { + return 0 +} + +func (any *objectLazyAny) ToInt64() int64 { + return 0 +} + +func (any *objectLazyAny) ToUint() uint { + return 0 +} + +func (any *objectLazyAny) ToUint32() uint32 { + return 0 +} + +func (any *objectLazyAny) ToUint64() uint64 { + return 0 +} + +func (any *objectLazyAny) ToFloat32() float32 { + return 0 +} + +func (any *objectLazyAny) ToFloat64() float64 { + return 0 +} + +func (any *objectLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *objectLazyAny) ToVal(obj interface{}) { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadVal(obj) +} + +func (any *objectLazyAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case string: + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + valueBytes := locateObjectField(iter, firstPath) + if valueBytes == nil { + return newInvalidAny(path) + } + iter.ResetBytes(valueBytes) + return locatePath(iter, path[1:]) + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadMapCB(func(iter *Iterator, field string) bool { + mapped := locatePath(iter, path[1:]) + if mapped.ValueType() != InvalidValue { + mappedAll[field] = mapped + } + return true + }) + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *objectLazyAny) Keys() []string { + keys := []string{} + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadMapCB(func(iter *Iterator, field string) bool { + iter.Skip() + keys = append(keys, field) + return true + }) + return keys +} + +func (any *objectLazyAny) Size() int { + size := 0 + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + iter.Skip() + size++ + return true + }) + return size +} + +func (any *objectLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *objectLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} + +type objectAny struct { + baseAny + err error + val reflect.Value +} + +func wrapStruct(val interface{}) *objectAny { + return &objectAny{baseAny{}, nil, reflect.ValueOf(val)} +} + +func (any *objectAny) ValueType() ValueType { + return ObjectValue +} + +func (any *objectAny) MustBeValid() Any { + return any +} + +func (any *objectAny) Parse() *Iterator { + return nil +} + +func (any *objectAny) LastError() error { + return any.err +} + +func (any *objectAny) ToBool() bool { + return any.val.NumField() != 0 +} + +func (any *objectAny) ToInt() int { + return 0 +} + +func (any *objectAny) ToInt32() int32 { + return 0 +} + +func (any *objectAny) ToInt64() int64 { + return 0 +} + +func (any *objectAny) ToUint() uint { + return 0 +} + +func (any *objectAny) ToUint32() uint32 { + return 0 +} + +func (any *objectAny) ToUint64() uint64 { + return 0 +} + +func (any *objectAny) ToFloat32() float32 { + return 0 +} + +func (any *objectAny) ToFloat64() float64 { + return 0 +} + +func (any *objectAny) ToString() string { + str, err := MarshalToString(any.val.Interface()) + any.err = err + return str +} + +func (any *objectAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case string: + field := any.val.FieldByName(firstPath) + if !field.IsValid() { + return newInvalidAny(path) + } + return Wrap(field.Interface()) + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + for i := 0; i < any.val.NumField(); i++ { + field := any.val.Field(i) + if field.CanInterface() { + mapped := Wrap(field.Interface()).Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll[any.val.Type().Field(i).Name] = mapped + } + } + } + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *objectAny) Keys() []string { + keys := make([]string, 0, any.val.NumField()) + for i := 0; i < any.val.NumField(); i++ { + keys = append(keys, any.val.Type().Field(i).Name) + } + return keys +} + +func (any *objectAny) Size() int { + return any.val.NumField() +} + +func (any *objectAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *objectAny) GetInterface() interface{} { + return any.val.Interface() +} + +type mapAny struct { + baseAny + err error + val reflect.Value +} + +func wrapMap(val interface{}) *mapAny { + return &mapAny{baseAny{}, nil, reflect.ValueOf(val)} +} + +func (any *mapAny) ValueType() ValueType { + return ObjectValue +} + +func (any *mapAny) MustBeValid() Any { + return any +} + +func (any *mapAny) Parse() *Iterator { + return nil +} + +func (any *mapAny) LastError() error { + return any.err +} + +func (any *mapAny) ToBool() bool { + return true +} + +func (any *mapAny) ToInt() int { + return 0 +} + +func (any *mapAny) ToInt32() int32 { + return 0 +} + +func (any *mapAny) ToInt64() int64 { + return 0 +} + +func (any *mapAny) ToUint() uint { + return 0 +} + +func (any *mapAny) ToUint32() uint32 { + return 0 +} + +func (any *mapAny) ToUint64() uint64 { + return 0 +} + +func (any *mapAny) ToFloat32() float32 { + return 0 +} + +func (any *mapAny) ToFloat64() float64 { + return 0 +} + +func (any *mapAny) ToString() string { + str, err := MarshalToString(any.val.Interface()) + any.err = err + return str +} + +func (any *mapAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + for _, key := range any.val.MapKeys() { + keyAsStr := key.String() + element := Wrap(any.val.MapIndex(key).Interface()) + mapped := element.Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll[keyAsStr] = mapped + } + } + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + value := any.val.MapIndex(reflect.ValueOf(firstPath)) + if !value.IsValid() { + return newInvalidAny(path) + } + return Wrap(value.Interface()) + } +} + +func (any *mapAny) Keys() []string { + keys := make([]string, 0, any.val.Len()) + for _, key := range any.val.MapKeys() { + keys = append(keys, key.String()) + } + return keys +} + +func (any *mapAny) Size() int { + return any.val.Len() +} + +func (any *mapAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *mapAny) GetInterface() interface{} { + return any.val.Interface() +} diff --git a/vendor/github.com/json-iterator/go/any_str.go b/vendor/github.com/json-iterator/go/any_str.go new file mode 100644 index 000000000..1f12f6612 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_str.go @@ -0,0 +1,166 @@ +package jsoniter + +import ( + "fmt" + "strconv" +) + +type stringAny struct { + baseAny + val string +} + +func (any *stringAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} +} + +func (any *stringAny) Parse() *Iterator { + return nil +} + +func (any *stringAny) ValueType() ValueType { + return StringValue +} + +func (any *stringAny) MustBeValid() Any { + return any +} + +func (any *stringAny) LastError() error { + return nil +} + +func (any *stringAny) ToBool() bool { + str := any.ToString() + if str == "0" { + return false + } + for _, c := range str { + switch c { + case ' ', '\n', '\r', '\t': + default: + return true + } + } + return false +} + +func (any *stringAny) ToInt() int { + return int(any.ToInt64()) + +} + +func (any *stringAny) ToInt32() int32 { + return int32(any.ToInt64()) +} + +func (any *stringAny) ToInt64() int64 { + if any.val == "" { + return 0 + } + + flag := 1 + startPos := 0 + if any.val[0] == '+' || any.val[0] == '-' { + startPos = 1 + } + + if any.val[0] == '-' { + flag = -1 + } + + endPos := startPos + for i := startPos; i < len(any.val); i++ { + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + break + } + } + parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64) + return int64(flag) * parsed +} + +func (any *stringAny) ToUint() uint { + return uint(any.ToUint64()) +} + +func (any *stringAny) ToUint32() uint32 { + return uint32(any.ToUint64()) +} + +func (any *stringAny) ToUint64() uint64 { + if any.val == "" { + return 0 + } + + startPos := 0 + + if any.val[0] == '-' { + return 0 + } + if any.val[0] == '+' { + startPos = 1 + } + + endPos := startPos + for i := startPos; i < len(any.val); i++ { + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + break + } + } + parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64) + return parsed +} + +func (any *stringAny) ToFloat32() float32 { + return float32(any.ToFloat64()) +} + +func (any *stringAny) ToFloat64() float64 { + if len(any.val) == 0 { + return 0 + } + + // first char invalid + if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') { + return 0 + } + + // extract valid num expression from string + // eg 123true => 123, -12.12xxa => -12.12 + endPos := 1 + for i := 1; i < len(any.val); i++ { + if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' { + endPos = i + 1 + continue + } + + // end position is the first char which is not digit + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + endPos = i + break + } + } + parsed, _ := strconv.ParseFloat(any.val[:endPos], 64) + return parsed +} + +func (any *stringAny) ToString() string { + return any.val +} + +func (any *stringAny) WriteTo(stream *Stream) { + stream.WriteString(any.val) +} + +func (any *stringAny) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_uint32.go b/vendor/github.com/json-iterator/go/any_uint32.go new file mode 100644 index 000000000..656bbd33d --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_uint32.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type uint32Any struct { + baseAny + val uint32 +} + +func (any *uint32Any) LastError() error { + return nil +} + +func (any *uint32Any) ValueType() ValueType { + return NumberValue +} + +func (any *uint32Any) MustBeValid() Any { + return any +} + +func (any *uint32Any) ToBool() bool { + return any.val != 0 +} + +func (any *uint32Any) ToInt() int { + return int(any.val) +} + +func (any *uint32Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *uint32Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *uint32Any) ToUint() uint { + return uint(any.val) +} + +func (any *uint32Any) ToUint32() uint32 { + return any.val +} + +func (any *uint32Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *uint32Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *uint32Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *uint32Any) ToString() string { + return strconv.FormatInt(int64(any.val), 10) +} + +func (any *uint32Any) WriteTo(stream *Stream) { + stream.WriteUint32(any.val) +} + +func (any *uint32Any) Parse() *Iterator { + return nil +} + +func (any *uint32Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_uint64.go b/vendor/github.com/json-iterator/go/any_uint64.go new file mode 100644 index 000000000..7df2fce33 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_uint64.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type uint64Any struct { + baseAny + val uint64 +} + +func (any *uint64Any) LastError() error { + return nil +} + +func (any *uint64Any) ValueType() ValueType { + return NumberValue +} + +func (any *uint64Any) MustBeValid() Any { + return any +} + +func (any *uint64Any) ToBool() bool { + return any.val != 0 +} + +func (any *uint64Any) ToInt() int { + return int(any.val) +} + +func (any *uint64Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *uint64Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *uint64Any) ToUint() uint { + return uint(any.val) +} + +func (any *uint64Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *uint64Any) ToUint64() uint64 { + return any.val +} + +func (any *uint64Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *uint64Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *uint64Any) ToString() string { + return strconv.FormatUint(any.val, 10) +} + +func (any *uint64Any) WriteTo(stream *Stream) { + stream.WriteUint64(any.val) +} + +func (any *uint64Any) Parse() *Iterator { + return nil +} + +func (any *uint64Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/build.sh b/vendor/github.com/json-iterator/go/build.sh new file mode 100644 index 000000000..b45ef6883 --- /dev/null +++ b/vendor/github.com/json-iterator/go/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +set -x + +if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then + mkdir -p /tmp/build-golang/src/github.com/json-iterator + ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go +fi +export GOPATH=/tmp/build-golang +go get -u github.com/golang/dep/cmd/dep +cd /tmp/build-golang/src/github.com/json-iterator/go +exec $GOPATH/bin/dep ensure -update diff --git a/vendor/github.com/json-iterator/go/config.go b/vendor/github.com/json-iterator/go/config.go new file mode 100644 index 000000000..2adcdc3b7 --- /dev/null +++ b/vendor/github.com/json-iterator/go/config.go @@ -0,0 +1,375 @@ +package jsoniter + +import ( + "encoding/json" + "io" + "reflect" + "sync" + "unsafe" + + "github.com/modern-go/concurrent" + "github.com/modern-go/reflect2" +) + +// Config customize how the API should behave. +// The API is created from Config by Froze. +type Config struct { + IndentionStep int + MarshalFloatWith6Digits bool + EscapeHTML bool + SortMapKeys bool + UseNumber bool + DisallowUnknownFields bool + TagKey string + OnlyTaggedField bool + ValidateJsonRawMessage bool + ObjectFieldMustBeSimpleString bool + CaseSensitive bool +} + +// API the public interface of this package. +// Primary Marshal and Unmarshal. +type API interface { + IteratorPool + StreamPool + MarshalToString(v interface{}) (string, error) + Marshal(v interface{}) ([]byte, error) + MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) + UnmarshalFromString(str string, v interface{}) error + Unmarshal(data []byte, v interface{}) error + Get(data []byte, path ...interface{}) Any + NewEncoder(writer io.Writer) *Encoder + NewDecoder(reader io.Reader) *Decoder + Valid(data []byte) bool + RegisterExtension(extension Extension) + DecoderOf(typ reflect2.Type) ValDecoder + EncoderOf(typ reflect2.Type) ValEncoder +} + +// ConfigDefault the default API +var ConfigDefault = Config{ + EscapeHTML: true, +}.Froze() + +// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior +var ConfigCompatibleWithStandardLibrary = Config{ + EscapeHTML: true, + SortMapKeys: true, + ValidateJsonRawMessage: true, +}.Froze() + +// ConfigFastest marshals float with only 6 digits precision +var ConfigFastest = Config{ + EscapeHTML: false, + MarshalFloatWith6Digits: true, // will lose precession + ObjectFieldMustBeSimpleString: true, // do not unescape object field +}.Froze() + +type frozenConfig struct { + configBeforeFrozen Config + sortMapKeys bool + indentionStep int + objectFieldMustBeSimpleString bool + onlyTaggedField bool + disallowUnknownFields bool + decoderCache *concurrent.Map + encoderCache *concurrent.Map + encoderExtension Extension + decoderExtension Extension + extraExtensions []Extension + streamPool *sync.Pool + iteratorPool *sync.Pool + caseSensitive bool +} + +func (cfg *frozenConfig) initCache() { + cfg.decoderCache = concurrent.NewMap() + cfg.encoderCache = concurrent.NewMap() +} + +func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { + cfg.decoderCache.Store(cacheKey, decoder) +} + +func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { + cfg.encoderCache.Store(cacheKey, encoder) +} + +func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { + decoder, found := cfg.decoderCache.Load(cacheKey) + if found { + return decoder.(ValDecoder) + } + return nil +} + +func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { + encoder, found := cfg.encoderCache.Load(cacheKey) + if found { + return encoder.(ValEncoder) + } + return nil +} + +var cfgCache = concurrent.NewMap() + +func getFrozenConfigFromCache(cfg Config) *frozenConfig { + obj, found := cfgCache.Load(cfg) + if found { + return obj.(*frozenConfig) + } + return nil +} + +func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { + cfgCache.Store(cfg, frozenConfig) +} + +// Froze forge API from config +func (cfg Config) Froze() API { + api := &frozenConfig{ + sortMapKeys: cfg.SortMapKeys, + indentionStep: cfg.IndentionStep, + objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, + onlyTaggedField: cfg.OnlyTaggedField, + disallowUnknownFields: cfg.DisallowUnknownFields, + caseSensitive: cfg.CaseSensitive, + } + api.streamPool = &sync.Pool{ + New: func() interface{} { + return NewStream(api, nil, 512) + }, + } + api.iteratorPool = &sync.Pool{ + New: func() interface{} { + return NewIterator(api) + }, + } + api.initCache() + encoderExtension := EncoderExtension{} + decoderExtension := DecoderExtension{} + if cfg.MarshalFloatWith6Digits { + api.marshalFloatWith6Digits(encoderExtension) + } + if cfg.EscapeHTML { + api.escapeHTML(encoderExtension) + } + if cfg.UseNumber { + api.useNumber(decoderExtension) + } + if cfg.ValidateJsonRawMessage { + api.validateJsonRawMessage(encoderExtension) + } + api.encoderExtension = encoderExtension + api.decoderExtension = decoderExtension + api.configBeforeFrozen = cfg + return api +} + +func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { + api := getFrozenConfigFromCache(cfg) + if api != nil { + return api + } + api = cfg.Froze().(*frozenConfig) + for _, extension := range extraExtensions { + api.RegisterExtension(extension) + } + addFrozenConfigToCache(cfg, api) + return api +} + +func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { + encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { + rawMessage := *(*json.RawMessage)(ptr) + iter := cfg.BorrowIterator([]byte(rawMessage)) + defer cfg.ReturnIterator(iter) + iter.Read() + if iter.Error != nil && iter.Error != io.EOF { + stream.WriteRaw("null") + } else { + stream.WriteRaw(string(rawMessage)) + } + }, func(ptr unsafe.Pointer) bool { + return len(*((*json.RawMessage)(ptr))) == 0 + }} + extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder + extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder +} + +func (cfg *frozenConfig) useNumber(extension DecoderExtension) { + extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { + exitingValue := *((*interface{})(ptr)) + if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { + iter.ReadVal(exitingValue) + return + } + if iter.WhatIsNext() == NumberValue { + *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) + } else { + *((*interface{})(ptr)) = iter.Read() + } + }} +} +func (cfg *frozenConfig) getTagKey() string { + tagKey := cfg.configBeforeFrozen.TagKey + if tagKey == "" { + return "json" + } + return tagKey +} + +func (cfg *frozenConfig) RegisterExtension(extension Extension) { + cfg.extraExtensions = append(cfg.extraExtensions, extension) + copied := cfg.configBeforeFrozen + cfg.configBeforeFrozen = copied +} + +type lossyFloat32Encoder struct { +} + +func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat32Lossy(*((*float32)(ptr))) +} + +func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float32)(ptr)) == 0 +} + +type lossyFloat64Encoder struct { +} + +func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat64Lossy(*((*float64)(ptr))) +} + +func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float64)(ptr)) == 0 +} + +// EnableLossyFloatMarshalling keeps 10**(-6) precision +// for float variables for better performance. +func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { + // for better performance + extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} + extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} +} + +type htmlEscapedStringEncoder struct { +} + +func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + str := *((*string)(ptr)) + stream.WriteStringWithHTMLEscaped(str) +} + +func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*string)(ptr)) == "" +} + +func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { + encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} +} + +func (cfg *frozenConfig) cleanDecoders() { + typeDecoders = map[string]ValDecoder{} + fieldDecoders = map[string]ValDecoder{} + *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) +} + +func (cfg *frozenConfig) cleanEncoders() { + typeEncoders = map[string]ValEncoder{} + fieldEncoders = map[string]ValEncoder{} + *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) +} + +func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { + stream := cfg.BorrowStream(nil) + defer cfg.ReturnStream(stream) + stream.WriteVal(v) + if stream.Error != nil { + return "", stream.Error + } + return string(stream.Buffer()), nil +} + +func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { + stream := cfg.BorrowStream(nil) + defer cfg.ReturnStream(stream) + stream.WriteVal(v) + if stream.Error != nil { + return nil, stream.Error + } + result := stream.Buffer() + copied := make([]byte, len(result)) + copy(copied, result) + return copied, nil +} + +func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + if prefix != "" { + panic("prefix is not supported") + } + for _, r := range indent { + if r != ' ' { + panic("indent can only be space") + } + } + newCfg := cfg.configBeforeFrozen + newCfg.IndentionStep = len(indent) + return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) +} + +func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { + data := []byte(str) + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.ReadVal(v) + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error + } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") + return iter.Error +} + +func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + return locatePath(iter, path) +} + +func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.ReadVal(v) + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error + } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") + return iter.Error +} + +func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { + stream := NewStream(cfg, writer, 512) + return &Encoder{stream} +} + +func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { + iter := Parse(cfg, reader, 512) + return &Decoder{iter} +} + +func (cfg *frozenConfig) Valid(data []byte) bool { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.Skip() + return iter.Error == nil +} diff --git a/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md b/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md new file mode 100644 index 000000000..3095662b0 --- /dev/null +++ b/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md @@ -0,0 +1,7 @@ +| json type \ dest type | bool | int | uint | float |string| +| --- | --- | --- | --- |--|--| +| number | positive => true
negative => true
zero => false| 23.2 => 23
-32.1 => -32| 12.1 => 12
-12.1 => 0|as normal|same as origin| +| string | empty string => false
string "0" => false
other strings => true | "123.32" => 123
"-123.4" => -123
"123.23xxxw" => 123
"abcde12" => 0
"-32.1" => -32| 13.2 => 13
-1.1 => 0 |12.1 => 12.1
-12.3 => -12.3
12.4xxa => 12.4
+1.1e2 =>110 |same as origin| +| bool | true => true
false => false| true => 1
false => 0 | true => 1
false => 0 |true => 1
false => 0|true => "true"
false => "false"| +| object | true | 0 | 0 |0|originnal json| +| array | empty array => false
nonempty array => true| [] => 0
[1,2] => 1 | [] => 0
[1,2] => 1 |[] => 0
[1,2] => 1|original json| \ No newline at end of file diff --git a/vendor/github.com/json-iterator/go/iter.go b/vendor/github.com/json-iterator/go/iter.go new file mode 100644 index 000000000..29b31cf78 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter.go @@ -0,0 +1,349 @@ +package jsoniter + +import ( + "encoding/json" + "fmt" + "io" +) + +// ValueType the type for JSON element +type ValueType int + +const ( + // InvalidValue invalid JSON element + InvalidValue ValueType = iota + // StringValue JSON element "string" + StringValue + // NumberValue JSON element 100 or 0.10 + NumberValue + // NilValue JSON element null + NilValue + // BoolValue JSON element true or false + BoolValue + // ArrayValue JSON element [] + ArrayValue + // ObjectValue JSON element {} + ObjectValue +) + +var hexDigits []byte +var valueTypes []ValueType + +func init() { + hexDigits = make([]byte, 256) + for i := 0; i < len(hexDigits); i++ { + hexDigits[i] = 255 + } + for i := '0'; i <= '9'; i++ { + hexDigits[i] = byte(i - '0') + } + for i := 'a'; i <= 'f'; i++ { + hexDigits[i] = byte((i - 'a') + 10) + } + for i := 'A'; i <= 'F'; i++ { + hexDigits[i] = byte((i - 'A') + 10) + } + valueTypes = make([]ValueType, 256) + for i := 0; i < len(valueTypes); i++ { + valueTypes[i] = InvalidValue + } + valueTypes['"'] = StringValue + valueTypes['-'] = NumberValue + valueTypes['0'] = NumberValue + valueTypes['1'] = NumberValue + valueTypes['2'] = NumberValue + valueTypes['3'] = NumberValue + valueTypes['4'] = NumberValue + valueTypes['5'] = NumberValue + valueTypes['6'] = NumberValue + valueTypes['7'] = NumberValue + valueTypes['8'] = NumberValue + valueTypes['9'] = NumberValue + valueTypes['t'] = BoolValue + valueTypes['f'] = BoolValue + valueTypes['n'] = NilValue + valueTypes['['] = ArrayValue + valueTypes['{'] = ObjectValue +} + +// Iterator is a io.Reader like object, with JSON specific read functions. +// Error is not returned as return value, but stored as Error member on this iterator instance. +type Iterator struct { + cfg *frozenConfig + reader io.Reader + buf []byte + head int + tail int + depth int + captureStartedAt int + captured []byte + Error error + Attachment interface{} // open for customized decoder +} + +// NewIterator creates an empty Iterator instance +func NewIterator(cfg API) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: nil, + buf: nil, + head: 0, + tail: 0, + depth: 0, + } +} + +// Parse creates an Iterator instance from io.Reader +func Parse(cfg API, reader io.Reader, bufSize int) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: reader, + buf: make([]byte, bufSize), + head: 0, + tail: 0, + depth: 0, + } +} + +// ParseBytes creates an Iterator instance from byte array +func ParseBytes(cfg API, input []byte) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: nil, + buf: input, + head: 0, + tail: len(input), + depth: 0, + } +} + +// ParseString creates an Iterator instance from string +func ParseString(cfg API, input string) *Iterator { + return ParseBytes(cfg, []byte(input)) +} + +// Pool returns a pool can provide more iterator with same configuration +func (iter *Iterator) Pool() IteratorPool { + return iter.cfg +} + +// Reset reuse iterator instance by specifying another reader +func (iter *Iterator) Reset(reader io.Reader) *Iterator { + iter.reader = reader + iter.head = 0 + iter.tail = 0 + iter.depth = 0 + return iter +} + +// ResetBytes reuse iterator instance by specifying another byte array as input +func (iter *Iterator) ResetBytes(input []byte) *Iterator { + iter.reader = nil + iter.buf = input + iter.head = 0 + iter.tail = len(input) + iter.depth = 0 + return iter +} + +// WhatIsNext gets ValueType of relatively next json element +func (iter *Iterator) WhatIsNext() ValueType { + valueType := valueTypes[iter.nextToken()] + iter.unreadByte() + return valueType +} + +func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\t', '\r': + continue + } + iter.head = i + return false + } + return true +} + +func (iter *Iterator) isObjectEnd() bool { + c := iter.nextToken() + if c == ',' { + return false + } + if c == '}' { + return true + } + iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c})) + return true +} + +func (iter *Iterator) nextToken() byte { + // a variation of skip whitespaces, returning the next non-whitespace token + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\t', '\r': + continue + } + iter.head = i + 1 + return c + } + if !iter.loadMore() { + return 0 + } + } +} + +// ReportError record a error in iterator instance with current position. +func (iter *Iterator) ReportError(operation string, msg string) { + if iter.Error != nil { + if iter.Error != io.EOF { + return + } + } + peekStart := iter.head - 10 + if peekStart < 0 { + peekStart = 0 + } + peekEnd := iter.head + 10 + if peekEnd > iter.tail { + peekEnd = iter.tail + } + parsing := string(iter.buf[peekStart:peekEnd]) + contextStart := iter.head - 50 + if contextStart < 0 { + contextStart = 0 + } + contextEnd := iter.head + 50 + if contextEnd > iter.tail { + contextEnd = iter.tail + } + context := string(iter.buf[contextStart:contextEnd]) + iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...", + operation, msg, iter.head-peekStart, parsing, context) +} + +// CurrentBuffer gets current buffer as string for debugging purpose +func (iter *Iterator) CurrentBuffer() string { + peekStart := iter.head - 10 + if peekStart < 0 { + peekStart = 0 + } + return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head, + string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail])) +} + +func (iter *Iterator) readByte() (ret byte) { + if iter.head == iter.tail { + if iter.loadMore() { + ret = iter.buf[iter.head] + iter.head++ + return ret + } + return 0 + } + ret = iter.buf[iter.head] + iter.head++ + return ret +} + +func (iter *Iterator) loadMore() bool { + if iter.reader == nil { + if iter.Error == nil { + iter.head = iter.tail + iter.Error = io.EOF + } + return false + } + if iter.captured != nil { + iter.captured = append(iter.captured, + iter.buf[iter.captureStartedAt:iter.tail]...) + iter.captureStartedAt = 0 + } + for { + n, err := iter.reader.Read(iter.buf) + if n == 0 { + if err != nil { + if iter.Error == nil { + iter.Error = err + } + return false + } + } else { + iter.head = 0 + iter.tail = n + return true + } + } +} + +func (iter *Iterator) unreadByte() { + if iter.Error != nil { + return + } + iter.head-- + return +} + +// Read read the next JSON element as generic interface{}. +func (iter *Iterator) Read() interface{} { + valueType := iter.WhatIsNext() + switch valueType { + case StringValue: + return iter.ReadString() + case NumberValue: + if iter.cfg.configBeforeFrozen.UseNumber { + return json.Number(iter.readNumberAsString()) + } + return iter.ReadFloat64() + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + return nil + case BoolValue: + return iter.ReadBool() + case ArrayValue: + arr := []interface{}{} + iter.ReadArrayCB(func(iter *Iterator) bool { + var elem interface{} + iter.ReadVal(&elem) + arr = append(arr, elem) + return true + }) + return arr + case ObjectValue: + obj := map[string]interface{}{} + iter.ReadMapCB(func(Iter *Iterator, field string) bool { + var elem interface{} + iter.ReadVal(&elem) + obj[field] = elem + return true + }) + return obj + default: + iter.ReportError("Read", fmt.Sprintf("unexpected value type: %v", valueType)) + return nil + } +} + +// limit maximum depth of nesting, as allowed by https://tools.ietf.org/html/rfc7159#section-9 +const maxDepth = 10000 + +func (iter *Iterator) incrementDepth() (success bool) { + iter.depth++ + if iter.depth <= maxDepth { + return true + } + iter.ReportError("incrementDepth", "exceeded max depth") + return false +} + +func (iter *Iterator) decrementDepth() (success bool) { + iter.depth-- + if iter.depth >= 0 { + return true + } + iter.ReportError("decrementDepth", "unexpected negative nesting") + return false +} diff --git a/vendor/github.com/json-iterator/go/iter_array.go b/vendor/github.com/json-iterator/go/iter_array.go new file mode 100644 index 000000000..204fe0e09 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_array.go @@ -0,0 +1,64 @@ +package jsoniter + +// ReadArray read array element, tells if the array has more element to read. +func (iter *Iterator) ReadArray() (ret bool) { + c := iter.nextToken() + switch c { + case 'n': + iter.skipThreeBytes('u', 'l', 'l') + return false // null + case '[': + c = iter.nextToken() + if c != ']' { + iter.unreadByte() + return true + } + return false + case ']': + return false + case ',': + return true + default: + iter.ReportError("ReadArray", "expect [ or , or ] or n, but found "+string([]byte{c})) + return + } +} + +// ReadArrayCB read array with callback +func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) { + c := iter.nextToken() + if c == '[' { + if !iter.incrementDepth() { + return false + } + c = iter.nextToken() + if c != ']' { + iter.unreadByte() + if !callback(iter) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + for c == ',' { + if !callback(iter) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + } + if c != ']' { + iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c})) + iter.decrementDepth() + return false + } + return iter.decrementDepth() + } + return iter.decrementDepth() + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c})) + return false +} diff --git a/vendor/github.com/json-iterator/go/iter_float.go b/vendor/github.com/json-iterator/go/iter_float.go new file mode 100644 index 000000000..8a3d8b6fb --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_float.go @@ -0,0 +1,342 @@ +package jsoniter + +import ( + "encoding/json" + "io" + "math/big" + "strconv" + "strings" + "unsafe" +) + +var floatDigits []int8 + +const invalidCharForNumber = int8(-1) +const endOfNumber = int8(-2) +const dotInNumber = int8(-3) + +func init() { + floatDigits = make([]int8, 256) + for i := 0; i < len(floatDigits); i++ { + floatDigits[i] = invalidCharForNumber + } + for i := int8('0'); i <= int8('9'); i++ { + floatDigits[i] = i - int8('0') + } + floatDigits[','] = endOfNumber + floatDigits[']'] = endOfNumber + floatDigits['}'] = endOfNumber + floatDigits[' '] = endOfNumber + floatDigits['\t'] = endOfNumber + floatDigits['\n'] = endOfNumber + floatDigits['.'] = dotInNumber +} + +// ReadBigFloat read big.Float +func (iter *Iterator) ReadBigFloat() (ret *big.Float) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return nil + } + prec := 64 + if len(str) > prec { + prec = len(str) + } + val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero) + if err != nil { + iter.Error = err + return nil + } + return val +} + +// ReadBigInt read big.Int +func (iter *Iterator) ReadBigInt() (ret *big.Int) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return nil + } + ret = big.NewInt(0) + var success bool + ret, success = ret.SetString(str, 10) + if !success { + iter.ReportError("ReadBigInt", "invalid big int") + return nil + } + return ret +} + +//ReadFloat32 read float32 +func (iter *Iterator) ReadFloat32() (ret float32) { + c := iter.nextToken() + if c == '-' { + return -iter.readPositiveFloat32() + } + iter.unreadByte() + return iter.readPositiveFloat32() +} + +func (iter *Iterator) readPositiveFloat32() (ret float32) { + i := iter.head + // first char + if i == iter.tail { + return iter.readFloat32SlowPath() + } + c := iter.buf[i] + i++ + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat32SlowPath() + case endOfNumber: + iter.ReportError("readFloat32", "empty number") + return + case dotInNumber: + iter.ReportError("readFloat32", "leading dot is invalid") + return + case 0: + if i == iter.tail { + return iter.readFloat32SlowPath() + } + c = iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.ReportError("readFloat32", "leading zero is invalid") + return + } + } + value := uint64(ind) + // chars before dot +non_decimal_loop: + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat32SlowPath() + case endOfNumber: + iter.head = i + return float32(value) + case dotInNumber: + break non_decimal_loop + } + if value > uint64SafeToMultiple10 { + return iter.readFloat32SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; + } + // chars after dot + if c == '.' { + i++ + decimalPlaces := 0 + if i == iter.tail { + return iter.readFloat32SlowPath() + } + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case endOfNumber: + if decimalPlaces > 0 && decimalPlaces < len(pow10) { + iter.head = i + return float32(float64(value) / float64(pow10[decimalPlaces])) + } + // too many decimal places + return iter.readFloat32SlowPath() + case invalidCharForNumber, dotInNumber: + return iter.readFloat32SlowPath() + } + decimalPlaces++ + if value > uint64SafeToMultiple10 { + return iter.readFloat32SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) + } + } + return iter.readFloat32SlowPath() +} + +func (iter *Iterator) readNumberAsString() (ret string) { + strBuf := [16]byte{} + str := strBuf[0:0] +load_loop: + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case '+', '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + str = append(str, c) + continue + default: + iter.head = i + break load_loop + } + } + if !iter.loadMore() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + return + } + if len(str) == 0 { + iter.ReportError("readNumberAsString", "invalid number") + } + return *(*string)(unsafe.Pointer(&str)) +} + +func (iter *Iterator) readFloat32SlowPath() (ret float32) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return + } + errMsg := validateFloat(str) + if errMsg != "" { + iter.ReportError("readFloat32SlowPath", errMsg) + return + } + val, err := strconv.ParseFloat(str, 32) + if err != nil { + iter.Error = err + return + } + return float32(val) +} + +// ReadFloat64 read float64 +func (iter *Iterator) ReadFloat64() (ret float64) { + c := iter.nextToken() + if c == '-' { + return -iter.readPositiveFloat64() + } + iter.unreadByte() + return iter.readPositiveFloat64() +} + +func (iter *Iterator) readPositiveFloat64() (ret float64) { + i := iter.head + // first char + if i == iter.tail { + return iter.readFloat64SlowPath() + } + c := iter.buf[i] + i++ + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat64SlowPath() + case endOfNumber: + iter.ReportError("readFloat64", "empty number") + return + case dotInNumber: + iter.ReportError("readFloat64", "leading dot is invalid") + return + case 0: + if i == iter.tail { + return iter.readFloat64SlowPath() + } + c = iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.ReportError("readFloat64", "leading zero is invalid") + return + } + } + value := uint64(ind) + // chars before dot +non_decimal_loop: + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat64SlowPath() + case endOfNumber: + iter.head = i + return float64(value) + case dotInNumber: + break non_decimal_loop + } + if value > uint64SafeToMultiple10 { + return iter.readFloat64SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; + } + // chars after dot + if c == '.' { + i++ + decimalPlaces := 0 + if i == iter.tail { + return iter.readFloat64SlowPath() + } + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case endOfNumber: + if decimalPlaces > 0 && decimalPlaces < len(pow10) { + iter.head = i + return float64(value) / float64(pow10[decimalPlaces]) + } + // too many decimal places + return iter.readFloat64SlowPath() + case invalidCharForNumber, dotInNumber: + return iter.readFloat64SlowPath() + } + decimalPlaces++ + if value > uint64SafeToMultiple10 { + return iter.readFloat64SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) + if value > maxFloat64 { + return iter.readFloat64SlowPath() + } + } + } + return iter.readFloat64SlowPath() +} + +func (iter *Iterator) readFloat64SlowPath() (ret float64) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return + } + errMsg := validateFloat(str) + if errMsg != "" { + iter.ReportError("readFloat64SlowPath", errMsg) + return + } + val, err := strconv.ParseFloat(str, 64) + if err != nil { + iter.Error = err + return + } + return val +} + +func validateFloat(str string) string { + // strconv.ParseFloat is not validating `1.` or `1.e1` + if len(str) == 0 { + return "empty number" + } + if str[0] == '-' { + return "-- is not valid" + } + dotPos := strings.IndexByte(str, '.') + if dotPos != -1 { + if dotPos == len(str)-1 { + return "dot can not be last character" + } + switch str[dotPos+1] { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + default: + return "missing digit after dot" + } + } + return "" +} + +// ReadNumber read json.Number +func (iter *Iterator) ReadNumber() (ret json.Number) { + return json.Number(iter.readNumberAsString()) +} diff --git a/vendor/github.com/json-iterator/go/iter_int.go b/vendor/github.com/json-iterator/go/iter_int.go new file mode 100644 index 000000000..d786a89fe --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_int.go @@ -0,0 +1,346 @@ +package jsoniter + +import ( + "math" + "strconv" +) + +var intDigits []int8 + +const uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1 +const uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1 +const maxFloat64 = 1<<53 - 1 + +func init() { + intDigits = make([]int8, 256) + for i := 0; i < len(intDigits); i++ { + intDigits[i] = invalidCharForNumber + } + for i := int8('0'); i <= int8('9'); i++ { + intDigits[i] = i - int8('0') + } +} + +// ReadUint read uint +func (iter *Iterator) ReadUint() uint { + if strconv.IntSize == 32 { + return uint(iter.ReadUint32()) + } + return uint(iter.ReadUint64()) +} + +// ReadInt read int +func (iter *Iterator) ReadInt() int { + if strconv.IntSize == 32 { + return int(iter.ReadInt32()) + } + return int(iter.ReadInt64()) +} + +// ReadInt8 read int8 +func (iter *Iterator) ReadInt8() (ret int8) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt8+1 { + iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int8(val) + } + val := iter.readUint32(c) + if val > math.MaxInt8 { + iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int8(val) +} + +// ReadUint8 read uint8 +func (iter *Iterator) ReadUint8() (ret uint8) { + val := iter.readUint32(iter.nextToken()) + if val > math.MaxUint8 { + iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return uint8(val) +} + +// ReadInt16 read int16 +func (iter *Iterator) ReadInt16() (ret int16) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt16+1 { + iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int16(val) + } + val := iter.readUint32(c) + if val > math.MaxInt16 { + iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int16(val) +} + +// ReadUint16 read uint16 +func (iter *Iterator) ReadUint16() (ret uint16) { + val := iter.readUint32(iter.nextToken()) + if val > math.MaxUint16 { + iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return uint16(val) +} + +// ReadInt32 read int32 +func (iter *Iterator) ReadInt32() (ret int32) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt32+1 { + iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int32(val) + } + val := iter.readUint32(c) + if val > math.MaxInt32 { + iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int32(val) +} + +// ReadUint32 read uint32 +func (iter *Iterator) ReadUint32() (ret uint32) { + return iter.readUint32(iter.nextToken()) +} + +func (iter *Iterator) readUint32(c byte) (ret uint32) { + ind := intDigits[c] + if ind == 0 { + iter.assertInteger() + return 0 // single zero + } + if ind == invalidCharForNumber { + iter.ReportError("readUint32", "unexpected character: "+string([]byte{byte(ind)})) + return + } + value := uint32(ind) + if iter.tail-iter.head > 10 { + i := iter.head + ind2 := intDigits[iter.buf[i]] + if ind2 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + i++ + ind3 := intDigits[iter.buf[i]] + if ind3 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10 + uint32(ind2) + } + //iter.head = i + 1 + //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + i++ + ind4 := intDigits[iter.buf[i]] + if ind4 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100 + uint32(ind2)*10 + uint32(ind3) + } + i++ + ind5 := intDigits[iter.buf[i]] + if ind5 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000 + uint32(ind2)*100 + uint32(ind3)*10 + uint32(ind4) + } + i++ + ind6 := intDigits[iter.buf[i]] + if ind6 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10000 + uint32(ind2)*1000 + uint32(ind3)*100 + uint32(ind4)*10 + uint32(ind5) + } + i++ + ind7 := intDigits[iter.buf[i]] + if ind7 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100000 + uint32(ind2)*10000 + uint32(ind3)*1000 + uint32(ind4)*100 + uint32(ind5)*10 + uint32(ind6) + } + i++ + ind8 := intDigits[iter.buf[i]] + if ind8 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000000 + uint32(ind2)*100000 + uint32(ind3)*10000 + uint32(ind4)*1000 + uint32(ind5)*100 + uint32(ind6)*10 + uint32(ind7) + } + i++ + ind9 := intDigits[iter.buf[i]] + value = value*10000000 + uint32(ind2)*1000000 + uint32(ind3)*100000 + uint32(ind4)*10000 + uint32(ind5)*1000 + uint32(ind6)*100 + uint32(ind7)*10 + uint32(ind8) + iter.head = i + if ind9 == invalidCharForNumber { + iter.assertInteger() + return value + } + } + for { + for i := iter.head; i < iter.tail; i++ { + ind = intDigits[iter.buf[i]] + if ind == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + if value > uint32SafeToMultiply10 { + value2 := (value << 3) + (value << 1) + uint32(ind) + if value2 < value { + iter.ReportError("readUint32", "overflow") + return + } + value = value2 + continue + } + value = (value << 3) + (value << 1) + uint32(ind) + } + if !iter.loadMore() { + iter.assertInteger() + return value + } + } +} + +// ReadInt64 read int64 +func (iter *Iterator) ReadInt64() (ret int64) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint64(iter.readByte()) + if val > math.MaxInt64+1 { + iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) + return + } + return -int64(val) + } + val := iter.readUint64(c) + if val > math.MaxInt64 { + iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) + return + } + return int64(val) +} + +// ReadUint64 read uint64 +func (iter *Iterator) ReadUint64() uint64 { + return iter.readUint64(iter.nextToken()) +} + +func (iter *Iterator) readUint64(c byte) (ret uint64) { + ind := intDigits[c] + if ind == 0 { + iter.assertInteger() + return 0 // single zero + } + if ind == invalidCharForNumber { + iter.ReportError("readUint64", "unexpected character: "+string([]byte{byte(ind)})) + return + } + value := uint64(ind) + if iter.tail-iter.head > 10 { + i := iter.head + ind2 := intDigits[iter.buf[i]] + if ind2 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + i++ + ind3 := intDigits[iter.buf[i]] + if ind3 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10 + uint64(ind2) + } + //iter.head = i + 1 + //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + i++ + ind4 := intDigits[iter.buf[i]] + if ind4 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100 + uint64(ind2)*10 + uint64(ind3) + } + i++ + ind5 := intDigits[iter.buf[i]] + if ind5 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000 + uint64(ind2)*100 + uint64(ind3)*10 + uint64(ind4) + } + i++ + ind6 := intDigits[iter.buf[i]] + if ind6 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10000 + uint64(ind2)*1000 + uint64(ind3)*100 + uint64(ind4)*10 + uint64(ind5) + } + i++ + ind7 := intDigits[iter.buf[i]] + if ind7 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100000 + uint64(ind2)*10000 + uint64(ind3)*1000 + uint64(ind4)*100 + uint64(ind5)*10 + uint64(ind6) + } + i++ + ind8 := intDigits[iter.buf[i]] + if ind8 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000000 + uint64(ind2)*100000 + uint64(ind3)*10000 + uint64(ind4)*1000 + uint64(ind5)*100 + uint64(ind6)*10 + uint64(ind7) + } + i++ + ind9 := intDigits[iter.buf[i]] + value = value*10000000 + uint64(ind2)*1000000 + uint64(ind3)*100000 + uint64(ind4)*10000 + uint64(ind5)*1000 + uint64(ind6)*100 + uint64(ind7)*10 + uint64(ind8) + iter.head = i + if ind9 == invalidCharForNumber { + iter.assertInteger() + return value + } + } + for { + for i := iter.head; i < iter.tail; i++ { + ind = intDigits[iter.buf[i]] + if ind == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + if value > uint64SafeToMultiple10 { + value2 := (value << 3) + (value << 1) + uint64(ind) + if value2 < value { + iter.ReportError("readUint64", "overflow") + return + } + value = value2 + continue + } + value = (value << 3) + (value << 1) + uint64(ind) + } + if !iter.loadMore() { + iter.assertInteger() + return value + } + } +} + +func (iter *Iterator) assertInteger() { + if iter.head < iter.tail && iter.buf[iter.head] == '.' { + iter.ReportError("assertInteger", "can not decode float as int") + } +} diff --git a/vendor/github.com/json-iterator/go/iter_object.go b/vendor/github.com/json-iterator/go/iter_object.go new file mode 100644 index 000000000..58ee89c84 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_object.go @@ -0,0 +1,267 @@ +package jsoniter + +import ( + "fmt" + "strings" +) + +// ReadObject read one field from object. +// If object ended, returns empty string. +// Otherwise, returns the field name. +func (iter *Iterator) ReadObject() (ret string) { + c := iter.nextToken() + switch c { + case 'n': + iter.skipThreeBytes('u', 'l', 'l') + return "" // null + case '{': + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field + } + if c == '}' { + return "" // end of object + } + iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) + return + case ',': + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field + case '}': + return "" // end of object + default: + iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c}))) + return + } +} + +// CaseInsensitive +func (iter *Iterator) readFieldHash() int64 { + hash := int64(0x811c9dc5) + c := iter.nextToken() + if c != '"' { + iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c})) + return 0 + } + for { + for i := iter.head; i < iter.tail; i++ { + // require ascii string and no escape + b := iter.buf[i] + if b == '\\' { + iter.head = i + for _, b := range iter.readStringSlowPath() { + if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { + b += 'a' - 'A' + } + hash ^= int64(b) + hash *= 0x1000193 + } + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 + } + return hash + } + if b == '"' { + iter.head = i + 1 + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 + } + return hash + } + if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { + b += 'a' - 'A' + } + hash ^= int64(b) + hash *= 0x1000193 + } + if !iter.loadMore() { + iter.ReportError("readFieldHash", `incomplete field name`) + return 0 + } + } +} + +func calcHash(str string, caseSensitive bool) int64 { + if !caseSensitive { + str = strings.ToLower(str) + } + hash := int64(0x811c9dc5) + for _, b := range []byte(str) { + hash ^= int64(b) + hash *= 0x1000193 + } + return int64(hash) +} + +// ReadObjectCB read object with callback, the key is ascii only and field name not copied +func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { + c := iter.nextToken() + var field string + if c == '{' { + if !iter.incrementDepth() { + return false + } + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + for c == ',' { + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + } + if c != '}' { + iter.ReportError("ReadObjectCB", `object not ended with }`) + iter.decrementDepth() + return false + } + return iter.decrementDepth() + } + if c == '}' { + return iter.decrementDepth() + } + iter.ReportError("ReadObjectCB", `expect " after {, but found `+string([]byte{c})) + iter.decrementDepth() + return false + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c})) + return false +} + +// ReadMapCB read map with callback, the key can be any string +func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool { + c := iter.nextToken() + if c == '{' { + if !iter.incrementDepth() { + return false + } + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field := iter.ReadString() + if iter.nextToken() != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + iter.decrementDepth() + return false + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + for c == ',' { + field = iter.ReadString() + if iter.nextToken() != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + iter.decrementDepth() + return false + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + } + if c != '}' { + iter.ReportError("ReadMapCB", `object not ended with }`) + iter.decrementDepth() + return false + } + return iter.decrementDepth() + } + if c == '}' { + return iter.decrementDepth() + } + iter.ReportError("ReadMapCB", `expect " after {, but found `+string([]byte{c})) + iter.decrementDepth() + return false + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) + return false +} + +func (iter *Iterator) readObjectStart() bool { + c := iter.nextToken() + if c == '{' { + c = iter.nextToken() + if c == '}' { + return false + } + iter.unreadByte() + return true + } else if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return false + } + iter.ReportError("readObjectStart", "expect { or n, but found "+string([]byte{c})) + return false +} + +func (iter *Iterator) readObjectFieldAsBytes() (ret []byte) { + str := iter.ReadStringAsSlice() + if iter.skipWhitespacesWithoutLoadMore() { + if ret == nil { + ret = make([]byte, len(str)) + copy(ret, str) + } + if !iter.loadMore() { + return + } + } + if iter.buf[iter.head] != ':' { + iter.ReportError("readObjectFieldAsBytes", "expect : after object field, but found "+string([]byte{iter.buf[iter.head]})) + return + } + iter.head++ + if iter.skipWhitespacesWithoutLoadMore() { + if ret == nil { + ret = make([]byte, len(str)) + copy(ret, str) + } + if !iter.loadMore() { + return + } + } + if ret == nil { + return str + } + return ret +} diff --git a/vendor/github.com/json-iterator/go/iter_skip.go b/vendor/github.com/json-iterator/go/iter_skip.go new file mode 100644 index 000000000..e91eefb15 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip.go @@ -0,0 +1,130 @@ +package jsoniter + +import "fmt" + +// ReadNil reads a json object as nil and +// returns whether it's a nil or not +func (iter *Iterator) ReadNil() (ret bool) { + c := iter.nextToken() + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') // null + return true + } + iter.unreadByte() + return false +} + +// ReadBool reads a json object as BoolValue +func (iter *Iterator) ReadBool() (ret bool) { + c := iter.nextToken() + if c == 't' { + iter.skipThreeBytes('r', 'u', 'e') + return true + } + if c == 'f' { + iter.skipFourBytes('a', 'l', 's', 'e') + return false + } + iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c})) + return +} + +// SkipAndReturnBytes skip next JSON element, and return its content as []byte. +// The []byte can be kept, it is a copy of data. +func (iter *Iterator) SkipAndReturnBytes() []byte { + iter.startCapture(iter.head) + iter.Skip() + return iter.stopCapture() +} + +// SkipAndAppendBytes skips next JSON element and appends its content to +// buffer, returning the result. +func (iter *Iterator) SkipAndAppendBytes(buf []byte) []byte { + iter.startCaptureTo(buf, iter.head) + iter.Skip() + return iter.stopCapture() +} + +func (iter *Iterator) startCaptureTo(buf []byte, captureStartedAt int) { + if iter.captured != nil { + panic("already in capture mode") + } + iter.captureStartedAt = captureStartedAt + iter.captured = buf +} + +func (iter *Iterator) startCapture(captureStartedAt int) { + iter.startCaptureTo(make([]byte, 0, 32), captureStartedAt) +} + +func (iter *Iterator) stopCapture() []byte { + if iter.captured == nil { + panic("not in capture mode") + } + captured := iter.captured + remaining := iter.buf[iter.captureStartedAt:iter.head] + iter.captureStartedAt = -1 + iter.captured = nil + return append(captured, remaining...) +} + +// Skip skips a json object and positions to relatively the next json object +func (iter *Iterator) Skip() { + c := iter.nextToken() + switch c { + case '"': + iter.skipString() + case 'n': + iter.skipThreeBytes('u', 'l', 'l') // null + case 't': + iter.skipThreeBytes('r', 'u', 'e') // true + case 'f': + iter.skipFourBytes('a', 'l', 's', 'e') // false + case '0': + iter.unreadByte() + iter.ReadFloat32() + case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.skipNumber() + case '[': + iter.skipArray() + case '{': + iter.skipObject() + default: + iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) + return + } +} + +func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) { + if iter.readByte() != b1 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b2 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b3 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b4 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } +} + +func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) { + if iter.readByte() != b1 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } + if iter.readByte() != b2 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } + if iter.readByte() != b3 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } +} diff --git a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go new file mode 100644 index 000000000..9303de41e --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go @@ -0,0 +1,163 @@ +//+build jsoniter_sloppy + +package jsoniter + +// sloppy but faster implementation, do not validate the input json + +func (iter *Iterator) skipNumber() { + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\r', '\t', ',', '}', ']': + iter.head = i + return + } + } + if !iter.loadMore() { + return + } + } +} + +func (iter *Iterator) skipArray() { + level := 1 + if !iter.incrementDepth() { + return + } + for { + for i := iter.head; i < iter.tail; i++ { + switch iter.buf[i] { + case '"': // If inside string, skip it + iter.head = i + 1 + iter.skipString() + i = iter.head - 1 // it will be i++ soon + case '[': // If open symbol, increase level + level++ + if !iter.incrementDepth() { + return + } + case ']': // If close symbol, increase level + level-- + if !iter.decrementDepth() { + return + } + + // If we have returned to the original level, we're done + if level == 0 { + iter.head = i + 1 + return + } + } + } + if !iter.loadMore() { + iter.ReportError("skipObject", "incomplete array") + return + } + } +} + +func (iter *Iterator) skipObject() { + level := 1 + if !iter.incrementDepth() { + return + } + + for { + for i := iter.head; i < iter.tail; i++ { + switch iter.buf[i] { + case '"': // If inside string, skip it + iter.head = i + 1 + iter.skipString() + i = iter.head - 1 // it will be i++ soon + case '{': // If open symbol, increase level + level++ + if !iter.incrementDepth() { + return + } + case '}': // If close symbol, increase level + level-- + if !iter.decrementDepth() { + return + } + + // If we have returned to the original level, we're done + if level == 0 { + iter.head = i + 1 + return + } + } + } + if !iter.loadMore() { + iter.ReportError("skipObject", "incomplete object") + return + } + } +} + +func (iter *Iterator) skipString() { + for { + end, escaped := iter.findStringEnd() + if end == -1 { + if !iter.loadMore() { + iter.ReportError("skipString", "incomplete string") + return + } + if escaped { + iter.head = 1 // skip the first char as last char read is \ + } + } else { + iter.head = end + return + } + } +} + +// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go +// Tries to find the end of string +// Support if string contains escaped quote symbols. +func (iter *Iterator) findStringEnd() (int, bool) { + escaped := false + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + if !escaped { + return i + 1, false + } + j := i - 1 + for { + if j < iter.head || iter.buf[j] != '\\' { + // even number of backslashes + // either end of buffer, or " found + return i + 1, true + } + j-- + if j < iter.head || iter.buf[j] != '\\' { + // odd number of backslashes + // it is \" or \\\" + break + } + j-- + } + } else if c == '\\' { + escaped = true + } + } + j := iter.tail - 1 + for { + if j < iter.head || iter.buf[j] != '\\' { + // even number of backslashes + // either end of buffer, or " found + return -1, false // do not end with \ + } + j-- + if j < iter.head || iter.buf[j] != '\\' { + // odd number of backslashes + // it is \" or \\\" + break + } + j-- + + } + return -1, true // end with \ +} diff --git a/vendor/github.com/json-iterator/go/iter_skip_strict.go b/vendor/github.com/json-iterator/go/iter_skip_strict.go new file mode 100644 index 000000000..6cf66d043 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip_strict.go @@ -0,0 +1,99 @@ +//+build !jsoniter_sloppy + +package jsoniter + +import ( + "fmt" + "io" +) + +func (iter *Iterator) skipNumber() { + if !iter.trySkipNumber() { + iter.unreadByte() + if iter.Error != nil && iter.Error != io.EOF { + return + } + iter.ReadFloat64() + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = nil + iter.ReadBigFloat() + } + } +} + +func (iter *Iterator) trySkipNumber() bool { + dotFound := false + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + case '.': + if dotFound { + iter.ReportError("validateNumber", `more than one dot found in number`) + return true // already failed + } + if i+1 == iter.tail { + return false + } + c = iter.buf[i+1] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + default: + iter.ReportError("validateNumber", `missing digit after dot`) + return true // already failed + } + dotFound = true + default: + switch c { + case ',', ']', '}', ' ', '\t', '\n', '\r': + if iter.head == i { + return false // if - without following digits + } + iter.head = i + return true // must be valid + } + return false // may be invalid + } + } + return false +} + +func (iter *Iterator) skipString() { + if !iter.trySkipString() { + iter.unreadByte() + iter.ReadString() + } +} + +func (iter *Iterator) trySkipString() bool { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + iter.head = i + 1 + return true // valid + } else if c == '\\' { + return false + } else if c < ' ' { + iter.ReportError("trySkipString", + fmt.Sprintf(`invalid control character found: %d`, c)) + return true // already failed + } + } + return false +} + +func (iter *Iterator) skipObject() { + iter.unreadByte() + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + iter.Skip() + return true + }) +} + +func (iter *Iterator) skipArray() { + iter.unreadByte() + iter.ReadArrayCB(func(iter *Iterator) bool { + iter.Skip() + return true + }) +} diff --git a/vendor/github.com/json-iterator/go/iter_str.go b/vendor/github.com/json-iterator/go/iter_str.go new file mode 100644 index 000000000..adc487ea8 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_str.go @@ -0,0 +1,215 @@ +package jsoniter + +import ( + "fmt" + "unicode/utf16" +) + +// ReadString read string from iterator +func (iter *Iterator) ReadString() (ret string) { + c := iter.nextToken() + if c == '"' { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + ret = string(iter.buf[iter.head:i]) + iter.head = i + 1 + return ret + } else if c == '\\' { + break + } else if c < ' ' { + iter.ReportError("ReadString", + fmt.Sprintf(`invalid control character found: %d`, c)) + return + } + } + return iter.readStringSlowPath() + } else if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return "" + } + iter.ReportError("ReadString", `expects " or n, but found `+string([]byte{c})) + return +} + +func (iter *Iterator) readStringSlowPath() (ret string) { + var str []byte + var c byte + for iter.Error == nil { + c = iter.readByte() + if c == '"' { + return string(str) + } + if c == '\\' { + c = iter.readByte() + str = iter.readEscapedChar(c, str) + } else { + str = append(str, c) + } + } + iter.ReportError("readStringSlowPath", "unexpected end of input") + return +} + +func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte { + switch c { + case 'u': + r := iter.readU4() + if utf16.IsSurrogate(r) { + c = iter.readByte() + if iter.Error != nil { + return nil + } + if c != '\\' { + iter.unreadByte() + str = appendRune(str, r) + return str + } + c = iter.readByte() + if iter.Error != nil { + return nil + } + if c != 'u' { + str = appendRune(str, r) + return iter.readEscapedChar(c, str) + } + r2 := iter.readU4() + if iter.Error != nil { + return nil + } + combined := utf16.DecodeRune(r, r2) + if combined == '\uFFFD' { + str = appendRune(str, r) + str = appendRune(str, r2) + } else { + str = appendRune(str, combined) + } + } else { + str = appendRune(str, r) + } + case '"': + str = append(str, '"') + case '\\': + str = append(str, '\\') + case '/': + str = append(str, '/') + case 'b': + str = append(str, '\b') + case 'f': + str = append(str, '\f') + case 'n': + str = append(str, '\n') + case 'r': + str = append(str, '\r') + case 't': + str = append(str, '\t') + default: + iter.ReportError("readEscapedChar", + `invalid escape char after \`) + return nil + } + return str +} + +// ReadStringAsSlice read string from iterator without copying into string form. +// The []byte can not be kept, as it will change after next iterator call. +func (iter *Iterator) ReadStringAsSlice() (ret []byte) { + c := iter.nextToken() + if c == '"' { + for i := iter.head; i < iter.tail; i++ { + // require ascii string and no escape + // for: field name, base64, number + if iter.buf[i] == '"' { + // fast path: reuse the underlying buffer + ret = iter.buf[iter.head:i] + iter.head = i + 1 + return ret + } + } + readLen := iter.tail - iter.head + copied := make([]byte, readLen, readLen*2) + copy(copied, iter.buf[iter.head:iter.tail]) + iter.head = iter.tail + for iter.Error == nil { + c := iter.readByte() + if c == '"' { + return copied + } + copied = append(copied, c) + } + return copied + } + iter.ReportError("ReadStringAsSlice", `expects " or n, but found `+string([]byte{c})) + return +} + +func (iter *Iterator) readU4() (ret rune) { + for i := 0; i < 4; i++ { + c := iter.readByte() + if iter.Error != nil { + return + } + if c >= '0' && c <= '9' { + ret = ret*16 + rune(c-'0') + } else if c >= 'a' && c <= 'f' { + ret = ret*16 + rune(c-'a'+10) + } else if c >= 'A' && c <= 'F' { + ret = ret*16 + rune(c-'A'+10) + } else { + iter.ReportError("readU4", "expects 0~9 or a~f, but found "+string([]byte{c})) + return + } + } + return ret +} + +const ( + t1 = 0x00 // 0000 0000 + tx = 0x80 // 1000 0000 + t2 = 0xC0 // 1100 0000 + t3 = 0xE0 // 1110 0000 + t4 = 0xF0 // 1111 0000 + t5 = 0xF8 // 1111 1000 + + maskx = 0x3F // 0011 1111 + mask2 = 0x1F // 0001 1111 + mask3 = 0x0F // 0000 1111 + mask4 = 0x07 // 0000 0111 + + rune1Max = 1<<7 - 1 + rune2Max = 1<<11 - 1 + rune3Max = 1<<16 - 1 + + surrogateMin = 0xD800 + surrogateMax = 0xDFFF + + maxRune = '\U0010FFFF' // Maximum valid Unicode code point. + runeError = '\uFFFD' // the "error" Rune or "Unicode replacement character" +) + +func appendRune(p []byte, r rune) []byte { + // Negative values are erroneous. Making it unsigned addresses the problem. + switch i := uint32(r); { + case i <= rune1Max: + p = append(p, byte(r)) + return p + case i <= rune2Max: + p = append(p, t2|byte(r>>6)) + p = append(p, tx|byte(r)&maskx) + return p + case i > maxRune, surrogateMin <= i && i <= surrogateMax: + r = runeError + fallthrough + case i <= rune3Max: + p = append(p, t3|byte(r>>12)) + p = append(p, tx|byte(r>>6)&maskx) + p = append(p, tx|byte(r)&maskx) + return p + default: + p = append(p, t4|byte(r>>18)) + p = append(p, tx|byte(r>>12)&maskx) + p = append(p, tx|byte(r>>6)&maskx) + p = append(p, tx|byte(r)&maskx) + return p + } +} diff --git a/vendor/github.com/json-iterator/go/jsoniter.go b/vendor/github.com/json-iterator/go/jsoniter.go new file mode 100644 index 000000000..c2934f916 --- /dev/null +++ b/vendor/github.com/json-iterator/go/jsoniter.go @@ -0,0 +1,18 @@ +// Package jsoniter implements encoding and decoding of JSON as defined in +// RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json. +// Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter +// and variable type declarations (if any). +// jsoniter interfaces gives 100% compatibility with code using standard lib. +// +// "JSON and Go" +// (https://golang.org/doc/articles/json_and_go.html) +// gives a description of how Marshal/Unmarshal operate +// between arbitrary or predefined json objects and bytes, +// and it applies to jsoniter.Marshal/Unmarshal as well. +// +// Besides, jsoniter.Iterator provides a different set of interfaces +// iterating given bytes/string/reader +// and yielding parsed elements one by one. +// This set of interfaces reads input as required and gives +// better performance. +package jsoniter diff --git a/vendor/github.com/json-iterator/go/pool.go b/vendor/github.com/json-iterator/go/pool.go new file mode 100644 index 000000000..e2389b56c --- /dev/null +++ b/vendor/github.com/json-iterator/go/pool.go @@ -0,0 +1,42 @@ +package jsoniter + +import ( + "io" +) + +// IteratorPool a thread safe pool of iterators with same configuration +type IteratorPool interface { + BorrowIterator(data []byte) *Iterator + ReturnIterator(iter *Iterator) +} + +// StreamPool a thread safe pool of streams with same configuration +type StreamPool interface { + BorrowStream(writer io.Writer) *Stream + ReturnStream(stream *Stream) +} + +func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream { + stream := cfg.streamPool.Get().(*Stream) + stream.Reset(writer) + return stream +} + +func (cfg *frozenConfig) ReturnStream(stream *Stream) { + stream.out = nil + stream.Error = nil + stream.Attachment = nil + cfg.streamPool.Put(stream) +} + +func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator { + iter := cfg.iteratorPool.Get().(*Iterator) + iter.ResetBytes(data) + return iter +} + +func (cfg *frozenConfig) ReturnIterator(iter *Iterator) { + iter.Error = nil + iter.Attachment = nil + cfg.iteratorPool.Put(iter) +} diff --git a/vendor/github.com/json-iterator/go/reflect.go b/vendor/github.com/json-iterator/go/reflect.go new file mode 100644 index 000000000..39acb320a --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect.go @@ -0,0 +1,337 @@ +package jsoniter + +import ( + "fmt" + "reflect" + "unsafe" + + "github.com/modern-go/reflect2" +) + +// ValDecoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValDecoder with json.Decoder. +// For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). +// +// Reflection on type to create decoders, which is then cached +// Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions +// 1. create instance of new value, for example *int will need a int to be allocated +// 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New +// 3. assignment to map, both key and value will be reflect.Value +// For a simple struct binding, it will be reflect.Value free and allocation free +type ValDecoder interface { + Decode(ptr unsafe.Pointer, iter *Iterator) +} + +// ValEncoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValEncoder with json.Encoder. +// For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). +type ValEncoder interface { + IsEmpty(ptr unsafe.Pointer) bool + Encode(ptr unsafe.Pointer, stream *Stream) +} + +type checkIsEmpty interface { + IsEmpty(ptr unsafe.Pointer) bool +} + +type ctx struct { + *frozenConfig + prefix string + encoders map[reflect2.Type]ValEncoder + decoders map[reflect2.Type]ValDecoder +} + +func (b *ctx) caseSensitive() bool { + if b.frozenConfig == nil { + // default is case-insensitive + return false + } + return b.frozenConfig.caseSensitive +} + +func (b *ctx) append(prefix string) *ctx { + return &ctx{ + frozenConfig: b.frozenConfig, + prefix: b.prefix + " " + prefix, + encoders: b.encoders, + decoders: b.decoders, + } +} + +// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal +func (iter *Iterator) ReadVal(obj interface{}) { + depth := iter.depth + cacheKey := reflect2.RTypeOf(obj) + decoder := iter.cfg.getDecoderFromCache(cacheKey) + if decoder == nil { + typ := reflect2.TypeOf(obj) + if typ == nil || typ.Kind() != reflect.Ptr { + iter.ReportError("ReadVal", "can only unmarshal into pointer") + return + } + decoder = iter.cfg.DecoderOf(typ) + } + ptr := reflect2.PtrOf(obj) + if ptr == nil { + iter.ReportError("ReadVal", "can not read into nil pointer") + return + } + decoder.Decode(ptr, iter) + if iter.depth != depth { + iter.ReportError("ReadVal", "unexpected mismatched nesting") + return + } +} + +// WriteVal copy the go interface into underlying JSON, same as json.Marshal +func (stream *Stream) WriteVal(val interface{}) { + if nil == val { + stream.WriteNil() + return + } + cacheKey := reflect2.RTypeOf(val) + encoder := stream.cfg.getEncoderFromCache(cacheKey) + if encoder == nil { + typ := reflect2.TypeOf(val) + encoder = stream.cfg.EncoderOf(typ) + } + encoder.Encode(reflect2.PtrOf(val), stream) +} + +func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder { + cacheKey := typ.RType() + decoder := cfg.getDecoderFromCache(cacheKey) + if decoder != nil { + return decoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + ptrType := typ.(*reflect2.UnsafePtrType) + decoder = decoderOfType(ctx, ptrType.Elem()) + cfg.addDecoderToCache(cacheKey, decoder) + return decoder +} + +func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := getTypeDecoderFromExtension(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfType(ctx, typ) + for _, extension := range extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) + for _, extension := range ctx.extraExtensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + return decoder +} + +func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := ctx.decoders[typ] + if decoder != nil { + return decoder + } + placeholder := &placeholderDecoder{} + ctx.decoders[typ] = placeholder + decoder = _createDecoderOfType(ctx, typ) + placeholder.decoder = decoder + return decoder +} + +func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := createDecoderOfJsonRawMessage(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfJsonNumber(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfMarshaler(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfAny(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfNative(ctx, typ) + if decoder != nil { + return decoder + } + switch typ.Kind() { + case reflect.Interface: + ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType) + if isIFace { + return &ifaceDecoder{valType: ifaceType} + } + return &efaceDecoder{} + case reflect.Struct: + return decoderOfStruct(ctx, typ) + case reflect.Array: + return decoderOfArray(ctx, typ) + case reflect.Slice: + return decoderOfSlice(ctx, typ) + case reflect.Map: + return decoderOfMap(ctx, typ) + case reflect.Ptr: + return decoderOfOptional(ctx, typ) + default: + return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder { + cacheKey := typ.RType() + encoder := cfg.getEncoderFromCache(cacheKey) + if encoder != nil { + return encoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + encoder = encoderOfType(ctx, typ) + if typ.LikePtr() { + encoder = &onePtrEncoder{encoder} + } + cfg.addEncoderToCache(cacheKey, encoder) + return encoder +} + +type onePtrEncoder struct { + encoder ValEncoder +} + +func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := getTypeEncoderFromExtension(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfType(ctx, typ) + for _, extension := range extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) + for _, extension := range ctx.extraExtensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + return encoder +} + +func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := ctx.encoders[typ] + if encoder != nil { + return encoder + } + placeholder := &placeholderEncoder{} + ctx.encoders[typ] = placeholder + encoder = _createEncoderOfType(ctx, typ) + placeholder.encoder = encoder + return encoder +} +func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := createEncoderOfJsonRawMessage(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfJsonNumber(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfMarshaler(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfAny(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return encoderOfStruct(ctx, typ) + case reflect.Array: + return encoderOfArray(ctx, typ) + case reflect.Slice: + return encoderOfSlice(ctx, typ) + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return encoderOfOptional(ctx, typ) + default: + return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +type lazyErrorDecoder struct { + err error +} + +func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.WhatIsNext() != NilValue { + if iter.Error == nil { + iter.Error = decoder.err + } + } else { + iter.Skip() + } +} + +type lazyErrorEncoder struct { + err error +} + +func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if ptr == nil { + stream.WriteNil() + } else if stream.Error == nil { + stream.Error = encoder.err + } +} + +func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type placeholderDecoder struct { + decoder ValDecoder +} + +func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(ptr, iter) +} + +type placeholderEncoder struct { + encoder ValEncoder +} + +func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(ptr, stream) +} + +func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go new file mode 100644 index 000000000..13a0b7b08 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_array.go @@ -0,0 +1,104 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + decoder := decoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayDecoder{arrayType, decoder} +} + +func encoderOfArray(ctx *ctx, typ reflect2.Type) ValEncoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + if arrayType.Len() == 0 { + return emptyArrayEncoder{} + } + encoder := encoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayEncoder{arrayType, encoder} +} + +type emptyArrayEncoder struct{} + +func (encoder emptyArrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteEmptyArray() +} + +func (encoder emptyArrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return true +} + +type arrayEncoder struct { + arrayType *reflect2.UnsafeArrayType + elemEncoder ValEncoder +} + +func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteArrayStart() + elemPtr := unsafe.Pointer(ptr) + encoder.elemEncoder.Encode(elemPtr, stream) + for i := 1; i < encoder.arrayType.Len(); i++ { + stream.WriteMore() + elemPtr = encoder.arrayType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.arrayType, stream.Error.Error()) + } +} + +func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type arrayDecoder struct { + arrayType *reflect2.UnsafeArrayType + elemDecoder ValDecoder +} + +func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.arrayType, iter.Error.Error()) + } +} + +func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + arrayType := decoder.arrayType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return + } + if c != '[' { + iter.ReportError("decode array", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + return + } + iter.unreadByte() + elemPtr := arrayType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + if length >= arrayType.Len() { + iter.Skip() + continue + } + idx := length + length += 1 + elemPtr = arrayType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode array", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go new file mode 100644 index 000000000..8b6bc8b43 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_dynamic.go @@ -0,0 +1,70 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "reflect" + "unsafe" +) + +type dynamicEncoder struct { + valType reflect2.Type +} + +func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + stream.WriteVal(obj) +} + +func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.valType.UnsafeIndirect(ptr) == nil +} + +type efaceDecoder struct { +} + +func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + pObj := (*interface{})(ptr) + obj := *pObj + if obj == nil { + *pObj = iter.Read() + return + } + typ := reflect2.TypeOf(obj) + if typ.Kind() != reflect.Ptr { + *pObj = iter.Read() + return + } + ptrType := typ.(*reflect2.UnsafePtrType) + ptrElemType := ptrType.Elem() + if iter.WhatIsNext() == NilValue { + if ptrElemType.Kind() != reflect.Ptr { + iter.skipFourBytes('n', 'u', 'l', 'l') + *pObj = nil + return + } + } + if reflect2.IsNil(obj) { + obj := ptrElemType.New() + iter.ReadVal(obj) + *pObj = obj + return + } + iter.ReadVal(obj) +} + +type ifaceDecoder struct { + valType *reflect2.UnsafeIFaceType +} + +func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + decoder.valType.UnsafeSet(ptr, decoder.valType.UnsafeNew()) + return + } + obj := decoder.valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + iter.ReportError("decode non empty interface", "can not unmarshal into nil") + return + } + iter.ReadVal(obj) +} diff --git a/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go new file mode 100644 index 000000000..74a97bfe5 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_extension.go @@ -0,0 +1,483 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "reflect" + "sort" + "strings" + "unicode" + "unsafe" +) + +var typeDecoders = map[string]ValDecoder{} +var fieldDecoders = map[string]ValDecoder{} +var typeEncoders = map[string]ValEncoder{} +var fieldEncoders = map[string]ValEncoder{} +var extensions = []Extension{} + +// StructDescriptor describe how should we encode/decode the struct +type StructDescriptor struct { + Type reflect2.Type + Fields []*Binding +} + +// GetField get one field from the descriptor by its name. +// Can not use map here to keep field orders. +func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { + for _, binding := range structDescriptor.Fields { + if binding.Field.Name() == fieldName { + return binding + } + } + return nil +} + +// Binding describe how should we encode/decode the struct field +type Binding struct { + levels []int + Field reflect2.StructField + FromNames []string + ToNames []string + Encoder ValEncoder + Decoder ValDecoder +} + +// Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder. +// Can also rename fields by UpdateStructDescriptor. +type Extension interface { + UpdateStructDescriptor(structDescriptor *StructDescriptor) + CreateMapKeyDecoder(typ reflect2.Type) ValDecoder + CreateMapKeyEncoder(typ reflect2.Type) ValEncoder + CreateDecoder(typ reflect2.Type) ValDecoder + CreateEncoder(typ reflect2.Type) ValEncoder + DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder + DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder +} + +// DummyExtension embed this type get dummy implementation for all methods of Extension +type DummyExtension struct { +} + +// UpdateStructDescriptor No-op +func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateMapKeyDecoder No-op +func (extension *DummyExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension *DummyExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// CreateDecoder No-op +func (extension *DummyExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder No-op +func (extension *DummyExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension *DummyExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension *DummyExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type EncoderExtension map[reflect2.Type]ValEncoder + +// UpdateStructDescriptor No-op +func (extension EncoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateDecoder No-op +func (extension EncoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder get encoder from map +func (extension EncoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return extension[typ] +} + +// CreateMapKeyDecoder No-op +func (extension EncoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension EncoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension EncoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension EncoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type DecoderExtension map[reflect2.Type]ValDecoder + +// UpdateStructDescriptor No-op +func (extension DecoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateMapKeyDecoder No-op +func (extension DecoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension DecoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// CreateDecoder get decoder from map +func (extension DecoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return extension[typ] +} + +// CreateEncoder No-op +func (extension DecoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension DecoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension DecoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type funcDecoder struct { + fun DecoderFunc +} + +func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.fun(ptr, iter) +} + +type funcEncoder struct { + fun EncoderFunc + isEmptyFunc func(ptr unsafe.Pointer) bool +} + +func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.fun(ptr, stream) +} + +func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool { + if encoder.isEmptyFunc == nil { + return false + } + return encoder.isEmptyFunc(ptr) +} + +// DecoderFunc the function form of TypeDecoder +type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator) + +// EncoderFunc the function form of TypeEncoder +type EncoderFunc func(ptr unsafe.Pointer, stream *Stream) + +// RegisterTypeDecoderFunc register TypeDecoder for a type with function +func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) { + typeDecoders[typ] = &funcDecoder{fun} +} + +// RegisterTypeDecoder register TypeDecoder for a typ +func RegisterTypeDecoder(typ string, decoder ValDecoder) { + typeDecoders[typ] = decoder +} + +// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function +func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) { + RegisterFieldDecoder(typ, field, &funcDecoder{fun}) +} + +// RegisterFieldDecoder register TypeDecoder for a struct field +func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) { + fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder +} + +// RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function +func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { + typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc} +} + +// RegisterTypeEncoder register TypeEncoder for a type +func RegisterTypeEncoder(typ string, encoder ValEncoder) { + typeEncoders[typ] = encoder +} + +// RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function +func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { + RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc}) +} + +// RegisterFieldEncoder register TypeEncoder for a struct field +func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) { + fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder +} + +// RegisterExtension register extension +func RegisterExtension(extension Extension) { + extensions = append(extensions, extension) +} + +func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := _getTypeDecoderFromExtension(ctx, typ) + if decoder != nil { + for _, extension := range extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) + for _, extension := range ctx.extraExtensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + } + return decoder +} +func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { + for _, extension := range extensions { + decoder := extension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + } + decoder := ctx.decoderExtension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + for _, extension := range ctx.extraExtensions { + decoder := extension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + } + typeName := typ.String() + decoder = typeDecoders[typeName] + if decoder != nil { + return decoder + } + if typ.Kind() == reflect.Ptr { + ptrType := typ.(*reflect2.UnsafePtrType) + decoder := typeDecoders[ptrType.Elem().String()] + if decoder != nil { + return &OptionalDecoder{ptrType.Elem(), decoder} + } + } + return nil +} + +func getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := _getTypeEncoderFromExtension(ctx, typ) + if encoder != nil { + for _, extension := range extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) + for _, extension := range ctx.extraExtensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + } + return encoder +} + +func _getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { + for _, extension := range extensions { + encoder := extension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + } + encoder := ctx.encoderExtension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + for _, extension := range ctx.extraExtensions { + encoder := extension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + } + typeName := typ.String() + encoder = typeEncoders[typeName] + if encoder != nil { + return encoder + } + if typ.Kind() == reflect.Ptr { + typePtr := typ.(*reflect2.UnsafePtrType) + encoder := typeEncoders[typePtr.Elem().String()] + if encoder != nil { + return &OptionalEncoder{encoder} + } + } + return nil +} + +func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor { + structType := typ.(*reflect2.UnsafeStructType) + embeddedBindings := []*Binding{} + bindings := []*Binding{} + for i := 0; i < structType.NumField(); i++ { + field := structType.Field(i) + tag, hastag := field.Tag().Lookup(ctx.getTagKey()) + if ctx.onlyTaggedField && !hastag && !field.Anonymous() { + continue + } + if tag == "-" || field.Name() == "_" { + continue + } + tagParts := strings.Split(tag, ",") + if field.Anonymous() && (tag == "" || tagParts[0] == "") { + if field.Type().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, field.Type()) + for _, binding := range structDescriptor.Fields { + binding.levels = append([]int{i}, binding.levels...) + omitempty := binding.Encoder.(*structFieldEncoder).omitempty + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} + embeddedBindings = append(embeddedBindings, binding) + } + continue + } else if field.Type().Kind() == reflect.Ptr { + ptrType := field.Type().(*reflect2.UnsafePtrType) + if ptrType.Elem().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, ptrType.Elem()) + for _, binding := range structDescriptor.Fields { + binding.levels = append([]int{i}, binding.levels...) + omitempty := binding.Encoder.(*structFieldEncoder).omitempty + binding.Encoder = &dereferenceEncoder{binding.Encoder} + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &dereferenceDecoder{ptrType.Elem(), binding.Decoder} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} + embeddedBindings = append(embeddedBindings, binding) + } + continue + } + } + } + fieldNames := calcFieldNames(field.Name(), tagParts[0], tag) + fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name()) + decoder := fieldDecoders[fieldCacheKey] + if decoder == nil { + decoder = decoderOfType(ctx.append(field.Name()), field.Type()) + } + encoder := fieldEncoders[fieldCacheKey] + if encoder == nil { + encoder = encoderOfType(ctx.append(field.Name()), field.Type()) + } + binding := &Binding{ + Field: field, + FromNames: fieldNames, + ToNames: fieldNames, + Decoder: decoder, + Encoder: encoder, + } + binding.levels = []int{i} + bindings = append(bindings, binding) + } + return createStructDescriptor(ctx, typ, bindings, embeddedBindings) +} +func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { + structDescriptor := &StructDescriptor{ + Type: typ, + Fields: bindings, + } + for _, extension := range extensions { + extension.UpdateStructDescriptor(structDescriptor) + } + ctx.encoderExtension.UpdateStructDescriptor(structDescriptor) + ctx.decoderExtension.UpdateStructDescriptor(structDescriptor) + for _, extension := range ctx.extraExtensions { + extension.UpdateStructDescriptor(structDescriptor) + } + processTags(structDescriptor, ctx.frozenConfig) + // merge normal & embedded bindings & sort with original order + allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...)) + sort.Sort(allBindings) + structDescriptor.Fields = allBindings + return structDescriptor +} + +type sortableBindings []*Binding + +func (bindings sortableBindings) Len() int { + return len(bindings) +} + +func (bindings sortableBindings) Less(i, j int) bool { + left := bindings[i].levels + right := bindings[j].levels + k := 0 + for { + if left[k] < right[k] { + return true + } else if left[k] > right[k] { + return false + } + k++ + } +} + +func (bindings sortableBindings) Swap(i, j int) { + bindings[i], bindings[j] = bindings[j], bindings[i] +} + +func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) { + for _, binding := range structDescriptor.Fields { + shouldOmitEmpty := false + tagParts := strings.Split(binding.Field.Tag().Get(cfg.getTagKey()), ",") + for _, tagPart := range tagParts[1:] { + if tagPart == "omitempty" { + shouldOmitEmpty = true + } else if tagPart == "string" { + if binding.Field.Type().Kind() == reflect.String { + binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg} + binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg} + } else { + binding.Decoder = &stringModeNumberDecoder{binding.Decoder} + binding.Encoder = &stringModeNumberEncoder{binding.Encoder} + } + } + } + binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder} + binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty} + } +} + +func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string { + // ignore? + if wholeTag == "-" { + return []string{} + } + // rename? + var fieldNames []string + if tagProvidedFieldName == "" { + fieldNames = []string{originalFieldName} + } else { + fieldNames = []string{tagProvidedFieldName} + } + // private? + isNotExported := unicode.IsLower(rune(originalFieldName[0])) || originalFieldName[0] == '_' + if isNotExported { + fieldNames = []string{} + } + return fieldNames +} diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go new file mode 100644 index 000000000..98d45c1ec --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_number.go @@ -0,0 +1,112 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "strconv" + "unsafe" +) + +type Number string + +// String returns the literal text of the number. +func (n Number) String() string { return string(n) } + +// Float64 returns the number as a float64. +func (n Number) Float64() (float64, error) { + return strconv.ParseFloat(string(n), 64) +} + +// Int64 returns the number as an int64. +func (n Number) Int64() (int64, error) { + return strconv.ParseInt(string(n), 10, 64) +} + +func CastJsonNumber(val interface{}) (string, bool) { + switch typedVal := val.(type) { + case json.Number: + return string(typedVal), true + case Number: + return string(typedVal), true + } + return "", false +} + +var jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() +var jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() + +func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +type jsonNumberCodec struct { +} + +func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*json.Number)(ptr)) = json.Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*json.Number)(ptr)) = "" + default: + *((*json.Number)(ptr)) = json.Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*json.Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.Number)(ptr))) == 0 +} + +type jsoniterNumberCodec struct { +} + +func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*Number)(ptr)) = Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*Number)(ptr)) = "" + default: + *((*Number)(ptr)) = Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*Number)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go new file mode 100644 index 000000000..eba434f2f --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go @@ -0,0 +1,76 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "unsafe" +) + +var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() +var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() + +func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +type jsonRawMessageCodec struct { +} + +func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*json.RawMessage)(ptr)) = nil + } else { + *((*json.RawMessage)(ptr)) = iter.SkipAndReturnBytes() + } +} + +func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*json.RawMessage)(ptr)) == nil { + stream.WriteNil() + } else { + stream.WriteRaw(string(*((*json.RawMessage)(ptr)))) + } +} + +func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.RawMessage)(ptr))) == 0 +} + +type jsoniterRawMessageCodec struct { +} + +func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*RawMessage)(ptr)) = nil + } else { + *((*RawMessage)(ptr)) = iter.SkipAndReturnBytes() + } +} + +func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*RawMessage)(ptr)) == nil { + stream.WriteNil() + } else { + stream.WriteRaw(string(*((*RawMessage)(ptr)))) + } +} + +func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*RawMessage)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go new file mode 100644 index 000000000..582967130 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_map.go @@ -0,0 +1,346 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "sort" + "unsafe" +) + +func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { + mapType := typ.(*reflect2.UnsafeMapType) + keyDecoder := decoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()) + elemDecoder := decoderOfType(ctx.append("[mapElem]"), mapType.Elem()) + return &mapDecoder{ + mapType: mapType, + keyType: mapType.Key(), + elemType: mapType.Elem(), + keyDecoder: keyDecoder, + elemDecoder: elemDecoder, + } +} + +func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder { + mapType := typ.(*reflect2.UnsafeMapType) + if ctx.sortMapKeys { + return &sortKeysMapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } + } + return &mapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } +} + +func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := ctx.decoderExtension.CreateMapKeyDecoder(typ) + if decoder != nil { + return decoder + } + for _, extension := range ctx.extraExtensions { + decoder := extension.CreateMapKeyDecoder(typ) + if decoder != nil { + return decoder + } + } + + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(unmarshalerType) { + return &referenceDecoder{ + &unmarshalerDecoder{ + valType: ptrType, + }, + } + } + if typ.Implements(unmarshalerType) { + return &unmarshalerDecoder{ + valType: typ, + } + } + if ptrType.Implements(textUnmarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ + valType: ptrType, + }, + } + } + if typ.Implements(textUnmarshalerType) { + return &textUnmarshalerDecoder{ + valType: typ, + } + } + + switch typ.Kind() { + case reflect.String: + return decoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyDecoder{decoderOfType(ctx, typ)} + default: + return &lazyErrorDecoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := ctx.encoderExtension.CreateMapKeyEncoder(typ) + if encoder != nil { + return encoder + } + for _, extension := range ctx.extraExtensions { + encoder := extension.CreateMapKeyEncoder(typ) + if encoder != nil { + return encoder + } + } + + if typ == textMarshalerType { + return &directTextMarshalerEncoder{ + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + if typ.Implements(textMarshalerType) { + return &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + + switch typ.Kind() { + case reflect.String: + return encoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyEncoder{encoderOfType(ctx, typ)} + default: + if typ.Kind() == reflect.Interface { + return &dynamicMapKeyEncoder{ctx, typ} + } + return &lazyErrorEncoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +type mapDecoder struct { + mapType *reflect2.UnsafeMapType + keyType reflect2.Type + elemType reflect2.Type + keyDecoder ValDecoder + elemDecoder ValDecoder +} + +func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + mapType := decoder.mapType + c := iter.nextToken() + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + *(*unsafe.Pointer)(ptr) = nil + mapType.UnsafeSet(ptr, mapType.UnsafeNew()) + return + } + if mapType.UnsafeIsNil(ptr) { + mapType.UnsafeSet(ptr, mapType.UnsafeMakeMap(0)) + } + if c != '{' { + iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) + return + } + c = iter.nextToken() + if c == '}' { + return + } + iter.unreadByte() + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + } + if c != '}' { + iter.ReportError("ReadMapCB", `expect }, but found `+string([]byte{c})) + } +} + +type numericMapKeyDecoder struct { + decoder ValDecoder +} + +func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } + decoder.decoder.Decode(ptr, iter) + c = iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } +} + +type numericMapKeyEncoder struct { + encoder ValEncoder +} + +func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.encoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type dynamicMapKeyEncoder struct { + ctx *ctx + valType reflect2.Type +} + +func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).Encode(reflect2.PtrOf(obj), stream) +} + +func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + obj := encoder.valType.UnsafeIndirect(ptr) + return encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).IsEmpty(reflect2.PtrOf(obj)) +} + +type mapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *(*unsafe.Pointer)(ptr) == nil { + stream.WriteNil() + return + } + stream.WriteObjectStart() + iter := encoder.mapType.UnsafeIterate(ptr) + for i := 0; iter.HasNext(); i++ { + if i != 0 { + stream.WriteMore() + } + key, elem := iter.UnsafeNext() + encoder.keyEncoder.Encode(key, stream) + if stream.indention > 0 { + stream.writeTwoBytes(byte(':'), byte(' ')) + } else { + stream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, stream) + } + stream.WriteObjectEnd() +} + +func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type sortKeysMapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *(*unsafe.Pointer)(ptr) == nil { + stream.WriteNil() + return + } + stream.WriteObjectStart() + mapIter := encoder.mapType.UnsafeIterate(ptr) + subStream := stream.cfg.BorrowStream(nil) + subStream.Attachment = stream.Attachment + subIter := stream.cfg.BorrowIterator(nil) + keyValues := encodedKeyValues{} + for mapIter.HasNext() { + key, elem := mapIter.UnsafeNext() + subStreamIndex := subStream.Buffered() + encoder.keyEncoder.Encode(key, subStream) + if subStream.Error != nil && subStream.Error != io.EOF && stream.Error == nil { + stream.Error = subStream.Error + } + encodedKey := subStream.Buffer()[subStreamIndex:] + subIter.ResetBytes(encodedKey) + decodedKey := subIter.ReadString() + if stream.indention > 0 { + subStream.writeTwoBytes(byte(':'), byte(' ')) + } else { + subStream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, subStream) + keyValues = append(keyValues, encodedKV{ + key: decodedKey, + keyValue: subStream.Buffer()[subStreamIndex:], + }) + } + sort.Sort(keyValues) + for i, keyValue := range keyValues { + if i != 0 { + stream.WriteMore() + } + stream.Write(keyValue.keyValue) + } + if subStream.Error != nil && stream.Error == nil { + stream.Error = subStream.Error + } + stream.WriteObjectEnd() + stream.cfg.ReturnStream(subStream) + stream.cfg.ReturnIterator(subIter) +} + +func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type encodedKeyValues []encodedKV + +type encodedKV struct { + key string + keyValue []byte +} + +func (sv encodedKeyValues) Len() int { return len(sv) } +func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } +func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv[j].key } diff --git a/vendor/github.com/json-iterator/go/reflect_marshaler.go b/vendor/github.com/json-iterator/go/reflect_marshaler.go new file mode 100644 index 000000000..3e21f3756 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_marshaler.go @@ -0,0 +1,225 @@ +package jsoniter + +import ( + "encoding" + "encoding/json" + "unsafe" + + "github.com/modern-go/reflect2" +) + +var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() +var unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() +var textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() +var textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() + +func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(unmarshalerType) { + return &referenceDecoder{ + &unmarshalerDecoder{ptrType}, + } + } + if ptrType.Implements(textUnmarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ptrType}, + } + } + return nil +} + +func createEncoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == marshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + } + return encoder + } + if typ.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &marshalerEncoder{ + valType: typ, + checkIsEmpty: checkIsEmpty, + } + return encoder + } + ptrType := reflect2.PtrTo(typ) + if ctx.prefix != "" && ptrType.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &marshalerEncoder{ + valType: ptrType, + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + if typ == textMarshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directTextMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + return encoder + } + if typ.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return encoder + } + // if prefix is empty, the type is the root type + if ctx.prefix != "" && ptrType.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: ptrType, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + return nil +} + +type marshalerEncoder struct { + checkIsEmpty checkIsEmpty + valType reflect2.Type +} + +func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := obj.(json.Marshaler) + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + // html escape was already done by jsoniter + // but the extra '\n' should be trimed + l := len(bytes) + if l > 0 && bytes[l-1] == '\n' { + bytes = bytes[:l-1] + } + stream.Write(bytes) + } +} + +func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directMarshalerEncoder struct { + checkIsEmpty checkIsEmpty +} + +func (encoder *directMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*json.Marshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + stream.Write(bytes) + } +} + +func (encoder *directMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type textMarshalerEncoder struct { + valType reflect2.Type + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := (obj).(encoding.TextMarshaler) + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directTextMarshalerEncoder struct { + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *directTextMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*encoding.TextMarshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *directTextMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type unmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + unmarshaler := obj.(json.Unmarshaler) + iter.nextToken() + iter.unreadByte() // skip spaces + bytes := iter.SkipAndReturnBytes() + err := unmarshaler.UnmarshalJSON(bytes) + if err != nil { + iter.ReportError("unmarshalerDecoder", err.Error()) + } +} + +type textUnmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + ptrType := valType.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elem := elemType.UnsafeNew() + ptrType.UnsafeSet(ptr, unsafe.Pointer(&elem)) + obj = valType.UnsafeIndirect(ptr) + } + unmarshaler := (obj).(encoding.TextUnmarshaler) + str := iter.ReadString() + err := unmarshaler.UnmarshalText([]byte(str)) + if err != nil { + iter.ReportError("textUnmarshalerDecoder", err.Error()) + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_native.go b/vendor/github.com/json-iterator/go/reflect_native.go new file mode 100644 index 000000000..f88722d14 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_native.go @@ -0,0 +1,453 @@ +package jsoniter + +import ( + "encoding/base64" + "reflect" + "strconv" + "unsafe" + + "github.com/modern-go/reflect2" +) + +const ptrSize = 32 << uintptr(^uintptr(0)>>63) + +func createEncoderOfNative(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + kind := typ.Kind() + switch kind { + case reflect.String: + if typeName != "string" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + switch typ.Kind() { + case reflect.String: + if typeName != "string" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +type stringCodec struct { +} + +func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*string)(ptr)) = iter.ReadString() +} + +func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + str := *((*string)(ptr)) + stream.WriteString(str) +} + +func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*string)(ptr)) == "" +} + +type int8Codec struct { +} + +func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int8)(ptr)) = iter.ReadInt8() + } +} + +func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt8(*((*int8)(ptr))) +} + +func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int8)(ptr)) == 0 +} + +type int16Codec struct { +} + +func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int16)(ptr)) = iter.ReadInt16() + } +} + +func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt16(*((*int16)(ptr))) +} + +func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int16)(ptr)) == 0 +} + +type int32Codec struct { +} + +func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int32)(ptr)) = iter.ReadInt32() + } +} + +func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt32(*((*int32)(ptr))) +} + +func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int32)(ptr)) == 0 +} + +type int64Codec struct { +} + +func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int64)(ptr)) = iter.ReadInt64() + } +} + +func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt64(*((*int64)(ptr))) +} + +func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int64)(ptr)) == 0 +} + +type uint8Codec struct { +} + +func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint8)(ptr)) = iter.ReadUint8() + } +} + +func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint8(*((*uint8)(ptr))) +} + +func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint8)(ptr)) == 0 +} + +type uint16Codec struct { +} + +func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint16)(ptr)) = iter.ReadUint16() + } +} + +func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint16(*((*uint16)(ptr))) +} + +func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint16)(ptr)) == 0 +} + +type uint32Codec struct { +} + +func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint32)(ptr)) = iter.ReadUint32() + } +} + +func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint32(*((*uint32)(ptr))) +} + +func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint32)(ptr)) == 0 +} + +type uint64Codec struct { +} + +func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint64)(ptr)) = iter.ReadUint64() + } +} + +func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint64(*((*uint64)(ptr))) +} + +func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint64)(ptr)) == 0 +} + +type float32Codec struct { +} + +func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float32)(ptr)) = iter.ReadFloat32() + } +} + +func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat32(*((*float32)(ptr))) +} + +func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float32)(ptr)) == 0 +} + +type float64Codec struct { +} + +func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float64)(ptr)) = iter.ReadFloat64() + } +} + +func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat64(*((*float64)(ptr))) +} + +func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float64)(ptr)) == 0 +} + +type boolCodec struct { +} + +func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*bool)(ptr)) = iter.ReadBool() + } +} + +func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteBool(*((*bool)(ptr))) +} + +func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool { + return !(*((*bool)(ptr))) +} + +type base64Codec struct { + sliceType *reflect2.UnsafeSliceType + sliceDecoder ValDecoder +} + +func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + codec.sliceType.UnsafeSetNil(ptr) + return + } + switch iter.WhatIsNext() { + case StringValue: + src := iter.ReadString() + dst, err := base64.StdEncoding.DecodeString(src) + if err != nil { + iter.ReportError("decode base64", err.Error()) + } else { + codec.sliceType.UnsafeSet(ptr, unsafe.Pointer(&dst)) + } + case ArrayValue: + codec.sliceDecoder.Decode(ptr, iter) + default: + iter.ReportError("base64Codec", "invalid input") + } +} + +func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + if codec.sliceType.UnsafeIsNil(ptr) { + stream.WriteNil() + return + } + src := *((*[]byte)(ptr)) + encoding := base64.StdEncoding + stream.writeByte('"') + if len(src) != 0 { + size := encoding.EncodedLen(len(src)) + buf := make([]byte, size) + encoding.Encode(buf, src) + stream.buf = append(stream.buf, buf...) + } + stream.writeByte('"') +} + +func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*[]byte)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go new file mode 100644 index 000000000..fa71f4748 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_optional.go @@ -0,0 +1,129 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "unsafe" +) + +func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + decoder := decoderOfType(ctx, elemType) + return &OptionalDecoder{elemType, decoder} +} + +func encoderOfOptional(ctx *ctx, typ reflect2.Type) ValEncoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elemEncoder := encoderOfType(ctx, elemType) + encoder := &OptionalEncoder{elemEncoder} + return encoder +} + +type OptionalDecoder struct { + ValueType reflect2.Type + ValueDecoder ValDecoder +} + +func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*unsafe.Pointer)(ptr)) = nil + } else { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.ValueType.UnsafeNew() + decoder.ValueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.ValueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } + } +} + +type dereferenceDecoder struct { + // only to deference a pointer + valueType reflect2.Type + valueDecoder ValDecoder +} + +func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.valueType.UnsafeNew() + decoder.valueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } +} + +type OptionalEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *OptionalEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *OptionalEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*unsafe.Pointer)(ptr)) == nil +} + +type dereferenceEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *dereferenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *dereferenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + dePtr := *((*unsafe.Pointer)(ptr)) + if dePtr == nil { + return true + } + return encoder.ValueEncoder.IsEmpty(dePtr) +} + +func (encoder *dereferenceEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + deReferenced := *((*unsafe.Pointer)(ptr)) + if deReferenced == nil { + return true + } + isEmbeddedPtrNil, converted := encoder.ValueEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := unsafe.Pointer(deReferenced) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type referenceEncoder struct { + encoder ValEncoder +} + +func (encoder *referenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func (encoder *referenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +type referenceDecoder struct { + decoder ValDecoder +} + +func (decoder *referenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(unsafe.Pointer(&ptr), iter) +} diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go new file mode 100644 index 000000000..9441d79df --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_slice.go @@ -0,0 +1,99 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + decoder := decoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceDecoder{sliceType, decoder} +} + +func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + encoder := encoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceEncoder{sliceType, encoder} +} + +type sliceEncoder struct { + sliceType *reflect2.UnsafeSliceType + elemEncoder ValEncoder +} + +func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if encoder.sliceType.UnsafeIsNil(ptr) { + stream.WriteNil() + return + } + length := encoder.sliceType.UnsafeLengthOf(ptr) + if length == 0 { + stream.WriteEmptyArray() + return + } + stream.WriteArrayStart() + encoder.elemEncoder.Encode(encoder.sliceType.UnsafeGetIndex(ptr, 0), stream) + for i := 1; i < length; i++ { + stream.WriteMore() + elemPtr := encoder.sliceType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.sliceType, stream.Error.Error()) + } +} + +func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.sliceType.UnsafeLengthOf(ptr) == 0 +} + +type sliceDecoder struct { + sliceType *reflect2.UnsafeSliceType + elemDecoder ValDecoder +} + +func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.sliceType, iter.Error.Error()) + } +} + +func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + sliceType := decoder.sliceType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + sliceType.UnsafeSetNil(ptr) + return + } + if c != '[' { + iter.ReportError("decode slice", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + sliceType.UnsafeSet(ptr, sliceType.UnsafeMakeSlice(0, 0)) + return + } + iter.unreadByte() + sliceType.UnsafeGrow(ptr, 1) + elemPtr := sliceType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + idx := length + length += 1 + sliceType.UnsafeGrow(ptr, length) + elemPtr = sliceType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode slice", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_decoder.go b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go new file mode 100644 index 000000000..92ae912dc --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go @@ -0,0 +1,1097 @@ +package jsoniter + +import ( + "fmt" + "io" + "strings" + "unsafe" + + "github.com/modern-go/reflect2" +) + +func decoderOfStruct(ctx *ctx, typ reflect2.Type) ValDecoder { + bindings := map[string]*Binding{} + structDescriptor := describeStruct(ctx, typ) + for _, binding := range structDescriptor.Fields { + for _, fromName := range binding.FromNames { + old := bindings[fromName] + if old == nil { + bindings[fromName] = binding + continue + } + ignoreOld, ignoreNew := resolveConflictBinding(ctx.frozenConfig, old, binding) + if ignoreOld { + delete(bindings, fromName) + } + if !ignoreNew { + bindings[fromName] = binding + } + } + } + fields := map[string]*structFieldDecoder{} + for k, binding := range bindings { + fields[k] = binding.Decoder.(*structFieldDecoder) + } + + if !ctx.caseSensitive() { + for k, binding := range bindings { + if _, found := fields[strings.ToLower(k)]; !found { + fields[strings.ToLower(k)] = binding.Decoder.(*structFieldDecoder) + } + } + } + + return createStructDecoder(ctx, typ, fields) +} + +func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structFieldDecoder) ValDecoder { + if ctx.disallowUnknownFields { + return &generalStructDecoder{typ: typ, fields: fields, disallowUnknownFields: true} + } + knownHash := map[int64]struct{}{ + 0: {}, + } + + switch len(fields) { + case 0: + return &skipObjectDecoder{typ} + case 1: + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder} + } + case 2: + var fieldHash1 int64 + var fieldHash2 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldHash1 == 0 { + fieldHash1 = fieldHash + fieldDecoder1 = fieldDecoder + } else { + fieldHash2 = fieldHash + fieldDecoder2 = fieldDecoder + } + } + return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2} + case 3: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } + } + return &threeFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3} + case 4: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } + } + return &fourFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4} + case 5: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } + } + return &fiveFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5} + case 6: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } + } + return &sixFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6} + case 7: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } + } + return &sevenFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7} + case 8: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } + } + return &eightFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8} + case 9: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + var fieldDecoder9 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else if fieldName8 == 0 { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } else { + fieldName9 = fieldHash + fieldDecoder9 = fieldDecoder + } + } + return &nineFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9} + case 10: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 + var fieldName10 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + var fieldDecoder9 *structFieldDecoder + var fieldDecoder10 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else if fieldName8 == 0 { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } else if fieldName9 == 0 { + fieldName9 = fieldHash + fieldDecoder9 = fieldDecoder + } else { + fieldName10 = fieldHash + fieldDecoder10 = fieldDecoder + } + } + return &tenFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9, + fieldName10, fieldDecoder10} + } + return &generalStructDecoder{typ, fields, false} +} + +type generalStructDecoder struct { + typ reflect2.Type + fields map[string]*structFieldDecoder + disallowUnknownFields bool +} + +func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + var c byte + for c = ','; c == ','; c = iter.nextToken() { + decoder.decodeOneField(ptr, iter) + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + if c != '}' { + iter.ReportError("struct Decode", `expect }, but found `+string([]byte{c})) + } + iter.decrementDepth() +} + +func (decoder *generalStructDecoder) decodeOneField(ptr unsafe.Pointer, iter *Iterator) { + var field string + var fieldDecoder *structFieldDecoder + if iter.cfg.objectFieldMustBeSimpleString { + fieldBytes := iter.ReadStringAsSlice() + field = *(*string)(unsafe.Pointer(&fieldBytes)) + fieldDecoder = decoder.fields[field] + if fieldDecoder == nil && !iter.cfg.caseSensitive { + fieldDecoder = decoder.fields[strings.ToLower(field)] + } + } else { + field = iter.ReadString() + fieldDecoder = decoder.fields[field] + if fieldDecoder == nil && !iter.cfg.caseSensitive { + fieldDecoder = decoder.fields[strings.ToLower(field)] + } + } + if fieldDecoder == nil { + if decoder.disallowUnknownFields { + msg := "found unknown field: " + field + iter.ReportError("ReadObject", msg) + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + iter.Skip() + return + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + fieldDecoder.Decode(ptr, iter) +} + +type skipObjectDecoder struct { + typ reflect2.Type +} + +func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valueType := iter.WhatIsNext() + if valueType != ObjectValue && valueType != NilValue { + iter.ReportError("skipObjectDecoder", "expect object or null") + return + } + iter.Skip() +} + +type oneFieldStructDecoder struct { + typ reflect2.Type + fieldHash int64 + fieldDecoder *structFieldDecoder +} + +func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + if iter.readFieldHash() == decoder.fieldHash { + decoder.fieldDecoder.Decode(ptr, iter) + } else { + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type twoFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder +} + +func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type threeFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder +} + +func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type fourFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder +} + +func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type fiveFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder +} + +func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type sixFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder +} + +func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type sevenFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder +} + +func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type eightFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder +} + +func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type nineFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder + fieldHash9 int64 + fieldDecoder9 *structFieldDecoder +} + +func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + case decoder.fieldHash9: + decoder.fieldDecoder9.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type tenFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder + fieldHash9 int64 + fieldDecoder9 *structFieldDecoder + fieldHash10 int64 + fieldDecoder10 *structFieldDecoder +} + +func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + case decoder.fieldHash9: + decoder.fieldDecoder9.Decode(ptr, iter) + case decoder.fieldHash10: + decoder.fieldDecoder10.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type structFieldDecoder struct { + field reflect2.StructField + fieldDecoder ValDecoder +} + +func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + fieldPtr := decoder.field.UnsafeGet(ptr) + decoder.fieldDecoder.Decode(fieldPtr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%s: %s", decoder.field.Name(), iter.Error.Error()) + } +} + +type stringModeStringDecoder struct { + elemDecoder ValDecoder + cfg *frozenConfig +} + +func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.elemDecoder.Decode(ptr, iter) + str := *((*string)(ptr)) + tempIter := decoder.cfg.BorrowIterator([]byte(str)) + defer decoder.cfg.ReturnIterator(tempIter) + *((*string)(ptr)) = tempIter.ReadString() +} + +type stringModeNumberDecoder struct { + elemDecoder ValDecoder +} + +func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.WhatIsNext() == NilValue { + decoder.elemDecoder.Decode(ptr, iter) + return + } + + c := iter.nextToken() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return + } + decoder.elemDecoder.Decode(ptr, iter) + if iter.Error != nil { + return + } + c = iter.readByte() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go new file mode 100644 index 000000000..152e3ef5a --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go @@ -0,0 +1,211 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "unsafe" +) + +func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { + type bindingTo struct { + binding *Binding + toName string + ignored bool + } + orderedBindings := []*bindingTo{} + structDescriptor := describeStruct(ctx, typ) + for _, binding := range structDescriptor.Fields { + for _, toName := range binding.ToNames { + new := &bindingTo{ + binding: binding, + toName: toName, + } + for _, old := range orderedBindings { + if old.toName != toName { + continue + } + old.ignored, new.ignored = resolveConflictBinding(ctx.frozenConfig, old.binding, new.binding) + } + orderedBindings = append(orderedBindings, new) + } + } + if len(orderedBindings) == 0 { + return &emptyStructEncoder{} + } + finalOrderedFields := []structFieldTo{} + for _, bindingTo := range orderedBindings { + if !bindingTo.ignored { + finalOrderedFields = append(finalOrderedFields, structFieldTo{ + encoder: bindingTo.binding.Encoder.(*structFieldEncoder), + toName: bindingTo.toName, + }) + } + } + return &structEncoder{typ, finalOrderedFields} +} + +func createCheckIsEmpty(ctx *ctx, typ reflect2.Type) checkIsEmpty { + encoder := createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return &structEncoder{typ: typ} + case reflect.Array: + return &arrayEncoder{} + case reflect.Slice: + return &sliceEncoder{} + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return &OptionalEncoder{} + default: + return &lazyErrorEncoder{err: fmt.Errorf("unsupported type: %v", typ)} + } +} + +func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ignoreNew bool) { + newTagged := new.Field.Tag().Get(cfg.getTagKey()) != "" + oldTagged := old.Field.Tag().Get(cfg.getTagKey()) != "" + if newTagged { + if oldTagged { + if len(old.levels) > len(new.levels) { + return true, false + } else if len(new.levels) > len(old.levels) { + return false, true + } else { + return true, true + } + } else { + return true, false + } + } else { + if oldTagged { + return true, false + } + if len(old.levels) > len(new.levels) { + return true, false + } else if len(new.levels) > len(old.levels) { + return false, true + } else { + return true, true + } + } +} + +type structFieldEncoder struct { + field reflect2.StructField + fieldEncoder ValEncoder + omitempty bool +} + +func (encoder *structFieldEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + fieldPtr := encoder.field.UnsafeGet(ptr) + encoder.fieldEncoder.Encode(fieldPtr, stream) + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%s: %s", encoder.field.Name(), stream.Error.Error()) + } +} + +func (encoder *structFieldEncoder) IsEmpty(ptr unsafe.Pointer) bool { + fieldPtr := encoder.field.UnsafeGet(ptr) + return encoder.fieldEncoder.IsEmpty(fieldPtr) +} + +func (encoder *structFieldEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + isEmbeddedPtrNil, converted := encoder.fieldEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := encoder.field.UnsafeGet(ptr) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type IsEmbeddedPtrNil interface { + IsEmbeddedPtrNil(ptr unsafe.Pointer) bool +} + +type structEncoder struct { + typ reflect2.Type + fields []structFieldTo +} + +type structFieldTo struct { + encoder *structFieldEncoder + toName string +} + +func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteObjectStart() + isNotFirst := false + for _, field := range encoder.fields { + if field.encoder.omitempty && field.encoder.IsEmpty(ptr) { + continue + } + if field.encoder.IsEmbeddedPtrNil(ptr) { + continue + } + if isNotFirst { + stream.WriteMore() + } + stream.WriteObjectField(field.toName) + field.encoder.Encode(ptr, stream) + isNotFirst = true + } + stream.WriteObjectEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v.%s", encoder.typ, stream.Error.Error()) + } +} + +func (encoder *structEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type emptyStructEncoder struct { +} + +func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteEmptyObject() +} + +func (encoder *emptyStructEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type stringModeNumberEncoder struct { + elemEncoder ValEncoder +} + +func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.elemEncoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} + +type stringModeStringEncoder struct { + elemEncoder ValEncoder + cfg *frozenConfig +} + +func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + tempStream := encoder.cfg.BorrowStream(nil) + tempStream.Attachment = stream.Attachment + defer encoder.cfg.ReturnStream(tempStream) + encoder.elemEncoder.Encode(ptr, tempStream) + stream.WriteString(string(tempStream.Buffer())) +} + +func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/stream.go b/vendor/github.com/json-iterator/go/stream.go new file mode 100644 index 000000000..23d8a3ad6 --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream.go @@ -0,0 +1,210 @@ +package jsoniter + +import ( + "io" +) + +// stream is a io.Writer like object, with JSON specific write functions. +// Error is not returned as return value, but stored as Error member on this stream instance. +type Stream struct { + cfg *frozenConfig + out io.Writer + buf []byte + Error error + indention int + Attachment interface{} // open for customized encoder +} + +// NewStream create new stream instance. +// cfg can be jsoniter.ConfigDefault. +// out can be nil if write to internal buffer. +// bufSize is the initial size for the internal buffer in bytes. +func NewStream(cfg API, out io.Writer, bufSize int) *Stream { + return &Stream{ + cfg: cfg.(*frozenConfig), + out: out, + buf: make([]byte, 0, bufSize), + Error: nil, + indention: 0, + } +} + +// Pool returns a pool can provide more stream with same configuration +func (stream *Stream) Pool() StreamPool { + return stream.cfg +} + +// Reset reuse this stream instance by assign a new writer +func (stream *Stream) Reset(out io.Writer) { + stream.out = out + stream.buf = stream.buf[:0] +} + +// Available returns how many bytes are unused in the buffer. +func (stream *Stream) Available() int { + return cap(stream.buf) - len(stream.buf) +} + +// Buffered returns the number of bytes that have been written into the current buffer. +func (stream *Stream) Buffered() int { + return len(stream.buf) +} + +// Buffer if writer is nil, use this method to take the result +func (stream *Stream) Buffer() []byte { + return stream.buf +} + +// SetBuffer allows to append to the internal buffer directly +func (stream *Stream) SetBuffer(buf []byte) { + stream.buf = buf +} + +// Write writes the contents of p into the buffer. +// It returns the number of bytes written. +// If nn < len(p), it also returns an error explaining +// why the write is short. +func (stream *Stream) Write(p []byte) (nn int, err error) { + stream.buf = append(stream.buf, p...) + if stream.out != nil { + nn, err = stream.out.Write(stream.buf) + stream.buf = stream.buf[nn:] + return + } + return len(p), nil +} + +// WriteByte writes a single byte. +func (stream *Stream) writeByte(c byte) { + stream.buf = append(stream.buf, c) +} + +func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) { + stream.buf = append(stream.buf, c1, c2) +} + +func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) { + stream.buf = append(stream.buf, c1, c2, c3) +} + +func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) { + stream.buf = append(stream.buf, c1, c2, c3, c4) +} + +func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) { + stream.buf = append(stream.buf, c1, c2, c3, c4, c5) +} + +// Flush writes any buffered data to the underlying io.Writer. +func (stream *Stream) Flush() error { + if stream.out == nil { + return nil + } + if stream.Error != nil { + return stream.Error + } + _, err := stream.out.Write(stream.buf) + if err != nil { + if stream.Error == nil { + stream.Error = err + } + return err + } + stream.buf = stream.buf[:0] + return nil +} + +// WriteRaw write string out without quotes, just like []byte +func (stream *Stream) WriteRaw(s string) { + stream.buf = append(stream.buf, s...) +} + +// WriteNil write null to stream +func (stream *Stream) WriteNil() { + stream.writeFourBytes('n', 'u', 'l', 'l') +} + +// WriteTrue write true to stream +func (stream *Stream) WriteTrue() { + stream.writeFourBytes('t', 'r', 'u', 'e') +} + +// WriteFalse write false to stream +func (stream *Stream) WriteFalse() { + stream.writeFiveBytes('f', 'a', 'l', 's', 'e') +} + +// WriteBool write true or false into stream +func (stream *Stream) WriteBool(val bool) { + if val { + stream.WriteTrue() + } else { + stream.WriteFalse() + } +} + +// WriteObjectStart write { with possible indention +func (stream *Stream) WriteObjectStart() { + stream.indention += stream.cfg.indentionStep + stream.writeByte('{') + stream.writeIndention(0) +} + +// WriteObjectField write "field": with possible indention +func (stream *Stream) WriteObjectField(field string) { + stream.WriteString(field) + if stream.indention > 0 { + stream.writeTwoBytes(':', ' ') + } else { + stream.writeByte(':') + } +} + +// WriteObjectEnd write } with possible indention +func (stream *Stream) WriteObjectEnd() { + stream.writeIndention(stream.cfg.indentionStep) + stream.indention -= stream.cfg.indentionStep + stream.writeByte('}') +} + +// WriteEmptyObject write {} +func (stream *Stream) WriteEmptyObject() { + stream.writeByte('{') + stream.writeByte('}') +} + +// WriteMore write , with possible indention +func (stream *Stream) WriteMore() { + stream.writeByte(',') + stream.writeIndention(0) +} + +// WriteArrayStart write [ with possible indention +func (stream *Stream) WriteArrayStart() { + stream.indention += stream.cfg.indentionStep + stream.writeByte('[') + stream.writeIndention(0) +} + +// WriteEmptyArray write [] +func (stream *Stream) WriteEmptyArray() { + stream.writeTwoBytes('[', ']') +} + +// WriteArrayEnd write ] with possible indention +func (stream *Stream) WriteArrayEnd() { + stream.writeIndention(stream.cfg.indentionStep) + stream.indention -= stream.cfg.indentionStep + stream.writeByte(']') +} + +func (stream *Stream) writeIndention(delta int) { + if stream.indention == 0 { + return + } + stream.writeByte('\n') + toWrite := stream.indention - delta + for i := 0; i < toWrite; i++ { + stream.buf = append(stream.buf, ' ') + } +} diff --git a/vendor/github.com/json-iterator/go/stream_float.go b/vendor/github.com/json-iterator/go/stream_float.go new file mode 100644 index 000000000..826aa594a --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_float.go @@ -0,0 +1,111 @@ +package jsoniter + +import ( + "fmt" + "math" + "strconv" +) + +var pow10 []uint64 + +func init() { + pow10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000} +} + +// WriteFloat32 write float32 to stream +func (stream *Stream) WriteFloat32(val float32) { + if math.IsInf(float64(val), 0) || math.IsNaN(float64(val)) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + abs := math.Abs(float64(val)) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + if float32(abs) < 1e-6 || float32(abs) >= 1e21 { + fmt = 'e' + } + } + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32) +} + +// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster +func (stream *Stream) WriteFloat32Lossy(val float32) { + if math.IsInf(float64(val), 0) || math.IsNaN(float64(val)) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + if val < 0 { + stream.writeByte('-') + val = -val + } + if val > 0x4ffffff { + stream.WriteFloat32(val) + return + } + precision := 6 + exp := uint64(1000000) // 6 + lval := uint64(float64(val)*float64(exp) + 0.5) + stream.WriteUint64(lval / exp) + fval := lval % exp + if fval == 0 { + return + } + stream.writeByte('.') + for p := precision - 1; p > 0 && fval < pow10[p]; p-- { + stream.writeByte('0') + } + stream.WriteUint64(fval) + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] + } +} + +// WriteFloat64 write float64 to stream +func (stream *Stream) WriteFloat64(val float64) { + if math.IsInf(val, 0) || math.IsNaN(val) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + abs := math.Abs(val) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + if abs < 1e-6 || abs >= 1e21 { + fmt = 'e' + } + } + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64) +} + +// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster +func (stream *Stream) WriteFloat64Lossy(val float64) { + if math.IsInf(val, 0) || math.IsNaN(val) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + if val < 0 { + stream.writeByte('-') + val = -val + } + if val > 0x4ffffff { + stream.WriteFloat64(val) + return + } + precision := 6 + exp := uint64(1000000) // 6 + lval := uint64(val*float64(exp) + 0.5) + stream.WriteUint64(lval / exp) + fval := lval % exp + if fval == 0 { + return + } + stream.writeByte('.') + for p := precision - 1; p > 0 && fval < pow10[p]; p-- { + stream.writeByte('0') + } + stream.WriteUint64(fval) + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] + } +} diff --git a/vendor/github.com/json-iterator/go/stream_int.go b/vendor/github.com/json-iterator/go/stream_int.go new file mode 100644 index 000000000..d1059ee4c --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_int.go @@ -0,0 +1,190 @@ +package jsoniter + +var digits []uint32 + +func init() { + digits = make([]uint32, 1000) + for i := uint32(0); i < 1000; i++ { + digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0' + if i < 10 { + digits[i] += 2 << 24 + } else if i < 100 { + digits[i] += 1 << 24 + } + } +} + +func writeFirstBuf(space []byte, v uint32) []byte { + start := v >> 24 + if start == 0 { + space = append(space, byte(v>>16), byte(v>>8)) + } else if start == 1 { + space = append(space, byte(v>>8)) + } + space = append(space, byte(v)) + return space +} + +func writeBuf(buf []byte, v uint32) []byte { + return append(buf, byte(v>>16), byte(v>>8), byte(v)) +} + +// WriteUint8 write uint8 to stream +func (stream *Stream) WriteUint8(val uint8) { + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteInt8 write int8 to stream +func (stream *Stream) WriteInt8(nval int8) { + var val uint8 + if nval < 0 { + val = uint8(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint8(nval) + } + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteUint16 write uint16 to stream +func (stream *Stream) WriteUint16(val uint16) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return +} + +// WriteInt16 write int16 to stream +func (stream *Stream) WriteInt16(nval int16) { + var val uint16 + if nval < 0 { + val = uint16(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint16(nval) + } + stream.WriteUint16(val) +} + +// WriteUint32 write uint32 to stream +func (stream *Stream) WriteUint32(val uint32) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + } else { + r3 := q2 - q3*1000 + stream.buf = append(stream.buf, byte(q3+'0')) + stream.buf = writeBuf(stream.buf, digits[r3]) + } + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt32 write int32 to stream +func (stream *Stream) WriteInt32(nval int32) { + var val uint32 + if nval < 0 { + val = uint32(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint32(nval) + } + stream.WriteUint32(val) +} + +// WriteUint64 write uint64 to stream +func (stream *Stream) WriteUint64(val uint64) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r3 := q2 - q3*1000 + q4 := q3 / 1000 + if q4 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q3]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r4 := q3 - q4*1000 + q5 := q4 / 1000 + if q5 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q4]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r5 := q4 - q5*1000 + q6 := q5 / 1000 + if q6 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q5]) + } else { + stream.buf = writeFirstBuf(stream.buf, digits[q6]) + r6 := q5 - q6*1000 + stream.buf = writeBuf(stream.buf, digits[r6]) + } + stream.buf = writeBuf(stream.buf, digits[r5]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt64 write int64 to stream +func (stream *Stream) WriteInt64(nval int64) { + var val uint64 + if nval < 0 { + val = uint64(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint64(nval) + } + stream.WriteUint64(val) +} + +// WriteInt write int to stream +func (stream *Stream) WriteInt(val int) { + stream.WriteInt64(int64(val)) +} + +// WriteUint write uint to stream +func (stream *Stream) WriteUint(val uint) { + stream.WriteUint64(uint64(val)) +} diff --git a/vendor/github.com/json-iterator/go/stream_str.go b/vendor/github.com/json-iterator/go/stream_str.go new file mode 100644 index 000000000..54c2ba0b3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_str.go @@ -0,0 +1,372 @@ +package jsoniter + +import ( + "unicode/utf8" +) + +// htmlSafeSet holds the value true if the ASCII character with the given +// array position can be safely represented inside a JSON string, embedded +// inside of HTML + + + + + +` diff --git a/vendor/github.com/swaggo/files/v2/.gitmodules b/vendor/github.com/swaggo/files/v2/.gitmodules new file mode 100644 index 000000000..dda717576 --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/.gitmodules @@ -0,0 +1,3 @@ +[submodule "swagger-ui"] + path = swagger-ui + url = https://github.com/swagger-api/swagger-ui.git diff --git a/vendor/github.com/swaggo/files/v2/LICENSE b/vendor/github.com/swaggo/files/v2/LICENSE new file mode 100644 index 000000000..1667ee95a --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Swaggo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/swaggo/files/v2/Makefile b/vendor/github.com/swaggo/files/v2/Makefile new file mode 100644 index 000000000..9ee79423c --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/Makefile @@ -0,0 +1,10 @@ +all: build + +.PHONY: init +init: + git submodule update --init --recursive + +.PHONY: build +build: + rm -rf dist/* + cp -r swagger-ui/dist/* dist/ \ No newline at end of file diff --git a/vendor/github.com/swaggo/files/v2/README.md b/vendor/github.com/swaggo/files/v2/README.md new file mode 100644 index 000000000..7732bdba8 --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/README.md @@ -0,0 +1,9 @@ +# swaggerFiles + +[![Build Status](https://github.com/swaggo/files/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/features/actions) +[![Go Report Card](https://goreportcard.com/badge/github.com/swaggo/files)](https://goreportcard.com/report/github.com/swaggo/files) + +Generate swagger ui embedded files by using: +``` + make +``` \ No newline at end of file diff --git a/vendor/github.com/swaggo/files/v2/dist/favicon-16x16.png b/vendor/github.com/swaggo/files/v2/dist/favicon-16x16.png new file mode 100644 index 000000000..8b194e617 Binary files /dev/null and b/vendor/github.com/swaggo/files/v2/dist/favicon-16x16.png differ diff --git a/vendor/github.com/swaggo/files/v2/dist/favicon-32x32.png b/vendor/github.com/swaggo/files/v2/dist/favicon-32x32.png new file mode 100644 index 000000000..249737fe4 Binary files /dev/null and b/vendor/github.com/swaggo/files/v2/dist/favicon-32x32.png differ diff --git a/vendor/github.com/swaggo/files/v2/dist/index.css b/vendor/github.com/swaggo/files/v2/dist/index.css new file mode 100644 index 000000000..f2376fdaa --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/dist/index.css @@ -0,0 +1,16 @@ +html { + box-sizing: border-box; + overflow: -moz-scrollbars-vertical; + overflow-y: scroll; +} + +*, +*:before, +*:after { + box-sizing: inherit; +} + +body { + margin: 0; + background: #fafafa; +} diff --git a/vendor/github.com/swaggo/files/v2/dist/index.html b/vendor/github.com/swaggo/files/v2/dist/index.html new file mode 100644 index 000000000..84ae62d3d --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/dist/index.html @@ -0,0 +1,19 @@ + + + + + + Swagger UI + + + + + + + +
+ + + + + diff --git a/vendor/github.com/swaggo/files/v2/dist/oauth2-redirect.html b/vendor/github.com/swaggo/files/v2/dist/oauth2-redirect.html new file mode 100644 index 000000000..564091718 --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/dist/oauth2-redirect.html @@ -0,0 +1,79 @@ + + + + Swagger UI: OAuth2 Redirect + + + + + diff --git a/vendor/github.com/swaggo/files/v2/dist/swagger-initializer.js b/vendor/github.com/swaggo/files/v2/dist/swagger-initializer.js new file mode 100644 index 000000000..8ea0ea3af --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/dist/swagger-initializer.js @@ -0,0 +1,20 @@ +window.onload = function() { + // + + // the following lines will be replaced by docker/configurator, when it runs in a docker-container + window.ui = SwaggerUIBundle({ + url: "https://petstore.swagger.io/v2/swagger.json", + dom_id: '#swagger-ui', + deepLinking: true, + presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIStandalonePreset + ], + plugins: [ + SwaggerUIBundle.plugins.DownloadUrl + ], + layout: "StandaloneLayout" + }); + + // +}; diff --git a/vendor/github.com/swaggo/files/v2/dist/swagger-ui-bundle.js b/vendor/github.com/swaggo/files/v2/dist/swagger-ui-bundle.js new file mode 100644 index 000000000..763a11668 --- /dev/null +++ b/vendor/github.com/swaggo/files/v2/dist/swagger-ui-bundle.js @@ -0,0 +1,3 @@ +/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIBundle=t():e.SwaggerUIBundle=t()}(this,(function(){return(()=>{var e={17967:(e,t)=>{"use strict";t.N=void 0;var r=/^([^\w]*)(javascript|data|vbscript)/im,n=/&#(\w+)(^\w|;)?/g,o=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,a=/^([^:]+):/gm,i=[".","/"];t.N=function(e){var t,s=(t=e||"",t.replace(n,(function(e,t){return String.fromCharCode(t)}))).replace(o,"").trim();if(!s)return"about:blank";if(function(e){return i.indexOf(e[0])>-1}(s))return s;var l=s.match(a);if(!l)return s;var u=l[0];return r.test(u)?"about:blank":s}},53795:(e,t,r)=>{"use strict";r.d(t,{Z:()=>P});var n=r(23101),o=r.n(n),a=r(61125),i=r.n(a),s=r(11882),l=r.n(s),u=r(97606),c=r.n(u),p=r(67294),f=r(43393);function h(e){return h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},h(e)}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=k(t,r),o=e||Object.keys(y({},r,{},t));return o.every(n)}function k(e,t){return function(r){if("string"==typeof r)return(0,f.is)(t[r],e[r]);if(Array.isArray(r))return(0,f.is)(S(t,r),S(e,r));throw new TypeError("Invalid key: expected Array or string: "+r)}}var C=function(e){function t(){return d(this,t),E(this,b(t).apply(this,arguments))}var r,n,o;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&w(e,t)}(t,e),r=t,n=[{key:"shouldComponentUpdate",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!A(this.updateOnProps,this.props,e,"updateOnProps")||!A(this.updateOnStates,this.state,t,"updateOnStates")}}],n&&m(r.prototype,n),o&&m(r,o),t}(p.Component);const O=C;var j=r(23930),I=r.n(j),N=r(45697),T=r.n(N);class P extends O{constructor(){super(...arguments),i()(this,"getModelName",(e=>-1!==l()(e).call(e,"#/definitions/")?e.replace(/^.*#\/definitions\//,""):-1!==l()(e).call(e,"#/components/schemas/")?e.replace(/^.*#\/components\/schemas\//,""):void 0)),i()(this,"getRefSchema",(e=>{let{specSelectors:t}=this.props;return t.findDefinition(e)}))}render(){let{getComponent:e,getConfigs:t,specSelectors:n,schema:a,required:i,name:s,isRef:l,specPath:u,displayName:c,includeReadOnly:f,includeWriteOnly:h}=this.props;const d=e("ObjectModel"),m=e("ArrayModel"),g=e("PrimitiveModel");let v="object",y=a&&a.get("$$ref");if(!s&&y&&(s=this.getModelName(y)),!a&&y&&(a=this.getRefSchema(s)),!a)return p.createElement("span",{className:"model model-title"},p.createElement("span",{className:"model-title__text"},c||s),p.createElement("img",{src:r(2517),height:"20px",width:"20px"}));const b=n.isOAS3()&&a.get("deprecated");switch(l=void 0!==l?l:!!y,v=a&&a.get("type")||v,v){case"object":return p.createElement(d,o()({className:"object"},this.props,{specPath:u,getConfigs:t,schema:a,name:s,deprecated:b,isRef:l,includeReadOnly:f,includeWriteOnly:h}));case"array":return p.createElement(m,o()({className:"array"},this.props,{getConfigs:t,schema:a,name:s,deprecated:b,required:i,includeReadOnly:f,includeWriteOnly:h}));default:return p.createElement(g,o()({},this.props,{getComponent:e,getConfigs:t,schema:a,name:s,deprecated:b,required:i}))}}}i()(P,"propTypes",{schema:c()(I()).isRequired,getComponent:T().func.isRequired,getConfigs:T().func.isRequired,specSelectors:T().object.isRequired,name:T().string,displayName:T().string,isRef:T().bool,required:T().bool,expandDepth:T().number,depth:T().number,specPath:I().list.isRequired,includeReadOnly:T().bool,includeWriteOnly:T().bool})},5623:(e,t,r)=>{"use strict";r.d(t,{Z:()=>f});var n=r(61125),o=r.n(n),a=r(28222),i=r.n(a),s=r(67294),l=r(84564),u=r.n(l),c=r(90242),p=r(27504);class f extends s.Component{constructor(e,t){super(e,t),o()(this,"getDefinitionUrl",(()=>{let{specSelectors:e}=this.props;return new(u())(e.url(),p.Z.location).toString()}));let{getConfigs:r}=e,{validatorUrl:n}=r();this.state={url:this.getDefinitionUrl(),validatorUrl:void 0===n?"https://validator.swagger.io/validator":n}}UNSAFE_componentWillReceiveProps(e){let{getConfigs:t}=e,{validatorUrl:r}=t();this.setState({url:this.getDefinitionUrl(),validatorUrl:void 0===r?"https://validator.swagger.io/validator":r})}render(){let{getConfigs:e}=this.props,{spec:t}=e(),r=(0,c.Nm)(this.state.validatorUrl);return"object"==typeof t&&i()(t).length?null:this.state.url&&(0,c.hW)(this.state.validatorUrl)&&(0,c.hW)(this.state.url)?s.createElement("span",{className:"float-right"},s.createElement("a",{target:"_blank",rel:"noopener noreferrer",href:`${r}/debug?url=${encodeURIComponent(this.state.url)}`},s.createElement(h,{src:`${r}?url=${encodeURIComponent(this.state.url)}`,alt:"Online validator badge"}))):null}}class h extends s.Component{constructor(e){super(e),this.state={loaded:!1,error:!1}}componentDidMount(){const e=new Image;e.onload=()=>{this.setState({loaded:!0})},e.onerror=()=>{this.setState({error:!0})},e.src=this.props.src}UNSAFE_componentWillReceiveProps(e){if(e.src!==this.props.src){const t=new Image;t.onload=()=>{this.setState({loaded:!0})},t.onerror=()=>{this.setState({error:!0})},t.src=e.src}}render(){return this.state.error?s.createElement("img",{alt:"Error"}):this.state.loaded?s.createElement("img",{src:this.props.src,alt:this.props.alt}):null}}},86019:(e,t,r)=>{"use strict";r.d(t,{Z:()=>me,s:()=>ge});var n=r(67294),o=r(89927);function a(e,t){if(Array.prototype.indexOf)return e.indexOf(t);for(var r=0,n=e.length;r=0;r--)!0===t(e[r])&&e.splice(r,1)}function s(e){throw new Error("Unhandled case for value: '"+e+"'")}var l=function(){function e(e){void 0===e&&(e={}),this.tagName="",this.attrs={},this.innerHTML="",this.whitespaceRegex=/\s+/,this.tagName=e.tagName||"",this.attrs=e.attrs||{},this.innerHTML=e.innerHtml||e.innerHTML||""}return e.prototype.setTagName=function(e){return this.tagName=e,this},e.prototype.getTagName=function(){return this.tagName||""},e.prototype.setAttr=function(e,t){return this.getAttrs()[e]=t,this},e.prototype.getAttr=function(e){return this.getAttrs()[e]},e.prototype.setAttrs=function(e){return Object.assign(this.getAttrs(),e),this},e.prototype.getAttrs=function(){return this.attrs||(this.attrs={})},e.prototype.setClass=function(e){return this.setAttr("class",e)},e.prototype.addClass=function(e){for(var t,r=this.getClass(),n=this.whitespaceRegex,o=r?r.split(n):[],i=e.split(n);t=i.shift();)-1===a(o,t)&&o.push(t);return this.getAttrs().class=o.join(" "),this},e.prototype.removeClass=function(e){for(var t,r=this.getClass(),n=this.whitespaceRegex,o=r?r.split(n):[],i=e.split(n);o.length&&(t=i.shift());){var s=a(o,t);-1!==s&&o.splice(s,1)}return this.getAttrs().class=o.join(" "),this},e.prototype.getClass=function(){return this.getAttrs().class||""},e.prototype.hasClass=function(e){return-1!==(" "+this.getClass()+" ").indexOf(" "+e+" ")},e.prototype.setInnerHTML=function(e){return this.innerHTML=e,this},e.prototype.setInnerHtml=function(e){return this.setInnerHTML(e)},e.prototype.getInnerHTML=function(){return this.innerHTML||""},e.prototype.getInnerHtml=function(){return this.getInnerHTML()},e.prototype.toAnchorString=function(){var e=this.getTagName(),t=this.buildAttrsStr();return["<",e,t=t?" "+t:"",">",this.getInnerHtml(),""].join("")},e.prototype.buildAttrsStr=function(){if(!this.attrs)return"";var e=this.getAttrs(),t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(r+'="'+e[r]+'"');return t.join(" ")},e}();var u=function(){function e(e){void 0===e&&(e={}),this.newWindow=!1,this.truncate={},this.className="",this.newWindow=e.newWindow||!1,this.truncate=e.truncate||{},this.className=e.className||""}return e.prototype.build=function(e){return new l({tagName:"a",attrs:this.createAttrs(e),innerHtml:this.processAnchorText(e.getAnchorText())})},e.prototype.createAttrs=function(e){var t={href:e.getAnchorHref()},r=this.createCssClass(e);return r&&(t.class=r),this.newWindow&&(t.target="_blank",t.rel="noopener noreferrer"),this.truncate&&this.truncate.length&&this.truncate.length=s)return l.host.length==t?(l.host.substr(0,t-o)+r).substr(0,s+n):i(c,s).substr(0,s+n);var p="";if(l.path&&(p+="/"+l.path),l.query&&(p+="?"+l.query),p){if((c+p).length>=s)return(c+p).length==t?(c+p).substr(0,t):(c+i(p,s-c.length)).substr(0,s+n);c+=p}if(l.fragment){var f="#"+l.fragment;if((c+f).length>=s)return(c+f).length==t?(c+f).substr(0,t):(c+i(f,s-c.length)).substr(0,s+n);c+=f}if(l.scheme&&l.host){var h=l.scheme+"://";if((c+h).length0&&(d=c.substr(-1*Math.floor(s/2))),(c.substr(0,Math.ceil(s/2))+r+d).substr(0,s+n)}(e,r):"middle"===n?function(e,t,r){if(e.length<=t)return e;var n,o;null==r?(r="…",n=8,o=3):(n=r.length,o=r.length);var a=t-o,i="";return a>0&&(i=e.substr(-1*Math.floor(a/2))),(e.substr(0,Math.ceil(a/2))+r+i).substr(0,a+n)}(e,r):function(e,t,r){return function(e,t,r){var n;return e.length>t&&(null==r?(r="…",n=3):n=r.length,e=e.substring(0,t-n)+r),e}(e,t,r)}(e,r)},e}(),c=function(){function e(e){this.__jsduckDummyDocProp=null,this.matchedText="",this.offset=0,this.tagBuilder=e.tagBuilder,this.matchedText=e.matchedText,this.offset=e.offset}return e.prototype.getMatchedText=function(){return this.matchedText},e.prototype.setOffset=function(e){this.offset=e},e.prototype.getOffset=function(){return this.offset},e.prototype.getCssClassSuffixes=function(){return[this.getType()]},e.prototype.buildTag=function(){return this.tagBuilder.build(this)},e}(),p=function(e,t){return p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},p(e,t)};function f(e,t){function r(){this.constructor=e}p(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var h=function(){return h=Object.assign||function(e){for(var t,r=1,n=arguments.length;r-1},e.isValidUriScheme=function(e){var t=e.match(this.uriSchemeRegex),r=t&&t[0].toLowerCase();return"javascript:"!==r&&"vbscript:"!==r},e.urlMatchDoesNotHaveProtocolOrDot=function(e,t){return!(!e||t&&this.hasFullProtocolRegex.test(t)||-1!==e.indexOf("."))},e.urlMatchDoesNotHaveAtLeastOneWordChar=function(e,t){return!(!e||!t)&&(!this.hasFullProtocolRegex.test(t)&&!this.hasWordCharAfterProtocolRegex.test(e))},e.hasFullProtocolRegex=/^[A-Za-z][-.+A-Za-z0-9]*:\/\//,e.uriSchemeRegex=/^[A-Za-z][-.+A-Za-z0-9]*:/,e.hasWordCharAfterProtocolRegex=new RegExp(":[^\\s]*?["+C+"]"),e.ipRegex=/[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/,e}(),V=(d=new RegExp("[/?#](?:["+N+"\\-+&@#/%=~_()|'$*\\[\\]{}?!:,.;^✓]*["+N+"\\-+&@#/%=~_()|'$*\\[\\]{}✓])?"),new RegExp(["(?:","(",/(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/.source,M(2),")","|","(","(//)?",/(?:www\.)/.source,M(6),")","|","(","(//)?",M(10)+"\\.",L.source,"(?![-"+I+"])",")",")","(?::[0-9]+)?","(?:"+d.source+")?"].join(""),"gi")),$=new RegExp("["+N+"]"),W=function(e){function t(t){var r=e.call(this,t)||this;return r.stripPrefix={scheme:!0,www:!0},r.stripTrailingSlash=!0,r.decodePercentEncoding=!0,r.matcherRegex=V,r.wordCharRegExp=$,r.stripPrefix=t.stripPrefix,r.stripTrailingSlash=t.stripTrailingSlash,r.decodePercentEncoding=t.decodePercentEncoding,r}return f(t,e),t.prototype.parseMatches=function(e){for(var t,r=this.matcherRegex,n=this.stripPrefix,o=this.stripTrailingSlash,a=this.decodePercentEncoding,i=this.tagBuilder,s=[],l=function(){var r=t[0],l=t[1],c=t[4],p=t[5],f=t[9],h=t.index,d=p||f,m=e.charAt(h-1);if(!q.isValid(r,l))return"continue";if(h>0&&"@"===m)return"continue";if(h>0&&d&&u.wordCharRegExp.test(m))return"continue";if(/\?$/.test(r)&&(r=r.substr(0,r.length-1)),u.matchHasUnbalancedClosingParen(r))r=r.substr(0,r.length-1);else{var g=u.matchHasInvalidCharAfterTld(r,l);g>-1&&(r=r.substr(0,g))}var v=["http://","https://"].find((function(e){return!!l&&-1!==l.indexOf(e)}));if(v){var y=r.indexOf(v);r=r.substr(y),l=l.substr(y),h+=y}var w=l?"scheme":c?"www":"tld",E=!!l;s.push(new b({tagBuilder:i,matchedText:r,offset:h,urlMatchType:w,url:r,protocolUrlMatch:E,protocolRelativeMatch:!!d,stripPrefix:n,stripTrailingSlash:o,decodePercentEncoding:a}))},u=this;null!==(t=r.exec(e));)l();return s},t.prototype.matchHasUnbalancedClosingParen=function(e){var t,r=e.charAt(e.length-1);if(")"===r)t="(";else if("]"===r)t="[";else{if("}"!==r)return!1;t="{"}for(var n=0,o=0,a=e.length-1;o"===e?(m=new ne(h(h({},m),{name:H()})),W()):E.test(e)||x.test(e)||":"===e||V()}function w(e){">"===e?V():E.test(e)?f=3:V()}function _(e){S.test(e)||("/"===e?f=12:">"===e?W():"<"===e?$():"="===e||A.test(e)||k.test(e)?V():f=5)}function C(e){S.test(e)?f=6:"/"===e?f=12:"="===e?f=7:">"===e?W():"<"===e?$():A.test(e)&&V()}function O(e){S.test(e)||("/"===e?f=12:"="===e?f=7:">"===e?W():"<"===e?$():A.test(e)?V():f=5)}function j(e){S.test(e)||('"'===e?f=8:"'"===e?f=9:/[>=`]/.test(e)?V():"<"===e?$():f=10)}function I(e){'"'===e&&(f=11)}function N(e){"'"===e&&(f=11)}function T(e){S.test(e)?f=4:">"===e?W():"<"===e&&$()}function P(e){S.test(e)?f=4:"/"===e?f=12:">"===e?W():"<"===e?$():(f=4,c--)}function R(e){">"===e?(m=new ne(h(h({},m),{isClosing:!0})),W()):f=4}function M(t){"--"===e.substr(c,2)?(c+=2,m=new ne(h(h({},m),{type:"comment"})),f=14):"DOCTYPE"===e.substr(c,7).toUpperCase()?(c+=7,m=new ne(h(h({},m),{type:"doctype"})),f=20):V()}function D(e){"-"===e?f=15:">"===e?V():f=16}function L(e){"-"===e?f=18:">"===e?V():f=16}function B(e){"-"===e&&(f=17)}function F(e){f="-"===e?18:16}function z(e){">"===e?W():"!"===e?f=19:"-"===e||(f=16)}function U(e){"-"===e?f=17:">"===e?W():f=16}function q(e){">"===e?W():"<"===e&&$()}function V(){f=0,m=u}function $(){f=1,m=new ne({idx:c})}function W(){var t=e.slice(d,m.idx);t&&a(t,d),"comment"===m.type?i(m.idx):"doctype"===m.type?l(m.idx):(m.isOpening&&n(m.name,m.idx),m.isClosing&&o(m.name,m.idx)),V(),d=c+1}function H(){var t=m.idx+(m.isClosing?2:1);return e.slice(t,c).toLowerCase()}d=0&&n++},onText:function(e,r){if(0===n){var a=function(e,t){if(!t.global)throw new Error("`splitRegex` must have the 'g' flag set");for(var r,n=[],o=0;r=t.exec(e);)n.push(e.substring(o,r.index)),n.push(r[0]),o=r.index+r[0].length;return n.push(e.substring(o)),n}(e,/( | |<|<|>|>|"|"|')/gi),i=r;a.forEach((function(e,r){if(r%2==0){var n=t.parseText(e,i);o.push.apply(o,n)}i+=e.length}))}},onCloseTag:function(e){r.indexOf(e)>=0&&(n=Math.max(n-1,0))},onComment:function(e){},onDoctype:function(e){}}),o=this.compactMatches(o),o=this.removeUnwantedMatches(o)},e.prototype.compactMatches=function(e){e.sort((function(e,t){return e.getOffset()-t.getOffset()}));for(var t=0;to?t:t+1;e.splice(i,1);continue}e[t+1].getOffset()/g,">"));for(var t=this.parse(e),r=[],n=0,o=0,a=t.length;o/i.test(e)}function se(){var e=[],t=new oe({stripPrefix:!1,url:!0,email:!0,replaceFn:function(t){switch(t.getType()){case"url":e.push({text:t.matchedText,url:t.getUrl()});break;case"email":e.push({text:t.matchedText,url:"mailto:"+t.getEmail().replace(/^mailto:/i,"")})}return!1}});return{links:e,autolinker:t}}function le(e){var t,r,n,o,a,i,s,l,u,c,p,f,h,d,m=e.tokens,g=null;for(r=0,n=m.length;r=0;t--)if("link_close"!==(a=o[t]).type){if("htmltag"===a.type&&(d=a.content,/^\s]/i.test(d)&&p>0&&p--,ie(a.content)&&p++),!(p>0)&&"text"===a.type&&ae.test(a.content)){if(g||(f=(g=se()).links,h=g.autolinker),i=a.content,f.length=0,h.link(i),!f.length)continue;for(s=[],c=a.level,l=0;l({useUnsafeMarkdown:!1})};const me=de;function ge(e){let{useUnsafeMarkdown:t=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=t,n=t?[]:["style","class"];return t&&!ge.hasWarnedAboutDeprecation&&(console.warn("useUnsafeMarkdown display configuration parameter is deprecated since >3.26.0 and will be removed in v4.0.0."),ge.hasWarnedAboutDeprecation=!0),pe().sanitize(e,{ADD_ATTR:["target"],FORBID_TAGS:["style","form"],ALLOW_DATA_ATTR:r,FORBID_ATTR:n})}ge.hasWarnedAboutDeprecation=!1},45308:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>f});var n,o=r(86),a=r.n(o),i=r(8712),s=r.n(i),l=r(90242),u=r(27621);const c=r(95102),p={},f=p;a()(n=s()(c).call(c)).call(n,(function(e){if("./index.js"===e)return;let t=c(e);p[(0,l.Zl)(e)]=t.default?t.default:t})),p.SafeRender=u.default},55812:(e,t,r)=>{"use strict";r.r(t),r.d(t,{SHOW_AUTH_POPUP:()=>p,AUTHORIZE:()=>f,LOGOUT:()=>h,PRE_AUTHORIZE_OAUTH2:()=>d,AUTHORIZE_OAUTH2:()=>m,VALIDATE:()=>g,CONFIGURE_AUTH:()=>v,RESTORE_AUTHORIZATION:()=>y,showDefinitions:()=>b,authorize:()=>w,authorizeWithPersistOption:()=>E,logout:()=>x,logoutWithPersistOption:()=>_,preAuthorizeImplicit:()=>S,authorizeOauth2:()=>A,authorizeOauth2WithPersistOption:()=>k,authorizePassword:()=>C,authorizeApplication:()=>O,authorizeAccessCodeWithFormParams:()=>j,authorizeAccessCodeWithBasicAuthentication:()=>I,authorizeRequest:()=>N,configureAuth:()=>T,restoreAuthorization:()=>P,persistAuthorizationIfNeeded:()=>R,authPopup:()=>M});var n=r(35627),o=r.n(n),a=r(76986),i=r.n(a),s=r(84564),l=r.n(s),u=r(27504),c=r(90242);const p="show_popup",f="authorize",h="logout",d="pre_authorize_oauth2",m="authorize_oauth2",g="validate",v="configure_auth",y="restore_authorization";function b(e){return{type:p,payload:e}}function w(e){return{type:f,payload:e}}const E=e=>t=>{let{authActions:r}=t;r.authorize(e),r.persistAuthorizationIfNeeded()};function x(e){return{type:h,payload:e}}const _=e=>t=>{let{authActions:r}=t;r.logout(e),r.persistAuthorizationIfNeeded()},S=e=>t=>{let{authActions:r,errActions:n}=t,{auth:a,token:i,isValid:s}=e,{schema:l,name:c}=a,p=l.get("flow");delete u.Z.swaggerUIRedirectOauth2,"accessCode"===p||s||n.newAuthErr({authId:c,source:"auth",level:"warning",message:"Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"}),i.error?n.newAuthErr({authId:c,source:"auth",level:"error",message:o()(i)}):r.authorizeOauth2WithPersistOption({auth:a,token:i})};function A(e){return{type:m,payload:e}}const k=e=>t=>{let{authActions:r}=t;r.authorizeOauth2(e),r.persistAuthorizationIfNeeded()},C=e=>t=>{let{authActions:r}=t,{schema:n,name:o,username:a,password:s,passwordType:l,clientId:u,clientSecret:p}=e,f={grant_type:"password",scope:e.scopes.join(" "),username:a,password:s},h={};switch(l){case"request-body":!function(e,t,r){t&&i()(e,{client_id:t});r&&i()(e,{client_secret:r})}(f,u,p);break;case"basic":h.Authorization="Basic "+(0,c.r3)(u+":"+p);break;default:console.warn(`Warning: invalid passwordType ${l} was passed, not including client id and secret`)}return r.authorizeRequest({body:(0,c.GZ)(f),url:n.get("tokenUrl"),name:o,headers:h,query:{},auth:e})};const O=e=>t=>{let{authActions:r}=t,{schema:n,scopes:o,name:a,clientId:i,clientSecret:s}=e,l={Authorization:"Basic "+(0,c.r3)(i+":"+s)},u={grant_type:"client_credentials",scope:o.join(" ")};return r.authorizeRequest({body:(0,c.GZ)(u),name:a,url:n.get("tokenUrl"),auth:e,headers:l})},j=e=>{let{auth:t,redirectUrl:r}=e;return e=>{let{authActions:n}=e,{schema:o,name:a,clientId:i,clientSecret:s,codeVerifier:l}=t,u={grant_type:"authorization_code",code:t.code,client_id:i,client_secret:s,redirect_uri:r,code_verifier:l};return n.authorizeRequest({body:(0,c.GZ)(u),name:a,url:o.get("tokenUrl"),auth:t})}},I=e=>{let{auth:t,redirectUrl:r}=e;return e=>{let{authActions:n}=e,{schema:o,name:a,clientId:i,clientSecret:s,codeVerifier:l}=t,u={Authorization:"Basic "+(0,c.r3)(i+":"+s)},p={grant_type:"authorization_code",code:t.code,client_id:i,redirect_uri:r,code_verifier:l};return n.authorizeRequest({body:(0,c.GZ)(p),name:a,url:o.get("tokenUrl"),auth:t,headers:u})}},N=e=>t=>{let r,{fn:n,getConfigs:a,authActions:s,errActions:u,oas3Selectors:c,specSelectors:p,authSelectors:f}=t,{body:h,query:d={},headers:m={},name:g,url:v,auth:y}=e,{additionalQueryStringParams:b}=f.getConfigs()||{};if(p.isOAS3()){let e=c.serverEffectiveValue(c.selectedServer());r=l()(v,e,!0)}else r=l()(v,p.url(),!0);"object"==typeof b&&(r.query=i()({},r.query,b));const w=r.toString();let E=i()({Accept:"application/json, text/plain, */*","Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"},m);n.fetch({url:w,method:"post",headers:E,query:d,body:h,requestInterceptor:a().requestInterceptor,responseInterceptor:a().responseInterceptor}).then((function(e){let t=JSON.parse(e.data),r=t&&(t.error||""),n=t&&(t.parseError||"");e.ok?r||n?u.newAuthErr({authId:g,level:"error",source:"auth",message:o()(t)}):s.authorizeOauth2WithPersistOption({auth:y,token:t}):u.newAuthErr({authId:g,level:"error",source:"auth",message:e.statusText})})).catch((e=>{let t=new Error(e).message;if(e.response&&e.response.data){const r=e.response.data;try{const e="string"==typeof r?JSON.parse(r):r;e.error&&(t+=`, error: ${e.error}`),e.error_description&&(t+=`, description: ${e.error_description}`)}catch(e){}}u.newAuthErr({authId:g,level:"error",source:"auth",message:t})}))};function T(e){return{type:v,payload:e}}function P(e){return{type:y,payload:e}}const R=()=>e=>{let{authSelectors:t,getConfigs:r}=e;if(r().persistAuthorization){const e=t.authorized();localStorage.setItem("authorized",o()(e.toJS()))}},M=(e,t)=>()=>{u.Z.swaggerUIRedirectOauth2=t,u.Z.open(e)}},93705:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u,preauthorizeBasic:()=>c,preauthorizeApiKey:()=>p});var n=r(11189),o=r.n(n),a=r(43962),i=r(55812),s=r(60035),l=r(48302);function u(){return{afterLoad(e){this.rootInjects=this.rootInjects||{},this.rootInjects.initOAuth=e.authActions.configureAuth,this.rootInjects.preauthorizeApiKey=o()(p).call(p,null,e),this.rootInjects.preauthorizeBasic=o()(c).call(c,null,e)},statePlugins:{auth:{reducers:a.default,actions:i,selectors:s},spec:{wrapActions:l}}}}function c(e,t,r,n){const{authActions:{authorize:o},specSelectors:{specJson:a,isOAS3:i}}=e,s=i()?["components","securitySchemes"]:["securityDefinitions"],l=a().getIn([...s,t]);return l?o({[t]:{value:{username:r,password:n},schema:l.toJS()}}):null}function p(e,t,r){const{authActions:{authorize:n},specSelectors:{specJson:o,isOAS3:a}}=e,i=a()?["components","securitySchemes"]:["securityDefinitions"],s=o().getIn([...i,t]);return s?n({[t]:{value:r,schema:s.toJS()}}):null}},43962:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>c});var n=r(86),o=r.n(n),a=r(76986),i=r.n(a),s=r(43393),l=r(90242),u=r(55812);const c={[u.SHOW_AUTH_POPUP]:(e,t)=>{let{payload:r}=t;return e.set("showDefinitions",r)},[u.AUTHORIZE]:(e,t)=>{var r;let{payload:n}=t,a=(0,s.fromJS)(n),i=e.get("authorized")||(0,s.Map)();return o()(r=a.entrySeq()).call(r,(t=>{let[r,n]=t;if(!(0,l.Wl)(n.getIn))return e.set("authorized",i);let o=n.getIn(["schema","type"]);if("apiKey"===o||"http"===o)i=i.set(r,n);else if("basic"===o){let e=n.getIn(["value","username"]),t=n.getIn(["value","password"]);i=i.setIn([r,"value"],{username:e,header:"Basic "+(0,l.r3)(e+":"+t)}),i=i.setIn([r,"schema"],n.get("schema"))}})),e.set("authorized",i)},[u.AUTHORIZE_OAUTH2]:(e,t)=>{let r,{payload:n}=t,{auth:o,token:a}=n;o.token=i()({},a),r=(0,s.fromJS)(o);let l=e.get("authorized")||(0,s.Map)();return l=l.set(r.get("name"),r),e.set("authorized",l)},[u.LOGOUT]:(e,t)=>{let{payload:r}=t,n=e.get("authorized").withMutations((e=>{o()(r).call(r,(t=>{e.delete(t)}))}));return e.set("authorized",n)},[u.CONFIGURE_AUTH]:(e,t)=>{let{payload:r}=t;return e.set("configs",r)},[u.RESTORE_AUTHORIZATION]:(e,t)=>{let{payload:r}=t;return e.set("authorized",(0,s.fromJS)(r.authorized))}}},60035:(e,t,r)=>{"use strict";r.r(t),r.d(t,{shownDefinitions:()=>y,definitionsToAuthorize:()=>b,getDefinitionsByNames:()=>w,definitionsForRequirements:()=>E,authorized:()=>x,isAuthorized:()=>_,getConfigs:()=>S});var n=r(86),o=r.n(n),a=r(51679),i=r.n(a),s=r(14418),l=r.n(s),u=r(11882),c=r.n(u),p=r(97606),f=r.n(p),h=r(28222),d=r.n(h),m=r(20573),g=r(43393);const v=e=>e,y=(0,m.P1)(v,(e=>e.get("showDefinitions"))),b=(0,m.P1)(v,(()=>e=>{var t;let{specSelectors:r}=e,n=r.securityDefinitions()||(0,g.Map)({}),a=(0,g.List)();return o()(t=n.entrySeq()).call(t,(e=>{let[t,r]=e,n=(0,g.Map)();n=n.set(t,r),a=a.push(n)})),a})),w=(e,t)=>e=>{var r;let{specSelectors:n}=e;console.warn("WARNING: getDefinitionsByNames is deprecated and will be removed in the next major version.");let a=n.securityDefinitions(),i=(0,g.List)();return o()(r=t.valueSeq()).call(r,(e=>{var t;let r=(0,g.Map)();o()(t=e.entrySeq()).call(t,(e=>{let t,[n,i]=e,s=a.get(n);var l;"oauth2"===s.get("type")&&i.size&&(t=s.get("scopes"),o()(l=t.keySeq()).call(l,(e=>{i.contains(e)||(t=t.delete(e))})),s=s.set("allowedScopes",t));r=r.set(n,s)})),i=i.push(r)})),i},E=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,g.List)();return e=>{let{authSelectors:r}=e;const n=r.definitionsToAuthorize()||(0,g.List)();let a=(0,g.List)();return o()(n).call(n,(e=>{let r=i()(t).call(t,(t=>t.get(e.keySeq().first())));r&&(o()(e).call(e,((t,n)=>{if("oauth2"===t.get("type")){const i=r.get(n);let s=t.get("scopes");var a;if(g.List.isList(i)&&g.Map.isMap(s))o()(a=s.keySeq()).call(a,(e=>{i.contains(e)||(s=s.delete(e))})),e=e.set(n,t.set("scopes",s))}})),a=a.push(e))})),a}},x=(0,m.P1)(v,(e=>e.get("authorized")||(0,g.Map)())),_=(e,t)=>e=>{var r;let{authSelectors:n}=e,o=n.authorized();return g.List.isList(t)?!!l()(r=t.toJS()).call(r,(e=>{var t,r;return-1===c()(t=f()(r=d()(e)).call(r,(e=>!!o.get(e)))).call(t,!1)})).length:null},S=(0,m.P1)(v,(e=>e.get("configs")))},48302:(e,t,r)=>{"use strict";r.r(t),r.d(t,{execute:()=>n});const n=(e,t)=>{let{authSelectors:r,specSelectors:n}=t;return t=>{let{path:o,method:a,operation:i,extras:s}=t,l={authorized:r.authorized()&&r.authorized().toJS(),definitions:n.securityDefinitions()&&n.securityDefinitions().toJS(),specSecurity:n.security()&&n.security().toJS()};return e({path:o,method:a,operation:i,securities:l,...s})}}},70714:(e,t,r)=>{"use strict";r.r(t),r.d(t,{UPDATE_CONFIGS:()=>n,TOGGLE_CONFIGS:()=>o,update:()=>a,toggle:()=>i,loaded:()=>s});const n="configs_update",o="configs_toggle";function a(e,t){return{type:n,payload:{[e]:t}}}function i(e){return{type:o,payload:e}}const s=()=>e=>{let{getConfigs:t,authActions:r}=e;if(t().persistAuthorization){const e=localStorage.getItem("authorized");e&&r.restoreAuthorization({authorized:JSON.parse(e)})}}},92256:(e,t,r)=>{"use strict";r.r(t),r.d(t,{parseYamlConfig:()=>o});var n=r(1272);const o=(e,t)=>{try{return n.ZP.load(e)}catch(e){return t&&t.errActions.newThrownErr(new Error(e)),{}}}},1661:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>c});var n=r(15163),o=r(92256),a=r(70714),i=r(22698),s=r(69018),l=r(37743);const u={getLocalConfig:()=>(0,o.parseYamlConfig)(n)};function c(){return{statePlugins:{spec:{actions:i,selectors:u},configs:{reducers:l.default,actions:a,selectors:s}}}}},37743:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>a});var n=r(43393),o=r(70714);const a={[o.UPDATE_CONFIGS]:(e,t)=>e.merge((0,n.fromJS)(t.payload)),[o.TOGGLE_CONFIGS]:(e,t)=>{const r=t.payload,n=e.get(r);return e.set(r,!n)}}},69018:(e,t,r)=>{"use strict";r.r(t),r.d(t,{get:()=>a});var n=r(58309),o=r.n(n);const a=(e,t)=>e.getIn(o()(t)?t:[t])},22698:(e,t,r)=>{"use strict";r.r(t),r.d(t,{downloadConfig:()=>o,getConfigByUrl:()=>a});var n=r(92256);const o=e=>t=>{const{fn:{fetch:r}}=t;return r(e)},a=(e,t)=>r=>{let{specActions:o}=r;if(e)return o.downloadConfig(e).then(a,a);function a(r){r instanceof Error||r.status>=400?(o.updateLoadingStatus("failedConfig"),o.updateLoadingStatus("failedConfig"),o.updateUrl(""),console.error(r.statusText+" "+e.url),t(null)):t((0,n.parseYamlConfig)(r.text))}}},31970:(e,t,r)=>{"use strict";r.r(t),r.d(t,{setHash:()=>n});const n=e=>e?history.pushState(null,null,`#${e}`):window.location.hash=""},34980:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(41599),o=r(60877),a=r(34584);function i(){return[n.default,{statePlugins:{configs:{wrapActions:{loaded:(e,t)=>function(){e(...arguments);const r=decodeURIComponent(window.location.hash);t.layoutActions.parseDeepLinkHash(r)}}}},wrapComponents:{operation:o.default,OperationTag:a.default}}]}},41599:(e,t,r)=>{"use strict";r.r(t),r.d(t,{show:()=>b,scrollTo:()=>w,parseDeepLinkHash:()=>E,readyToScroll:()=>x,scrollToElement:()=>_,clearScrollTo:()=>S,default:()=>A});var n=r(58309),o=r.n(n),a=r(24278),i=r.n(a),s=r(97606),l=r.n(s),u=r(11882),c=r.n(u),p=r(31970),f=r(45172),h=r.n(f),d=r(90242),m=r(43393),g=r.n(m);const v="layout_scroll_to",y="layout_clear_scroll",b=(e,t)=>{let{getConfigs:r,layoutSelectors:n}=t;return function(){for(var t=arguments.length,a=new Array(t),i=0;i({type:v,payload:o()(e)?e:[e]}),E=e=>t=>{let{layoutActions:r,layoutSelectors:n,getConfigs:o}=t;if(o().deepLinking&&e){var a;let t=i()(e).call(e,1);"!"===t[0]&&(t=i()(t).call(t,1)),"/"===t[0]&&(t=i()(t).call(t,1));const o=l()(a=t.split("/")).call(a,(e=>e||"")),s=n.isShownKeyFromUrlHashArray(o),[u,p="",f=""]=s;if("operations"===u){const e=n.isShownKeyFromUrlHashArray([p]);c()(p).call(p,"_")>-1&&(console.warn("Warning: escaping deep link whitespace with `_` will be unsupported in v4.0, use `%20` instead."),r.show(l()(e).call(e,(e=>e.replace(/_/g," "))),!0)),r.show(e,!0)}(c()(p).call(p,"_")>-1||c()(f).call(f,"_")>-1)&&(console.warn("Warning: escaping deep link whitespace with `_` will be unsupported in v4.0, use `%20` instead."),r.show(l()(s).call(s,(e=>e.replace(/_/g," "))),!0)),r.show(s,!0),r.scrollTo(s)}},x=(e,t)=>r=>{const n=r.layoutSelectors.getScrollToKey();g().is(n,(0,m.fromJS)(e))&&(r.layoutActions.scrollToElement(t),r.layoutActions.clearScrollTo())},_=(e,t)=>r=>{try{t=t||r.fn.getScrollParent(e),h().createScroller(t).to(e)}catch(e){console.error(e)}},S=()=>({type:y});const A={fn:{getScrollParent:function(e,t){const r=document.documentElement;let n=getComputedStyle(e);const o="absolute"===n.position,a=t?/(auto|scroll|hidden)/:/(auto|scroll)/;if("fixed"===n.position)return r;for(let t=e;t=t.parentElement;)if(n=getComputedStyle(t),(!o||"static"!==n.position)&&a.test(n.overflow+n.overflowY+n.overflowX))return t;return r}},statePlugins:{layout:{actions:{scrollToElement:_,scrollTo:w,clearScrollTo:S,readyToScroll:x,parseDeepLinkHash:E},selectors:{getScrollToKey:e=>e.get("scrollToKey"),isShownKeyFromUrlHashArray(e,t){const[r,n]=t;return n?["operations",r,n]:r?["operations-tag",r]:[]},urlHashArrayFromIsShownKey(e,t){let[r,n,o]=t;return"operations"==r?[n,o]:"operations-tag"==r?[n]:[]}},reducers:{[v]:(e,t)=>e.set("scrollToKey",g().fromJS(t.payload)),[y]:e=>e.delete("scrollToKey")},wrapActions:{show:b}}}}},34584:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(61125),o=r.n(n),a=r(67294);const i=(e,t)=>class extends a.Component{constructor(){super(...arguments),o()(this,"onLoad",(e=>{const{tag:r}=this.props,n=["operations-tag",r];t.layoutActions.readyToScroll(n,e)}))}render(){return a.createElement("span",{ref:this.onLoad},a.createElement(e,this.props))}}},60877:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(61125),o=r.n(n),a=r(67294);r(23930);const i=(e,t)=>class extends a.Component{constructor(){super(...arguments),o()(this,"onLoad",(e=>{const{operation:r}=this.props,{tag:n,operationId:o}=r.toObject();let{isShownKey:a}=r.toObject();a=a||["operations",n,o],t.layoutActions.readyToScroll(a,e)}))}render(){return a.createElement("span",{ref:this.onLoad},a.createElement(e,this.props))}}},48011:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>d});var n=r(76986),o=r.n(n),a=r(63460),i=r.n(a),s=r(11882),l=r.n(s),u=r(35627),c=r.n(u),p=r(20573),f=r(43393),h=r(27504);function d(e){let{fn:t}=e;return{statePlugins:{spec:{actions:{download:e=>r=>{let{errActions:n,specSelectors:a,specActions:s,getConfigs:l}=r,{fetch:u}=t;const c=l();function p(t){if(t instanceof Error||t.status>=400)return s.updateLoadingStatus("failed"),n.newThrownErr(o()(new Error((t.message||t.statusText)+" "+e),{source:"fetch"})),void(!t.status&&t instanceof Error&&function(){try{let t;if("URL"in h.Z?t=new(i())(e):(t=document.createElement("a"),t.href=e),"https:"!==t.protocol&&"https:"===h.Z.location.protocol){const e=o()(new Error(`Possible mixed-content issue? The page was loaded over https:// but a ${t.protocol}// URL was specified. Check that you are not attempting to load mixed content.`),{source:"fetch"});return void n.newThrownErr(e)}if(t.origin!==h.Z.location.origin){const e=o()(new Error(`Possible cross-origin (CORS) issue? The URL origin (${t.origin}) does not match the page (${h.Z.location.origin}). Check the server returns the correct 'Access-Control-Allow-*' headers.`),{source:"fetch"});n.newThrownErr(e)}}catch(e){return}}());s.updateLoadingStatus("success"),s.updateSpec(t.text),a.url()!==e&&s.updateUrl(e)}e=e||a.url(),s.updateLoadingStatus("loading"),n.clear({source:"fetch"}),u({url:e,loadSpec:!0,requestInterceptor:c.requestInterceptor||(e=>e),responseInterceptor:c.responseInterceptor||(e=>e),credentials:"same-origin",headers:{Accept:"application/json,*/*"}}).then(p,p)},updateLoadingStatus:e=>{let t=[null,"loading","failed","success","failedConfig"];return-1===l()(t).call(t,e)&&console.error(`Error: ${e} is not one of ${c()(t)}`),{type:"spec_update_loading_status",payload:e}}},reducers:{spec_update_loading_status:(e,t)=>"string"==typeof t.payload?e.set("loadingStatus",t.payload):e},selectors:{loadingStatus:(0,p.P1)((e=>e||(0,f.Map)()),(e=>e.get("loadingStatus")||null))}}}}}},34966:(e,t,r)=>{"use strict";r.r(t),r.d(t,{NEW_THROWN_ERR:()=>o,NEW_THROWN_ERR_BATCH:()=>a,NEW_SPEC_ERR:()=>i,NEW_SPEC_ERR_BATCH:()=>s,NEW_AUTH_ERR:()=>l,CLEAR:()=>u,CLEAR_BY:()=>c,newThrownErr:()=>p,newThrownErrBatch:()=>f,newSpecErr:()=>h,newSpecErrBatch:()=>d,newAuthErr:()=>m,clear:()=>g,clearBy:()=>v});var n=r(7710);const o="err_new_thrown_err",a="err_new_thrown_err_batch",i="err_new_spec_err",s="err_new_spec_err_batch",l="err_new_auth_err",u="err_clear",c="err_clear_by";function p(e){return{type:o,payload:(0,n.serializeError)(e)}}function f(e){return{type:a,payload:e}}function h(e){return{type:i,payload:e}}function d(e){return{type:s,payload:e}}function m(e){return{type:l,payload:e}}function g(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:u,payload:e}}function v(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>!0;return{type:c,payload:e}}},56982:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>c});var n=r(14418),o=r.n(n),a=r(97606),i=r.n(a),s=r(54061),l=r.n(s);const u=[r(2392),r(21835)];function c(e){var t;let r={jsSpec:{}},n=l()(u,((e,t)=>{try{let n=t.transform(e,r);return o()(n).call(n,(e=>!!e))}catch(t){return console.error("Transformer error:",t),e}}),e);return i()(t=o()(n).call(n,(e=>!!e))).call(t,(e=>(!e.get("line")&&e.get("path"),e)))}},2392:(e,t,r)=>{"use strict";r.r(t),r.d(t,{transform:()=>p});var n=r(97606),o=r.n(n),a=r(11882),i=r.n(a),s=r(24278),l=r.n(s),u=r(24282),c=r.n(u);function p(e){return o()(e).call(e,(e=>{var t;let r="is not of a type(s)",n=i()(t=e.get("message")).call(t,r);if(n>-1){var o,a;let t=l()(o=e.get("message")).call(o,n+r.length).split(",");return e.set("message",l()(a=e.get("message")).call(a,0,n)+function(e){return c()(e).call(e,((e,t,r,n)=>r===n.length-1&&n.length>1?e+"or "+t:n[r+1]&&n.length>2?e+t+", ":n[r+1]?e+t+" ":e+t),"should be a")}(t))}return e}))}},21835:(e,t,r)=>{"use strict";r.r(t),r.d(t,{transform:()=>n});r(97606),r(11882),r(27361),r(43393);function n(e,t){let{jsSpec:r}=t;return e}},77793:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(93527),o=r(34966),a=r(87667);function i(e){return{statePlugins:{err:{reducers:(0,n.default)(e),actions:o,selectors:a}}}}},93527:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>v});var n=r(76986),o=r.n(n),a=r(97606),i=r.n(a),s=r(39022),l=r.n(s),u=r(14418),c=r.n(u),p=r(2250),f=r.n(p),h=r(34966),d=r(43393),m=r(56982);let g={line:0,level:"error",message:"Unknown error"};function v(){return{[h.NEW_THROWN_ERR]:(e,t)=>{let{payload:r}=t,n=o()(g,r,{type:"thrown"});return e.update("errors",(e=>(e||(0,d.List)()).push((0,d.fromJS)(n)))).update("errors",(e=>(0,m.default)(e)))},[h.NEW_THROWN_ERR_BATCH]:(e,t)=>{let{payload:r}=t;return r=i()(r).call(r,(e=>(0,d.fromJS)(o()(g,e,{type:"thrown"})))),e.update("errors",(e=>{var t;return l()(t=e||(0,d.List)()).call(t,(0,d.fromJS)(r))})).update("errors",(e=>(0,m.default)(e)))},[h.NEW_SPEC_ERR]:(e,t)=>{let{payload:r}=t,n=(0,d.fromJS)(r);return n=n.set("type","spec"),e.update("errors",(e=>(e||(0,d.List)()).push((0,d.fromJS)(n)).sortBy((e=>e.get("line"))))).update("errors",(e=>(0,m.default)(e)))},[h.NEW_SPEC_ERR_BATCH]:(e,t)=>{let{payload:r}=t;return r=i()(r).call(r,(e=>(0,d.fromJS)(o()(g,e,{type:"spec"})))),e.update("errors",(e=>{var t;return l()(t=e||(0,d.List)()).call(t,(0,d.fromJS)(r))})).update("errors",(e=>(0,m.default)(e)))},[h.NEW_AUTH_ERR]:(e,t)=>{let{payload:r}=t,n=(0,d.fromJS)(o()({},r));return n=n.set("type","auth"),e.update("errors",(e=>(e||(0,d.List)()).push((0,d.fromJS)(n)))).update("errors",(e=>(0,m.default)(e)))},[h.CLEAR]:(e,t)=>{var r;let{payload:n}=t;if(!n||!e.get("errors"))return e;let o=c()(r=e.get("errors")).call(r,(e=>{var t;return f()(t=e.keySeq()).call(t,(t=>{const r=e.get(t),o=n[t];return!o||r!==o}))}));return e.merge({errors:o})},[h.CLEAR_BY]:(e,t)=>{var r;let{payload:n}=t;if(!n||"function"!=typeof n)return e;let o=c()(r=e.get("errors")).call(r,(e=>n(e)));return e.merge({errors:o})}}}},87667:(e,t,r)=>{"use strict";r.r(t),r.d(t,{allErrors:()=>a,lastError:()=>i});var n=r(43393),o=r(20573);const a=(0,o.P1)((e=>e),(e=>e.get("errors",(0,n.List)()))),i=(0,o.P1)(a,(e=>e.last()))},49978:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(4309);function o(){return{fn:{opsFilter:n.default}}}},4309:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>s});var n=r(14418),o=r.n(n),a=r(11882),i=r.n(a);function s(e,t){return o()(e).call(e,((e,r)=>-1!==i()(r).call(r,t)))}},25474:(e,t,r)=>{"use strict";r.r(t),r.d(t,{UPDATE_LAYOUT:()=>o,UPDATE_FILTER:()=>a,UPDATE_MODE:()=>i,SHOW:()=>s,updateLayout:()=>l,updateFilter:()=>u,show:()=>c,changeMode:()=>p});var n=r(90242);const o="layout_update_layout",a="layout_update_filter",i="layout_update_mode",s="layout_show";function l(e){return{type:o,payload:e}}function u(e){return{type:a,payload:e}}function c(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e=(0,n.AF)(e),{type:s,payload:{thing:e,shown:t}}}function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return e=(0,n.AF)(e),{type:i,payload:{thing:e,mode:t}}}},26821:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>s});var n=r(5672),o=r(25474),a=r(4400),i=r(28989);function s(){return{statePlugins:{layout:{reducers:n.default,actions:o,selectors:a},spec:{wrapSelectors:i}}}}},5672:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>s});var n=r(39022),o=r.n(n),a=r(43393),i=r(25474);const s={[i.UPDATE_LAYOUT]:(e,t)=>e.set("layout",t.payload),[i.UPDATE_FILTER]:(e,t)=>e.set("filter",t.payload),[i.SHOW]:(e,t)=>{const r=t.payload.shown,n=(0,a.fromJS)(t.payload.thing);return e.update("shown",(0,a.fromJS)({}),(e=>e.set(n,r)))},[i.UPDATE_MODE]:(e,t)=>{var r;let n=t.payload.thing,a=t.payload.mode;return e.setIn(o()(r=["modes"]).call(r,n),(a||"")+"")}}},4400:(e,t,r)=>{"use strict";r.r(t),r.d(t,{current:()=>i,currentFilter:()=>s,isShown:()=>l,whatMode:()=>u,showSummary:()=>c});var n=r(20573),o=r(90242),a=r(43393);const i=e=>e.get("layout"),s=e=>e.get("filter"),l=(e,t,r)=>(t=(0,o.AF)(t),e.get("shown",(0,a.fromJS)({})).get((0,a.fromJS)(t),r)),u=function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return t=(0,o.AF)(t),e.getIn(["modes",...t],r)},c=(0,n.P1)((e=>e),(e=>!l(e,"editor")))},28989:(e,t,r)=>{"use strict";r.r(t),r.d(t,{taggedOperations:()=>a});var n=r(24278),o=r.n(n);const a=(e,t)=>function(r){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i=0&&(s=o()(s).call(s,0,f)),s}},9150:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>a});var n=r(11189),o=r.n(n);function a(e){let{configs:t}=e;const r={debug:0,info:1,log:2,warn:3,error:4},n=e=>r[e]||-1;let{logLevel:a}=t,i=n(a);function s(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),o=1;o=i&&console[e](...r)}return s.warn=o()(s).call(s,null,"warn"),s.error=o()(s).call(s,null,"error"),s.info=o()(s).call(s,null,"info"),s.debug=o()(s).call(s,null,"debug"),{rootInjects:{log:s}}}},67002:(e,t,r)=>{"use strict";r.r(t),r.d(t,{UPDATE_SELECTED_SERVER:()=>n,UPDATE_REQUEST_BODY_VALUE:()=>o,UPDATE_REQUEST_BODY_VALUE_RETAIN_FLAG:()=>a,UPDATE_REQUEST_BODY_INCLUSION:()=>i,UPDATE_ACTIVE_EXAMPLES_MEMBER:()=>s,UPDATE_REQUEST_CONTENT_TYPE:()=>l,UPDATE_RESPONSE_CONTENT_TYPE:()=>u,UPDATE_SERVER_VARIABLE_VALUE:()=>c,SET_REQUEST_BODY_VALIDATE_ERROR:()=>p,CLEAR_REQUEST_BODY_VALIDATE_ERROR:()=>f,CLEAR_REQUEST_BODY_VALUE:()=>h,setSelectedServer:()=>d,setRequestBodyValue:()=>m,setRetainRequestBodyValueFlag:()=>g,setRequestBodyInclusion:()=>v,setActiveExamplesMember:()=>y,setRequestContentType:()=>b,setResponseContentType:()=>w,setServerVariableValue:()=>E,setRequestBodyValidateError:()=>x,clearRequestBodyValidateError:()=>_,initRequestBodyValidateError:()=>S,clearRequestBodyValue:()=>A});const n="oas3_set_servers",o="oas3_set_request_body_value",a="oas3_set_request_body_retain_flag",i="oas3_set_request_body_inclusion",s="oas3_set_active_examples_member",l="oas3_set_request_content_type",u="oas3_set_response_content_type",c="oas3_set_server_variable_value",p="oas3_set_request_body_validate_error",f="oas3_clear_request_body_validate_error",h="oas3_clear_request_body_value";function d(e,t){return{type:n,payload:{selectedServerUrl:e,namespace:t}}}function m(e){let{value:t,pathMethod:r}=e;return{type:o,payload:{value:t,pathMethod:r}}}const g=e=>{let{value:t,pathMethod:r}=e;return{type:a,payload:{value:t,pathMethod:r}}};function v(e){let{value:t,pathMethod:r,name:n}=e;return{type:i,payload:{value:t,pathMethod:r,name:n}}}function y(e){let{name:t,pathMethod:r,contextType:n,contextName:o}=e;return{type:s,payload:{name:t,pathMethod:r,contextType:n,contextName:o}}}function b(e){let{value:t,pathMethod:r}=e;return{type:l,payload:{value:t,pathMethod:r}}}function w(e){let{value:t,path:r,method:n}=e;return{type:u,payload:{value:t,path:r,method:n}}}function E(e){let{server:t,namespace:r,key:n,val:o}=e;return{type:c,payload:{server:t,namespace:r,key:n,val:o}}}const x=e=>{let{path:t,method:r,validationErrors:n}=e;return{type:p,payload:{path:t,method:r,validationErrors:n}}},_=e=>{let{path:t,method:r}=e;return{type:f,payload:{path:t,method:r}}},S=e=>{let{pathMethod:t}=e;return{type:f,payload:{path:t[0],method:t[1]}}},A=e=>{let{pathMethod:t}=e;return{type:h,payload:{pathMethod:t}}}},73723:(e,t,r)=>{"use strict";r.r(t),r.d(t,{definitionsToAuthorize:()=>f});var n=r(86),o=r.n(n),a=r(14418),i=r.n(a),s=r(24282),l=r.n(s),u=r(20573),c=r(43393),p=r(7779);const f=(h=(0,u.P1)((e=>e),(e=>{let{specSelectors:t}=e;return t.securityDefinitions()}),((e,t)=>{var r;let n=(0,c.List)();return t?(o()(r=t.entrySeq()).call(r,(e=>{let[t,r]=e;const a=r.get("type");var s;if("oauth2"===a&&o()(s=r.get("flows").entrySeq()).call(s,(e=>{let[o,a]=e,s=(0,c.fromJS)({flow:o,authorizationUrl:a.get("authorizationUrl"),tokenUrl:a.get("tokenUrl"),scopes:a.get("scopes"),type:r.get("type"),description:r.get("description")});n=n.push(new c.Map({[t]:i()(s).call(s,(e=>void 0!==e))}))})),"http"!==a&&"apiKey"!==a||(n=n.push(new c.Map({[t]:r}))),"openIdConnect"===a&&r.get("openIdConnectData")){let e=r.get("openIdConnectData"),a=e.get("grant_types_supported")||["authorization_code","implicit"];o()(a).call(a,(o=>{var a;let s=e.get("scopes_supported")&&l()(a=e.get("scopes_supported")).call(a,((e,t)=>e.set(t,"")),new c.Map),u=(0,c.fromJS)({flow:o,authorizationUrl:e.get("authorization_endpoint"),tokenUrl:e.get("token_endpoint"),scopes:s,type:"oauth2",openIdConnectUrl:r.get("openIdConnectUrl")});n=n.push(new c.Map({[t]:i()(u).call(u,(e=>void 0!==e))}))}))}})),n):n})),(e,t)=>function(){const r=t.getSystem().specSelectors.specJson();for(var n=arguments.length,o=new Array(n),a=0;a{"use strict";r.r(t),r.d(t,{default:()=>u});var n=r(23101),o=r.n(n),a=r(97606),i=r.n(a),s=r(67294),l=(r(23930),r(43393));const u=e=>{var t;let{callbacks:r,getComponent:n,specPath:a}=e;const u=n("OperationContainer",!0);if(!r)return s.createElement("span",null,"No callbacks");let c=i()(t=r.entrySeq()).call(t,(t=>{var r;let[n,c]=t;return s.createElement("div",{key:n},s.createElement("h2",null,n),i()(r=c.entrySeq()).call(r,(t=>{var r;let[c,p]=t;return"$$ref"===c?null:s.createElement("div",{key:c},i()(r=p.entrySeq()).call(r,(t=>{let[r,i]=t;if("$$ref"===r)return null;let p=(0,l.fromJS)({operation:i});return s.createElement(u,o()({},e,{op:p,key:r,tag:"",method:r,path:c,specPath:a.push(n,c,r),allowTryItOut:!1}))})))})))}));return s.createElement("div",null,c)}},86775:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>f});var n=r(61125),o=r.n(n),a=r(76986),i=r.n(a),s=r(14418),l=r.n(s),u=r(97606),c=r.n(u),p=r(67294);class f extends p.Component{constructor(e,t){super(e,t),o()(this,"onChange",(e=>{let{onChange:t}=this.props,{value:r,name:n}=e.target,o=i()({},this.state.value);n?o[n]=r:o=r,this.setState({value:o},(()=>t(this.state)))}));let{name:r,schema:n}=this.props,a=this.getValue();this.state={name:r,schema:n,value:a}}getValue(){let{name:e,authorized:t}=this.props;return t&&t.getIn([e,"value"])}render(){var e;let{schema:t,getComponent:r,errSelectors:n,name:o}=this.props;const a=r("Input"),i=r("Row"),s=r("Col"),u=r("authError"),f=r("Markdown",!0),h=r("JumpToPath",!0),d=(t.get("scheme")||"").toLowerCase();let m=this.getValue(),g=l()(e=n.allErrors()).call(e,(e=>e.get("authId")===o));if("basic"===d){var v;let e=m?m.get("username"):null;return p.createElement("div",null,p.createElement("h4",null,p.createElement("code",null,o||t.get("name")),"  (http, Basic)",p.createElement(h,{path:["securityDefinitions",o]})),e&&p.createElement("h6",null,"Authorized"),p.createElement(i,null,p.createElement(f,{source:t.get("description")})),p.createElement(i,null,p.createElement("label",null,"Username:"),e?p.createElement("code",null," ",e," "):p.createElement(s,null,p.createElement(a,{type:"text",required:"required",name:"username","aria-label":"auth-basic-username",onChange:this.onChange,autoFocus:!0}))),p.createElement(i,null,p.createElement("label",null,"Password:"),e?p.createElement("code",null," ****** "):p.createElement(s,null,p.createElement(a,{autoComplete:"new-password",name:"password",type:"password","aria-label":"auth-basic-password",onChange:this.onChange}))),c()(v=g.valueSeq()).call(v,((e,t)=>p.createElement(u,{error:e,key:t}))))}var y;return"bearer"===d?p.createElement("div",null,p.createElement("h4",null,p.createElement("code",null,o||t.get("name")),"  (http, Bearer)",p.createElement(h,{path:["securityDefinitions",o]})),m&&p.createElement("h6",null,"Authorized"),p.createElement(i,null,p.createElement(f,{source:t.get("description")})),p.createElement(i,null,p.createElement("label",null,"Value:"),m?p.createElement("code",null," ****** "):p.createElement(s,null,p.createElement(a,{type:"text","aria-label":"auth-bearer-value",onChange:this.onChange,autoFocus:!0}))),c()(y=g.valueSeq()).call(y,((e,t)=>p.createElement(u,{error:e,key:t})))):p.createElement("div",null,p.createElement("em",null,p.createElement("b",null,o)," HTTP authentication: unsupported scheme ",`'${d}'`))}}},76467:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>p});var n=r(33427),o=r(42458),a=r(15757),i=r(56617),s=r(9928),l=r(45327),u=r(86775),c=r(96796);const p={Callbacks:n.default,HttpAuth:u.default,RequestBody:o.default,Servers:i.default,ServersContainer:s.default,RequestBodyEditor:l.default,OperationServers:c.default,operationLink:a.default}},15757:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u});var n=r(35627),o=r.n(n),a=r(97606),i=r.n(a),s=r(67294);r(23930);class l extends s.Component{render(){const{link:e,name:t,getComponent:r}=this.props,n=r("Markdown",!0);let a=e.get("operationId")||e.get("operationRef"),l=e.get("parameters")&&e.get("parameters").toJS(),u=e.get("description");return s.createElement("div",{className:"operation-link"},s.createElement("div",{className:"description"},s.createElement("b",null,s.createElement("code",null,t)),u?s.createElement(n,{source:u}):null),s.createElement("pre",null,"Operation `",a,"`",s.createElement("br",null),s.createElement("br",null),"Parameters ",function(e,t){var r;if("string"!=typeof t)return"";return i()(r=t.split("\n")).call(r,((t,r)=>r>0?Array(e+1).join(" ")+t:t)).join("\n")}(0,o()(l,null,2))||"{}",s.createElement("br",null)))}}const u=l},96796:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(61125),o=r.n(n),a=r(67294);r(23930);class i extends a.Component{constructor(){super(...arguments),o()(this,"setSelectedServer",(e=>{const{path:t,method:r}=this.props;return this.forceUpdate(),this.props.setSelectedServer(e,`${t}:${r}`)})),o()(this,"setServerVariableValue",(e=>{const{path:t,method:r}=this.props;return this.forceUpdate(),this.props.setServerVariableValue({...e,namespace:`${t}:${r}`})})),o()(this,"getSelectedServer",(()=>{const{path:e,method:t}=this.props;return this.props.getSelectedServer(`${e}:${t}`)})),o()(this,"getServerVariable",((e,t)=>{const{path:r,method:n}=this.props;return this.props.getServerVariable({namespace:`${r}:${n}`,server:e},t)})),o()(this,"getEffectiveServerValue",(e=>{const{path:t,method:r}=this.props;return this.props.getEffectiveServerValue({server:e,namespace:`${t}:${r}`})}))}render(){const{operationServers:e,pathServers:t,getComponent:r}=this.props;if(!e&&!t)return null;const n=r("Servers"),o=e||t,i=e?"operation":"path";return a.createElement("div",{className:"opblock-section operation-servers"},a.createElement("div",{className:"opblock-section-header"},a.createElement("div",{className:"tab-header"},a.createElement("h4",{className:"opblock-title"},"Servers"))),a.createElement("div",{className:"opblock-description-wrapper"},a.createElement("h4",{className:"message"},"These ",i,"-level options override the global server options."),a.createElement(n,{servers:o,currentServer:this.getSelectedServer(),setSelectedServer:this.setSelectedServer,setServerVariableValue:this.setServerVariableValue,getServerVariable:this.getServerVariable,getEffectiveServerValue:this.getEffectiveServerValue})))}}},45327:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>c});var n=r(61125),o=r.n(n),a=r(67294),i=r(94184),s=r.n(i),l=r(90242);const u=Function.prototype;class c extends a.PureComponent{constructor(e,t){super(e,t),o()(this,"applyDefaultValue",(e=>{const{onChange:t,defaultValue:r}=e||this.props;return this.setState({value:r}),t(r)})),o()(this,"onChange",(e=>{this.props.onChange((0,l.Pz)(e))})),o()(this,"onDomChange",(e=>{const t=e.target.value;this.setState({value:t},(()=>this.onChange(t)))})),this.state={value:(0,l.Pz)(e.value)||e.defaultValue},e.onChange(e.value)}UNSAFE_componentWillReceiveProps(e){this.props.value!==e.value&&e.value!==this.state.value&&this.setState({value:(0,l.Pz)(e.value)}),!e.value&&e.defaultValue&&this.state.value&&this.applyDefaultValue(e)}render(){let{getComponent:e,errors:t}=this.props,{value:r}=this.state,n=t.size>0;const o=e("TextArea");return a.createElement("div",{className:"body-param"},a.createElement(o,{className:s()("body-param__text",{invalid:n}),title:t.size?t.join(", "):"",value:r,onChange:this.onDomChange}))}}o()(c,"defaultProps",{onChange:u,userHasEditedBody:!1})},42458:(e,t,r)=>{"use strict";r.r(t),r.d(t,{getDefaultRequestBodyValue:()=>m,default:()=>g});var n=r(97606),o=r.n(n),a=r(11882),i=r.n(a),s=r(58118),l=r.n(s),u=r(58309),c=r.n(u),p=r(67294),f=(r(23930),r(43393)),h=r(90242),d=r(2518);const m=(e,t,r)=>{const n=e.getIn(["content",t]),o=n.get("schema").toJS(),a=void 0!==n.get("examples"),i=n.get("example"),s=a?n.getIn(["examples",r,"value"]):i,l=(0,h.xi)(o,t,{includeWriteOnly:!0},s);return(0,h.Pz)(l)},g=e=>{let{userHasEditedBody:t,requestBody:r,requestBodyValue:n,requestBodyInclusionSetting:a,requestBodyErrors:s,getComponent:u,getConfigs:g,specSelectors:v,fn:y,contentType:b,isExecute:w,specPath:E,onChange:x,onChangeIncludeEmpty:_,activeExamplesKey:S,updateActiveExamplesKey:A,setRetainRequestBodyValueFlag:k}=e;const C=e=>{x(e.target.files[0])},O=e=>{let t={key:e,shouldDispatchInit:!1,defaultValue:!0};return"no value"===a.get(e,"no value")&&(t.shouldDispatchInit=!0),t},j=u("Markdown",!0),I=u("modelExample"),N=u("RequestBodyEditor"),T=u("highlightCode"),P=u("ExamplesSelectValueRetainer"),R=u("Example"),M=u("ParameterIncludeEmpty"),{showCommonExtensions:D}=g(),L=r&&r.get("description")||null,B=r&&r.get("content")||new f.OrderedMap;b=b||B.keySeq().first()||"";const F=B.get(b,(0,f.OrderedMap)()),z=F.get("schema",(0,f.OrderedMap)()),U=F.get("examples",null),q=null==U?void 0:o()(U).call(U,((e,t)=>{var n;const o=null===(n=e)||void 0===n?void 0:n.get("value",null);return o&&(e=e.set("value",m(r,b,t),o)),e}));if(s=f.List.isList(s)?s:(0,f.List)(),!F.size)return null;const V="object"===F.getIn(["schema","type"]),$="binary"===F.getIn(["schema","format"]),W="base64"===F.getIn(["schema","format"]);if("application/octet-stream"===b||0===i()(b).call(b,"image/")||0===i()(b).call(b,"audio/")||0===i()(b).call(b,"video/")||$||W){const e=u("Input");return w?p.createElement(e,{type:"file",onChange:C}):p.createElement("i",null,"Example values are not available for ",p.createElement("code",null,b)," media types.")}if(V&&("application/x-www-form-urlencoded"===b||0===i()(b).call(b,"multipart/"))&&z.get("properties",(0,f.OrderedMap)()).size>0){var H;const e=u("JsonSchemaForm"),t=u("ParameterExt"),r=z.get("properties",(0,f.OrderedMap)());return n=f.Map.isMap(n)?n:(0,f.OrderedMap)(),p.createElement("div",{className:"table-container"},L&&p.createElement(j,{source:L}),p.createElement("table",null,p.createElement("tbody",null,f.Map.isMap(r)&&o()(H=r.entrySeq()).call(H,(r=>{var i,d;let[m,g]=r;if(g.get("readOnly"))return;let v=D?(0,h.po)(g):null;const b=l()(i=z.get("required",(0,f.List)())).call(i,m),E=g.get("type"),S=g.get("format"),A=g.get("description"),k=n.getIn([m,"value"]),C=n.getIn([m,"errors"])||s,I=a.get(m)||!1,N=g.has("default")||g.has("example")||g.hasIn(["items","example"])||g.hasIn(["items","default"]),T=g.has("enum")&&(1===g.get("enum").size||b),P=N||T;let R="";"array"!==E||P||(R=[]),("object"===E||P)&&(R=(0,h.xi)(g,!1,{includeWriteOnly:!0})),"string"!=typeof R&&"object"===E&&(R=(0,h.Pz)(R)),"string"==typeof R&&"array"===E&&(R=JSON.parse(R));const L="string"===E&&("binary"===S||"base64"===S);return p.createElement("tr",{key:m,className:"parameters","data-property-name":m},p.createElement("td",{className:"parameters-col_name"},p.createElement("div",{className:b?"parameter__name required":"parameter__name"},m,b?p.createElement("span",null," *"):null),p.createElement("div",{className:"parameter__type"},E,S&&p.createElement("span",{className:"prop-format"},"($",S,")"),D&&v.size?o()(d=v.entrySeq()).call(d,(e=>{let[r,n]=e;return p.createElement(t,{key:`${r}-${n}`,xKey:r,xVal:n})})):null),p.createElement("div",{className:"parameter__deprecated"},g.get("deprecated")?"deprecated":null)),p.createElement("td",{className:"parameters-col_description"},p.createElement(j,{source:A}),w?p.createElement("div",null,p.createElement(e,{fn:y,dispatchInitialValue:!L,schema:g,description:m,getComponent:u,value:void 0===k?R:k,required:b,errors:C,onChange:e=>{x(e,[m])}}),b?null:p.createElement(M,{onChange:e=>_(m,e),isIncluded:I,isIncludedOptions:O(m),isDisabled:c()(k)?0!==k.length:!(0,h.O2)(k)})):null))})))))}const J=m(r,b,S);let K=null;return(0,d.O)(J)&&(K="json"),p.createElement("div",null,L&&p.createElement(j,{source:L}),q?p.createElement(P,{userHasEditedBody:t,examples:q,currentKey:S,currentUserInputValue:n,onSelect:e=>{A(e)},updateValue:x,defaultToFirstExample:!0,getComponent:u,setRetainRequestBodyValueFlag:k}):null,w?p.createElement("div",null,p.createElement(N,{value:n,errors:s,defaultValue:J,onChange:x,getComponent:u})):p.createElement(I,{getComponent:u,getConfigs:g,specSelectors:v,expandDepth:1,isExecute:w,schema:F.get("schema"),specPath:E.push("content",b),example:p.createElement(T,{className:"body-param__example",getConfigs:g,language:K,value:(0,h.Pz)(n)||J}),includeWriteOnly:!0}),q?p.createElement(R,{example:q.get(S),getComponent:u,getConfigs:g}):null)}},9928:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(67294);class o extends n.Component{render(){const{specSelectors:e,oas3Selectors:t,oas3Actions:r,getComponent:o}=this.props,a=e.servers(),i=o("Servers");return a&&a.size?n.createElement("div",null,n.createElement("span",{className:"servers-title"},"Servers"),n.createElement(i,{servers:a,currentServer:t.selectedServer(),setSelectedServer:r.setSelectedServer,setServerVariableValue:r.setServerVariableValue,getServerVariable:t.serverVariableValue,getEffectiveServerValue:t.serverEffectiveValue})):null}}},56617:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>p});var n=r(61125),o=r.n(n),a=r(51679),i=r.n(a),s=r(97606),l=r.n(s),u=r(67294),c=r(43393);r(23930);class p extends u.Component{constructor(){super(...arguments),o()(this,"onServerChange",(e=>{this.setServer(e.target.value)})),o()(this,"onServerVariableValueChange",(e=>{let{setServerVariableValue:t,currentServer:r}=this.props,n=e.target.getAttribute("data-variable"),o=e.target.value;"function"==typeof t&&t({server:r,key:n,val:o})})),o()(this,"setServer",(e=>{let{setSelectedServer:t}=this.props;t(e)}))}componentDidMount(){var e;let{servers:t,currentServer:r}=this.props;r||this.setServer(null===(e=t.first())||void 0===e?void 0:e.get("url"))}UNSAFE_componentWillReceiveProps(e){let{servers:t,setServerVariableValue:r,getServerVariable:n}=e;if(this.props.currentServer!==e.currentServer||this.props.servers!==e.servers){var o;let a=i()(t).call(t,(t=>t.get("url")===e.currentServer)),s=i()(o=this.props.servers).call(o,(e=>e.get("url")===this.props.currentServer))||(0,c.OrderedMap)();if(!a)return this.setServer(t.first().get("url"));let u=s.get("variables")||(0,c.OrderedMap)(),p=(i()(u).call(u,(e=>e.get("default")))||(0,c.OrderedMap)()).get("default"),f=a.get("variables")||(0,c.OrderedMap)(),h=(i()(f).call(f,(e=>e.get("default")))||(0,c.OrderedMap)()).get("default");l()(f).call(f,((t,o)=>{n(e.currentServer,o)&&p===h||r({server:e.currentServer,key:o,val:t.get("default")||""})}))}}render(){var e,t;let{servers:r,currentServer:n,getServerVariable:o,getEffectiveServerValue:a}=this.props,s=(i()(r).call(r,(e=>e.get("url")===n))||(0,c.OrderedMap)()).get("variables")||(0,c.OrderedMap)(),p=0!==s.size;return u.createElement("div",{className:"servers"},u.createElement("label",{htmlFor:"servers"},u.createElement("select",{onChange:this.onServerChange,value:n},l()(e=r.valueSeq()).call(e,(e=>u.createElement("option",{value:e.get("url"),key:e.get("url")},e.get("url"),e.get("description")&&` - ${e.get("description")}`))).toArray())),p?u.createElement("div",null,u.createElement("div",{className:"computed-url"},"Computed URL:",u.createElement("code",null,a(n))),u.createElement("h4",null,"Server variables"),u.createElement("table",null,u.createElement("tbody",null,l()(t=s.entrySeq()).call(t,(e=>{var t;let[r,a]=e;return u.createElement("tr",{key:r},u.createElement("td",null,r),u.createElement("td",null,a.get("enum")?u.createElement("select",{"data-variable":r,onChange:this.onServerVariableValueChange},l()(t=a.get("enum")).call(t,(e=>u.createElement("option",{selected:e===o(n,r),key:e,value:e},e)))):u.createElement("input",{type:"text",value:o(n,r)||"",onChange:this.onServerVariableValueChange,"data-variable":r})))}))))):null)}}},7779:(e,t,r)=>{"use strict";r.r(t),r.d(t,{isOAS3:()=>l,isSwagger2:()=>u,OAS3ComponentWrapFactory:()=>c});var n=r(23101),o=r.n(n),a=r(27043),i=r.n(a),s=r(67294);function l(e){const t=e.get("openapi");return"string"==typeof t&&(i()(t).call(t,"3.0.")&&t.length>4)}function u(e){const t=e.get("swagger");return"string"==typeof t&&i()(t).call(t,"2.0")}function c(e){return(t,r)=>n=>{if(r&&r.specSelectors&&r.specSelectors.specJson){return l(r.specSelectors.specJson())?s.createElement(e,o()({},n,r,{Ori:t})):s.createElement(t,n)}return console.warn("OAS3 wrapper: couldn't get spec"),null}}},97451:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>p});var n=r(92044),o=r(73723),a=r(91741),i=r(76467),s=r(37761),l=r(67002),u=r(5065),c=r(62109);function p(){return{components:i.default,wrapComponents:s.default,statePlugins:{spec:{wrapSelectors:n,selectors:a},auth:{wrapSelectors:o},oas3:{actions:l,reducers:c.default,selectors:u}}}}},62109:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>p});var n=r(8712),o=r.n(n),a=r(86),i=r.n(a),s=r(24282),l=r.n(s),u=r(43393),c=r(67002);const p={[c.UPDATE_SELECTED_SERVER]:(e,t)=>{let{payload:{selectedServerUrl:r,namespace:n}}=t;const o=n?[n,"selectedServer"]:["selectedServer"];return e.setIn(o,r)},[c.UPDATE_REQUEST_BODY_VALUE]:(e,t)=>{let{payload:{value:r,pathMethod:n}}=t,[a,s]=n;if(!u.Map.isMap(r))return e.setIn(["requestData",a,s,"bodyValue"],r);let l,c=e.getIn(["requestData",a,s,"bodyValue"])||(0,u.Map)();u.Map.isMap(c)||(c=(0,u.Map)());const[...p]=o()(r).call(r);return i()(p).call(p,(e=>{let t=r.getIn([e]);c.has(e)&&u.Map.isMap(t)||(l=c.setIn([e,"value"],t))})),e.setIn(["requestData",a,s,"bodyValue"],l)},[c.UPDATE_REQUEST_BODY_VALUE_RETAIN_FLAG]:(e,t)=>{let{payload:{value:r,pathMethod:n}}=t,[o,a]=n;return e.setIn(["requestData",o,a,"retainBodyValue"],r)},[c.UPDATE_REQUEST_BODY_INCLUSION]:(e,t)=>{let{payload:{value:r,pathMethod:n,name:o}}=t,[a,i]=n;return e.setIn(["requestData",a,i,"bodyInclusion",o],r)},[c.UPDATE_ACTIVE_EXAMPLES_MEMBER]:(e,t)=>{let{payload:{name:r,pathMethod:n,contextType:o,contextName:a}}=t,[i,s]=n;return e.setIn(["examples",i,s,o,a,"activeExample"],r)},[c.UPDATE_REQUEST_CONTENT_TYPE]:(e,t)=>{let{payload:{value:r,pathMethod:n}}=t,[o,a]=n;return e.setIn(["requestData",o,a,"requestContentType"],r)},[c.UPDATE_RESPONSE_CONTENT_TYPE]:(e,t)=>{let{payload:{value:r,path:n,method:o}}=t;return e.setIn(["requestData",n,o,"responseContentType"],r)},[c.UPDATE_SERVER_VARIABLE_VALUE]:(e,t)=>{let{payload:{server:r,namespace:n,key:o,val:a}}=t;const i=n?[n,"serverVariableValues",r,o]:["serverVariableValues",r,o];return e.setIn(i,a)},[c.SET_REQUEST_BODY_VALIDATE_ERROR]:(e,t)=>{let{payload:{path:r,method:n,validationErrors:o}}=t,a=[];if(a.push("Required field is not provided"),o.missingBodyValue)return e.setIn(["requestData",r,n,"errors"],(0,u.fromJS)(a));if(o.missingRequiredKeys&&o.missingRequiredKeys.length>0){const{missingRequiredKeys:t}=o;return e.updateIn(["requestData",r,n,"bodyValue"],(0,u.fromJS)({}),(e=>l()(t).call(t,((e,t)=>e.setIn([t,"errors"],(0,u.fromJS)(a))),e)))}return console.warn("unexpected result: SET_REQUEST_BODY_VALIDATE_ERROR"),e},[c.CLEAR_REQUEST_BODY_VALIDATE_ERROR]:(e,t)=>{let{payload:{path:r,method:n}}=t;const a=e.getIn(["requestData",r,n,"bodyValue"]);if(!u.Map.isMap(a))return e.setIn(["requestData",r,n,"errors"],(0,u.fromJS)([]));const[...i]=o()(a).call(a);return i?e.updateIn(["requestData",r,n,"bodyValue"],(0,u.fromJS)({}),(e=>l()(i).call(i,((e,t)=>e.setIn([t,"errors"],(0,u.fromJS)([]))),e))):e},[c.CLEAR_REQUEST_BODY_VALUE]:(e,t)=>{let{payload:{pathMethod:r}}=t,[n,o]=r;const a=e.getIn(["requestData",n,o,"bodyValue"]);return a?u.Map.isMap(a)?e.setIn(["requestData",n,o,"bodyValue"],(0,u.Map)()):e.setIn(["requestData",n,o,"bodyValue"],""):e}}},5065:(e,t,r)=>{"use strict";r.r(t),r.d(t,{selectedServer:()=>g,requestBodyValue:()=>v,shouldRetainRequestBodyValue:()=>y,selectDefaultRequestBodyValue:()=>b,hasUserEditedBody:()=>w,requestBodyInclusionSetting:()=>E,requestBodyErrors:()=>x,activeExamplesMember:()=>_,requestContentType:()=>S,responseContentType:()=>A,serverVariableValue:()=>k,serverVariables:()=>C,serverEffectiveValue:()=>O,validateBeforeExecute:()=>j,validateShallowRequired:()=>N});var n=r(97606),o=r.n(n),a=r(86),i=r.n(a),s=r(28222),l=r.n(s),u=r(11882),c=r.n(u),p=r(43393),f=r(7779),h=r(42458),d=r(90242);function m(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n{const n=t.getSystem().specSelectors.specJson();return(0,f.isOAS3)(n)?e(...r):null}}}const g=m(((e,t)=>{const r=t?[t,"selectedServer"]:["selectedServer"];return e.getIn(r)||""})),v=m(((e,t,r)=>e.getIn(["requestData",t,r,"bodyValue"])||null)),y=m(((e,t,r)=>e.getIn(["requestData",t,r,"retainBodyValue"])||!1)),b=(e,t,r)=>e=>{const{oas3Selectors:n,specSelectors:o}=e.getSystem(),a=o.specJson();if((0,f.isOAS3)(a)){const e=n.requestContentType(t,r);if(e)return(0,h.getDefaultRequestBodyValue)(o.specResolvedSubtree(["paths",t,r,"requestBody"]),e,n.activeExamplesMember(t,r,"requestBody","requestBody"))}return null},w=(e,t,r)=>e=>{const{oas3Selectors:n,specSelectors:o}=e.getSystem(),a=o.specJson();if((0,f.isOAS3)(a)){let e=!1;const a=n.requestContentType(t,r);let i=n.requestBodyValue(t,r);if(p.Map.isMap(i)&&(i=(0,d.Pz)(i.mapEntries((e=>p.Map.isMap(e[1])?[e[0],e[1].get("value")]:e)).toJS())),p.List.isList(i)&&(i=(0,d.Pz)(i)),a){const s=(0,h.getDefaultRequestBodyValue)(o.specResolvedSubtree(["paths",t,r,"requestBody"]),a,n.activeExamplesMember(t,r,"requestBody","requestBody"));e=!!i&&i!==s}return e}return null},E=m(((e,t,r)=>e.getIn(["requestData",t,r,"bodyInclusion"])||(0,p.Map)())),x=m(((e,t,r)=>e.getIn(["requestData",t,r,"errors"])||null)),_=m(((e,t,r,n,o)=>e.getIn(["examples",t,r,n,o,"activeExample"])||null)),S=m(((e,t,r)=>e.getIn(["requestData",t,r,"requestContentType"])||null)),A=m(((e,t,r)=>e.getIn(["requestData",t,r,"responseContentType"])||null)),k=m(((e,t,r)=>{let n;if("string"!=typeof t){const{server:e,namespace:o}=t;n=o?[o,"serverVariableValues",e,r]:["serverVariableValues",e,r]}else{n=["serverVariableValues",t,r]}return e.getIn(n)||null})),C=m(((e,t)=>{let r;if("string"!=typeof t){const{server:e,namespace:n}=t;r=n?[n,"serverVariableValues",e]:["serverVariableValues",e]}else{r=["serverVariableValues",t]}return e.getIn(r)||(0,p.OrderedMap)()})),O=m(((e,t)=>{var r,n;if("string"!=typeof t){const{server:o,namespace:a}=t;n=o,r=a?e.getIn([a,"serverVariableValues",n]):e.getIn(["serverVariableValues",n])}else n=t,r=e.getIn(["serverVariableValues",n]);r=r||(0,p.OrderedMap)();let a=n;return o()(r).call(r,((e,t)=>{a=a.replace(new RegExp(`{${t}}`,"g"),e)})),a})),j=(I=(e,t)=>((e,t)=>(t=t||[],!!e.getIn(["requestData",...t,"bodyValue"])))(e,t),function(){for(var e=arguments.length,t=new Array(e),r=0;r{const r=e.getSystem().specSelectors.specJson();let n=[...t][1]||[];return!r.getIn(["paths",...n,"requestBody","required"])||I(...t)}});var I;const N=(e,t)=>{var r;let{oas3RequiredRequestBodyContentType:n,oas3RequestContentType:o,oas3RequestBodyValue:a}=t,s=[];if(!p.Map.isMap(a))return s;let u=[];return i()(r=l()(n.requestContentType)).call(r,(e=>{if(e===o){let t=n.requestContentType[e];i()(t).call(t,(e=>{c()(u).call(u,e)<0&&u.push(e)}))}})),i()(u).call(u,(e=>{a.getIn([e,"value"])||s.push(e)})),s}},91741:(e,t,r)=>{"use strict";r.r(t),r.d(t,{servers:()=>u,isSwagger2:()=>p});var n=r(20573),o=r(43393),a=r(7779);const i=e=>e||(0,o.Map)(),s=(0,n.P1)(i,(e=>e.get("json",(0,o.Map)()))),l=(0,n.P1)(i,(e=>e.get("resolved",(0,o.Map)()))),u=(c=(0,n.P1)((e=>{let t=l(e);return t.count()<1&&(t=s(e)),t}),(e=>e.getIn(["servers"])||(0,o.Map)())),()=>function(e){const t=e.getSystem().specSelectors.specJson();if((0,a.isOAS3)(t)){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o()=>{const e=t.getSystem().specSelectors.specJson();return(0,a.isSwagger2)(e)}},92044:(e,t,r)=>{"use strict";r.r(t),r.d(t,{definitions:()=>h,hasHost:()=>d,securityDefinitions:()=>m,host:()=>g,basePath:()=>v,consumes:()=>y,produces:()=>b,schemes:()=>w,servers:()=>E,isOAS3:()=>x,isSwagger2:()=>_});var n=r(20573),o=r(33881),a=r(43393),i=r(7779);function s(e){return(t,r)=>function(){const n=r.getSystem().specSelectors.specJson();return(0,i.isOAS3)(n)?e(...arguments):t(...arguments)}}const l=e=>e||(0,a.Map)(),u=s((0,n.P1)((()=>null))),c=(0,n.P1)(l,(e=>e.get("json",(0,a.Map)()))),p=(0,n.P1)(l,(e=>e.get("resolved",(0,a.Map)()))),f=e=>{let t=p(e);return t.count()<1&&(t=c(e)),t},h=s((0,n.P1)(f,(e=>{const t=e.getIn(["components","schemas"]);return a.Map.isMap(t)?t:(0,a.Map)()}))),d=s((e=>f(e).hasIn(["servers",0]))),m=s((0,n.P1)(o.specJsonWithResolvedSubtrees,(e=>e.getIn(["components","securitySchemes"])||null))),g=u,v=u,y=u,b=u,w=u,E=s((0,n.P1)(f,(e=>e.getIn(["servers"])||(0,a.Map)()))),x=(e,t)=>()=>{const e=t.getSystem().specSelectors.specJson();return(0,i.isOAS3)(a.Map.isMap(e)?e:(0,a.Map)())},_=(e,t)=>()=>{const e=t.getSystem().specSelectors.specJson();return(0,i.isSwagger2)(a.Map.isMap(e)?e:(0,a.Map)())}},70356:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(67294);const o=(0,r(7779).OAS3ComponentWrapFactory)((e=>{let{Ori:t,...r}=e;const{schema:o,getComponent:a,errSelectors:i,authorized:s,onAuthChange:l,name:u}=r,c=a("HttpAuth");return"http"===o.get("type")?n.createElement(c,{key:u,schema:o,name:u,errSelectors:i,authorized:s,getComponent:a,onChange:l}):n.createElement(t,r)}))},37761:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u});var n=r(22460),o=r(70356),a=r(69487),i=r(50058),s=r(53499),l=r(90287);const u={Markdown:n.default,AuthItem:o.default,JsonSchema_string:l.default,VersionStamp:a.default,model:s.default,onlineValidatorBadge:i.default}},90287:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(67294);const o=(0,r(7779).OAS3ComponentWrapFactory)((e=>{let{Ori:t,...r}=e;const{schema:o,getComponent:a,errors:i,onChange:s}=r,l=o&&o.get?o.get("format"):null,u=o&&o.get?o.get("type"):null,c=a("Input");return u&&"string"===u&&l&&("binary"===l||"base64"===l)?n.createElement(c,{type:"file",className:i.length?"invalid":"",title:i.length?i:"",onChange:e=>{s(e.target.files[0])},disabled:t.isDisabled}):n.createElement(t,r)}))},22460:(e,t,r)=>{"use strict";r.r(t),r.d(t,{Markdown:()=>f,default:()=>h});var n=r(81607),o=r.n(n),a=r(67294),i=r(94184),s=r.n(i),l=r(89927),u=r(7779),c=r(86019);const p=new l._("commonmark");p.block.ruler.enable(["table"]),p.set({linkTarget:"_blank"});const f=e=>{let{source:t,className:r="",getConfigs:n}=e;if("string"!=typeof t)return null;if(t){const{useUnsafeMarkdown:e}=n(),i=p.render(t),l=(0,c.s)(i,{useUnsafeMarkdown:e});let u;return"string"==typeof l&&(u=o()(l).call(l)),a.createElement("div",{dangerouslySetInnerHTML:{__html:u},className:s()(r,"renderedMarkdown")})}return null};f.defaultProps={getConfigs:()=>({useUnsafeMarkdown:!1})};const h=(0,u.OAS3ComponentWrapFactory)(f)},53499:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u});var n=r(23101),o=r.n(n),a=r(67294),i=r(7779),s=r(53795);class l extends a.Component{render(){let{getConfigs:e,schema:t}=this.props,r=["model-box"],n=null;return!0===t.get("deprecated")&&(r.push("deprecated"),n=a.createElement("span",{className:"model-deprecated-warning"},"Deprecated:")),a.createElement("div",{className:r.join(" ")},n,a.createElement(s.Z,o()({},this.props,{getConfigs:e,depth:1,expandDepth:this.props.expandDepth||0})))}}const u=(0,i.OAS3ComponentWrapFactory)(l)},50058:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>a});var n=r(7779),o=r(5623);const a=(0,n.OAS3ComponentWrapFactory)(o.Z)},69487:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(67294);const o=(0,r(7779).OAS3ComponentWrapFactory)((e=>{const{Ori:t}=e;return n.createElement("span",null,n.createElement(t,e),n.createElement("small",{className:"version-stamp"},n.createElement("pre",{className:"version"},"OAS3")))}))},28560:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(87198),o=r.n(n);let a=!1;function i(){return{statePlugins:{spec:{wrapActions:{updateSpec:e=>function(){return a=!0,e(...arguments)},updateJsonSpec:(e,t)=>function(){const r=t.getConfigs().onComplete;return a&&"function"==typeof r&&(o()(r,0),a=!1),e(...arguments)}}}}}}},92135:(e,t,r)=>{"use strict";r.r(t),r.d(t,{requestSnippetGenerator_curl_powershell:()=>A,requestSnippetGenerator_curl_bash:()=>k,requestSnippetGenerator_curl_cmd:()=>C});var n=r(11882),o=r.n(n),a=r(81607),i=r.n(a),s=r(35627),l=r.n(s),u=r(97606),c=r.n(u),p=r(12196),f=r.n(p),h=r(74386),d=r.n(h),m=r(58118),g=r.n(m),v=r(27504),y=r(43393);const b=e=>{var t;const r="_**[]";return o()(e).call(e,r)<0?e:i()(t=e.split(r)[0]).call(t)},w=e=>"-d "===e||/^[_\/-]/g.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'",E=e=>"-d "===(e=e.replace(/\^/g,"^^").replace(/\\"/g,'\\\\"').replace(/"/g,'""').replace(/\n/g,"^\n"))?e.replace(/-d /g,"-d ^\n"):/^[_\/-]/g.test(e)?e:'"'+e+'"',x=e=>"-d "===e?e:/\n/.test(e)?'@"\n'+e.replace(/"/g,'\\"').replace(/`/g,"``").replace(/\$/,"`$")+'\n"@':/^[_\/-]/g.test(e)?e:"'"+e.replace(/"/g,'""').replace(/'/g,"''")+"'";function _(e){let t=[];for(let[r,n]of e.get("body").entrySeq()){let e=b(r);n instanceof v.Z.File?t.push(` "${e}": {\n "name": "${n.name}"${n.type?`,\n "type": "${n.type}"`:""}\n }`):t.push(` "${e}": ${l()(n,null,2).replace(/(\r\n|\r|\n)/g,"\n ")}`)}return`{\n${t.join(",\n")}\n}`}const S=function(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",o=!1,a="";const i=function(){for(var e=arguments.length,r=new Array(e),n=0;na+=` ${r}`,p=function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;return a+=f()(e=" ").call(e,t)};let h=e.get("headers");if(a+="curl"+n,e.has("curlOptions")&&i(...e.get("curlOptions")),i("-X",e.get("method")),u(),p(),s(`${e.get("url")}`),h&&h.size)for(let t of d()(m=e.get("headers")).call(m)){var m;u(),p();let[e,r]=t;s("-H",`${e}: ${r}`),o=o||/^content-type$/i.test(e)&&/^multipart\/form-data$/i.test(r)}const w=e.get("body");var E;if(w)if(o&&g()(E=["POST","PUT","PATCH"]).call(E,e.get("method")))for(let[e,t]of w.entrySeq()){let r=b(e);u(),p(),s("-F"),t instanceof v.Z.File?i(`${r}=@${t.name}${t.type?`;type=${t.type}`:""}`):i(`${r}=${t}`)}else if(w instanceof v.Z.File)u(),p(),s(`--data-binary '@${w.name}'`);else{u(),p(),s("-d ");let t=w;y.Map.isMap(t)?s(_(e)):("string"!=typeof t&&(t=l()(t)),s(t))}else w||"POST"!==e.get("method")||(u(),p(),s("-d ''"));return a},A=e=>S(e,x,"`\n",".exe"),k=e=>S(e,w,"\\\n"),C=e=>S(e,E,"^\n")},86575:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(92135),o=r(4669),a=r(84206);const i=()=>({components:{RequestSnippets:a.default},fn:n,statePlugins:{requestSnippets:{selectors:o}}})},84206:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>w});var n=r(14418),o=r.n(n),a=r(25110),i=r.n(a),s=r(86),l=r.n(s),u=r(97606),c=r.n(u),p=r(67294),f=r(27361),h=r.n(f),d=r(23560),m=r.n(d),g=r(74855),v=r(33424);const y={cursor:"pointer",lineHeight:1,display:"inline-flex",backgroundColor:"rgb(250, 250, 250)",paddingBottom:"0",paddingTop:"0",border:"1px solid rgb(51, 51, 51)",borderRadius:"4px 4px 0 0",boxShadow:"none",borderBottom:"none"},b={cursor:"pointer",lineHeight:1,display:"inline-flex",backgroundColor:"rgb(51, 51, 51)",boxShadow:"none",border:"1px solid rgb(51, 51, 51)",paddingBottom:"0",paddingTop:"0",borderRadius:"4px 4px 0 0",marginTop:"-5px",marginRight:"-5px",marginLeft:"-5px",zIndex:"9999",borderBottom:"none"},w=e=>{var t,r;let{request:n,requestSnippetsSelectors:a,getConfigs:s}=e;const u=m()(s)?s():null,f=!1!==h()(u,"syntaxHighlight")&&h()(u,"syntaxHighlight.activated",!0),d=(0,p.useRef)(null),[w,E]=(0,p.useState)(null===(t=a.getSnippetGenerators())||void 0===t?void 0:t.keySeq().first()),[x,_]=(0,p.useState)(null==a?void 0:a.getDefaultExpanded());(0,p.useEffect)((()=>{}),[]),(0,p.useEffect)((()=>{var e;const t=o()(e=i()(d.current.childNodes)).call(e,(e=>{var t;return!!e.nodeType&&(null===(t=e.classList)||void 0===t?void 0:t.contains("curl-command"))}));return l()(t).call(t,(e=>e.addEventListener("mousewheel",j,{passive:!1}))),()=>{l()(t).call(t,(e=>e.removeEventListener("mousewheel",j)))}}),[n]);const S=a.getSnippetGenerators(),A=S.get(w),k=A.get("fn")(n),C=()=>{_(!x)},O=e=>e===w?b:y,j=e=>{const{target:t,deltaY:r}=e,{scrollHeight:n,offsetHeight:o,scrollTop:a}=t;n>o&&(0===a&&r<0||o+a>=n&&r>0)&&e.preventDefault()},I=f?p.createElement(v.d3,{language:A.get("syntax"),className:"curl microlight",style:(0,v.C2)(h()(u,"syntaxHighlight.theme"))},k):p.createElement("textarea",{readOnly:!0,className:"curl",value:k});return p.createElement("div",{className:"request-snippets",ref:d},p.createElement("div",{style:{width:"100%",display:"flex",justifyContent:"flex-start",alignItems:"center",marginBottom:"15px"}},p.createElement("h4",{onClick:()=>C(),style:{cursor:"pointer"}},"Snippets"),p.createElement("button",{onClick:()=>C(),style:{border:"none",background:"none"},title:x?"Collapse operation":"Expand operation"},p.createElement("svg",{className:"arrow",width:"10",height:"10"},p.createElement("use",{href:x?"#large-arrow-down":"#large-arrow",xlinkHref:x?"#large-arrow-down":"#large-arrow"})))),x&&p.createElement("div",{className:"curl-command"},p.createElement("div",{style:{paddingLeft:"15px",paddingRight:"10px",width:"100%",display:"flex"}},c()(r=S.entrySeq()).call(r,(e=>{let[t,r]=e;return p.createElement("div",{style:O(t),className:"btn",key:t,onClick:()=>(e=>{w!==e&&E(e)})(t)},p.createElement("h4",{style:t===w?{color:"white"}:{}},r.get("title")))}))),p.createElement("div",{className:"copy-to-clipboard"},p.createElement(g.CopyToClipboard,{text:k},p.createElement("button",null))),p.createElement("div",null,I)))}},4669:(e,t,r)=>{"use strict";r.r(t),r.d(t,{getGenerators:()=>f,getSnippetGenerators:()=>h,getActiveLanguage:()=>d,getDefaultExpanded:()=>m});var n=r(14418),o=r.n(n),a=r(58118),i=r.n(a),s=r(97606),l=r.n(s),u=r(20573),c=r(43393);const p=e=>e||(0,c.Map)(),f=(0,u.P1)(p,(e=>{const t=e.get("languages"),r=e.get("generators",(0,c.Map)());return!t||t.isEmpty()?r:o()(r).call(r,((e,r)=>i()(t).call(t,r)))})),h=e=>t=>{var r,n;let{fn:a}=t;return o()(r=l()(n=f(e)).call(n,((e,t)=>{const r=(e=>a[`requestSnippetGenerator_${e}`])(t);return"function"!=typeof r?null:e.set("fn",r)}))).call(r,(e=>e))},d=(0,u.P1)(p,(e=>e.get("activeLanguage"))),m=(0,u.P1)(p,(e=>e.get("defaultExpanded")))},36195:(e,t,r)=>{"use strict";r.r(t),r.d(t,{ErrorBoundary:()=>i,default:()=>s});var n=r(67294),o=r(56189),a=r(29403);class i extends n.Component{static getDerivedStateFromError(e){return{hasError:!0,error:e}}constructor(){super(...arguments),this.state={hasError:!1,error:null}}componentDidCatch(e,t){this.props.fn.componentDidCatch(e,t)}render(){const{getComponent:e,targetName:t,children:r}=this.props;if(this.state.hasError){const r=e("Fallback");return n.createElement(r,{name:t})}return r}}i.defaultProps={targetName:"this component",getComponent:()=>a.default,fn:{componentDidCatch:o.componentDidCatch},children:null};const s=i},29403:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(67294);const o=e=>{let{name:t}=e;return n.createElement("div",{className:"fallback"},"😱 ",n.createElement("i",null,"Could not render ","t"===t?"this component":t,", see the console."))}},56189:(e,t,r)=>{"use strict";r.r(t),r.d(t,{componentDidCatch:()=>i,withErrorBoundary:()=>s});var n=r(23101),o=r.n(n),a=r(67294);const i=console.error,s=e=>t=>{const{getComponent:r,fn:n}=e(),i=r("ErrorBoundary"),s=n.getDisplayName(t);class l extends a.Component{render(){return a.createElement(i,{targetName:s,getComponent:r,fn:n},a.createElement(t,o()({},this.props,this.context)))}}var u;return l.displayName=`WithErrorBoundary(${s})`,(u=t).prototype&&u.prototype.isReactComponent&&(l.prototype.mapStateToProps=t.prototype.mapStateToProps),l}},27621:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>c});var n=r(47475),o=r.n(n),a=r(7287),i=r.n(a),s=r(36195),l=r(29403),u=r(56189);const c=function(){let{componentList:e=[],fullOverride:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return r=>{var n;let{getSystem:a}=r;const c=t?e:["App","BaseLayout","VersionPragmaFilter","InfoContainer","ServersContainer","SchemesContainer","AuthorizeBtnContainer","FilterContainer","Operations","OperationContainer","parameters","responses","OperationServers","Models","ModelWrapper",...e],p=i()(c,o()(n=Array(c.length)).call(n,((e,t)=>{let{fn:r}=t;return r.withErrorBoundary(e)})));return{fn:{componentDidCatch:u.componentDidCatch,withErrorBoundary:(0,u.withErrorBoundary)(a)},components:{ErrorBoundary:s.default,Fallback:l.default},wrapComponents:p}}}},57050:(e,t,r)=>{"use strict";r.r(t),r.d(t,{sampleFromSchemaGeneric:()=>F,inferSchema:()=>z,createXMLExample:()=>U,sampleFromSchema:()=>q,memoizedCreateXMLExample:()=>$,memoizedSampleFromSchema:()=>W});var n=r(11882),o=r.n(n),a=r(86),i=r.n(a),s=r(58309),l=r.n(s),u=r(58118),c=r.n(u),p=r(92039),f=r.n(p),h=r(24278),d=r.n(h),m=r(51679),g=r.n(m),v=r(39022),y=r.n(v),b=r(97606),w=r.n(b),E=r(35627),x=r.n(E),_=r(53479),S=r.n(_),A=r(14419),k=r.n(A),C=r(41609),O=r.n(C),j=r(90242),I=r(60314);const N={string:e=>e.pattern?(e=>{try{return new(k())(e).gen()}catch(e){return"string"}})(e.pattern):"string",string_email:()=>"user@example.com","string_date-time":()=>(new Date).toISOString(),string_date:()=>(new Date).toISOString().substring(0,10),string_uuid:()=>"3fa85f64-5717-4562-b3fc-2c963f66afa6",string_hostname:()=>"example.com",string_ipv4:()=>"198.51.100.42",string_ipv6:()=>"2001:0db8:5b96:0000:0000:426f:8e17:642a",number:()=>0,number_float:()=>0,integer:()=>0,boolean:e=>"boolean"!=typeof e.default||e.default},T=e=>{e=(0,j.mz)(e);let{type:t,format:r}=e,n=N[`${t}_${r}`]||N[t];return(0,j.Wl)(n)?n(e):"Unknown Type: "+e.type},P=e=>(0,j.XV)(e,"$$ref",(e=>"string"==typeof e&&o()(e).call(e,"#")>-1)),R=["maxProperties","minProperties"],M=["minItems","maxItems"],D=["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],L=["minLength","maxLength"],B=function(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=r=>{void 0===t[r]&&void 0!==e[r]&&(t[r]=e[r])};var s;(i()(r=["example","default","enum","xml","type",...R,...M,...D,...L]).call(r,(e=>a(e))),void 0!==e.required&&l()(e.required))&&(void 0!==t.required&&t.required.length||(t.required=[]),i()(s=e.required).call(s,(e=>{var r;c()(r=t.required).call(r,e)||t.required.push(e)})));if(e.properties){t.properties||(t.properties={});let r=(0,j.mz)(e.properties);for(let a in r){var u;if(Object.prototype.hasOwnProperty.call(r,a))if(!r[a]||!r[a].deprecated)if(!r[a]||!r[a].readOnly||n.includeReadOnly)if(!r[a]||!r[a].writeOnly||n.includeWriteOnly)if(!t.properties[a])t.properties[a]=r[a],!e.required&&l()(e.required)&&-1!==o()(u=e.required).call(u,a)&&(t.required?t.required.push(a):t.required=[a])}}return e.items&&(t.items||(t.items={}),t.items=B(e.items,t.items,n)),t},F=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];e&&(0,j.Wl)(e.toJS)&&(e=e.toJS());let a=void 0!==r||e&&void 0!==e.example||e&&void 0!==e.default;const s=!a&&e&&e.oneOf&&e.oneOf.length>0,u=!a&&e&&e.anyOf&&e.anyOf.length>0;if(!a&&(s||u)){const r=(0,j.mz)(s?e.oneOf[0]:e.anyOf[0]);if(B(r,e,t),!e.xml&&r.xml&&(e.xml=r.xml),void 0!==e.example&&void 0!==r.example)a=!0;else if(r.properties){e.properties||(e.properties={});let n=(0,j.mz)(r.properties);for(let a in n){var p;if(Object.prototype.hasOwnProperty.call(n,a))if(!n[a]||!n[a].deprecated)if(!n[a]||!n[a].readOnly||t.includeReadOnly)if(!n[a]||!n[a].writeOnly||t.includeWriteOnly)if(!e.properties[a])e.properties[a]=n[a],!r.required&&l()(r.required)&&-1!==o()(p=r.required).call(p,a)&&(e.required?e.required.push(a):e.required=[a])}}}const h={};let{xml:m,type:v,example:b,properties:E,additionalProperties:x,items:_}=e||{},{includeReadOnly:S,includeWriteOnly:A}=t;m=m||{};let k,{name:C,prefix:I,namespace:N}=m,L={};if(n&&(C=C||"notagname",k=(I?I+":":"")+C,N)){h[I?"xmlns:"+I:"xmlns"]=N}n&&(L[k]=[]);const z=t=>f()(t).call(t,(t=>Object.prototype.hasOwnProperty.call(e,t)));e&&!v&&(E||x||z(R)?v="object":_||z(M)?v="array":z(D)?(v="number",e.type="number"):a||e.enum||(v="string",e.type="string"));const U=t=>{var r,n,o,a,i;null!==(null===(r=e)||void 0===r?void 0:r.maxItems)&&void 0!==(null===(n=e)||void 0===n?void 0:n.maxItems)&&(t=d()(t).call(t,0,null===(i=e)||void 0===i?void 0:i.maxItems));if(null!==(null===(o=e)||void 0===o?void 0:o.minItems)&&void 0!==(null===(a=e)||void 0===a?void 0:a.minItems)){let r=0;for(;t.length<(null===(s=e)||void 0===s?void 0:s.minItems);){var s;t.push(t[r++%t.length])}}return t},q=(0,j.mz)(E);let V,$=0;const W=()=>e&&null!==e.maxProperties&&void 0!==e.maxProperties&&$>=e.maxProperties,H=()=>{if(!e||!e.required)return 0;let t=0;var r,o;n?i()(r=e.required).call(r,(e=>t+=void 0===L[e]?0:1)):i()(o=e.required).call(o,(e=>{var r;return t+=void 0===(null===(r=L[k])||void 0===r?void 0:g()(r).call(r,(t=>void 0!==t[e])))?0:1}));return e.required.length-t},J=t=>{var r;return!(e&&e.required&&e.required.length)||!c()(r=e.required).call(r,t)},K=t=>!e||null===e.maxProperties||void 0===e.maxProperties||!W()&&(!J(t)||e.maxProperties-$-H()>0);if(V=n?function(r){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;if(e&&q[r]){if(q[r].xml=q[r].xml||{},q[r].xml.attribute){const e=l()(q[r].enum)?q[r].enum[0]:void 0,t=q[r].example,n=q[r].default;return void(h[q[r].xml.name||r]=void 0!==t?t:void 0!==n?n:void 0!==e?e:T(q[r]))}q[r].xml.name=q[r].xml.name||r}else q[r]||!1===x||(q[r]={xml:{name:r}});let a=F(e&&q[r]||void 0,t,o,n);var i;K(r)&&($++,l()(a)?L[k]=y()(i=L[k]).call(i,a):L[k].push(a))}:(r,o)=>{if(K(r)){if(Object.prototype.hasOwnProperty.call(e,"discriminator")&&e.discriminator&&Object.prototype.hasOwnProperty.call(e.discriminator,"mapping")&&e.discriminator.mapping&&Object.prototype.hasOwnProperty.call(e,"$$ref")&&e.$$ref&&e.discriminator.propertyName===r){for(let t in e.discriminator.mapping)if(-1!==e.$$ref.search(e.discriminator.mapping[t])){L[r]=t;break}}else L[r]=F(q[r],t,o,n);$++}},a){let o;if(o=P(void 0!==r?r:void 0!==b?b:e.default),!n){if("number"==typeof o&&"string"===v)return`${o}`;if("string"!=typeof o||"string"===v)return o;try{return JSON.parse(o)}catch(e){return o}}if(e||(v=l()(o)?"array":typeof o),"array"===v){if(!l()(o)){if("string"==typeof o)return o;o=[o]}const r=e?e.items:void 0;r&&(r.xml=r.xml||m||{},r.xml.name=r.xml.name||m.name);let a=w()(o).call(o,(e=>F(r,t,e,n)));return a=U(a),m.wrapped?(L[k]=a,O()(h)||L[k].push({_attr:h})):L=a,L}if("object"===v){if("string"==typeof o)return o;for(let t in o)Object.prototype.hasOwnProperty.call(o,t)&&(e&&q[t]&&q[t].readOnly&&!S||e&&q[t]&&q[t].writeOnly&&!A||(e&&q[t]&&q[t].xml&&q[t].xml.attribute?h[q[t].xml.name||t]=o[t]:V(t,o[t])));return O()(h)||L[k].push({_attr:h}),L}return L[k]=O()(h)?o:[{_attr:h},o],L}if("object"===v){for(let e in q)Object.prototype.hasOwnProperty.call(q,e)&&(q[e]&&q[e].deprecated||q[e]&&q[e].readOnly&&!S||q[e]&&q[e].writeOnly&&!A||V(e));if(n&&h&&L[k].push({_attr:h}),W())return L;if(!0===x)n?L[k].push({additionalProp:"Anything can be here"}):L.additionalProp1={},$++;else if(x){const r=(0,j.mz)(x),o=F(r,t,void 0,n);if(n&&r.xml&&r.xml.name&&"notagname"!==r.xml.name)L[k].push(o);else{const t=null!==e.minProperties&&void 0!==e.minProperties&&$F(B(_,e,t),t,void 0,n)));else if(l()(_.oneOf)){var Y;r=w()(Y=_.oneOf).call(Y,(e=>F(B(_,e,t),t,void 0,n)))}else{if(!(!n||n&&m.wrapped))return F(_,t,void 0,n);r=[F(_,t,void 0,n)]}return r=U(r),n&&m.wrapped?(L[k]=r,O()(h)||L[k].push({_attr:h}),L):r}let Q;if(e&&l()(e.enum))Q=(0,j.AF)(e.enum)[0];else{if(!e)return;if(Q=T(e),"number"==typeof Q){let t=e.minimum;null!=t&&(e.exclusiveMinimum&&t++,Q=t);let r=e.maximum;null!=r&&(e.exclusiveMaximum&&r--,Q=r)}if("string"==typeof Q&&(null!==e.maxLength&&void 0!==e.maxLength&&(Q=d()(Q).call(Q,0,e.maxLength)),null!==e.minLength&&void 0!==e.minLength)){let t=0;for(;Q.length(e.schema&&(e=e.schema),e.properties&&(e.type="object"),e),U=(e,t,r)=>{const n=F(e,t,r,!0);if(n)return"string"==typeof n?n:S()(n,{declaration:!0,indent:"\t"})},q=(e,t,r)=>F(e,t,r,!1),V=(e,t,r)=>[e,x()(t),x()(r)],$=(0,I.Z)(U,V),W=(0,I.Z)(q,V)},8883:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(57050);function o(){return{fn:n}}},51228:(e,t,r)=>{"use strict";r.r(t),r.d(t,{UPDATE_SPEC:()=>U,UPDATE_URL:()=>q,UPDATE_JSON:()=>V,UPDATE_PARAM:()=>$,UPDATE_EMPTY_PARAM_INCLUSION:()=>W,VALIDATE_PARAMS:()=>H,SET_RESPONSE:()=>J,SET_REQUEST:()=>K,SET_MUTATED_REQUEST:()=>G,LOG_REQUEST:()=>Z,CLEAR_RESPONSE:()=>Y,CLEAR_REQUEST:()=>Q,CLEAR_VALIDATE_PARAMS:()=>X,UPDATE_OPERATION_META_VALUE:()=>ee,UPDATE_RESOLVED:()=>te,UPDATE_RESOLVED_SUBTREE:()=>re,SET_SCHEME:()=>ne,updateSpec:()=>oe,updateResolved:()=>ae,updateUrl:()=>ie,updateJsonSpec:()=>se,parseToJson:()=>le,resolveSpec:()=>ce,requestResolvedSubtree:()=>he,changeParam:()=>de,changeParamByIdentity:()=>me,updateResolvedSubtree:()=>ge,invalidateResolvedSubtreeCache:()=>ve,validateParams:()=>ye,updateEmptyParamInclusion:()=>be,clearValidateParams:()=>we,changeConsumesValue:()=>Ee,changeProducesValue:()=>xe,setResponse:()=>_e,setRequest:()=>Se,setMutatedRequest:()=>Ae,logRequest:()=>ke,executeRequest:()=>Ce,execute:()=>Oe,clearResponse:()=>je,clearRequest:()=>Ie,setScheme:()=>Ne});var n=r(58309),o=r.n(n),a=r(97606),i=r.n(a),s=r(96718),l=r.n(s),u=r(24282),c=r.n(u),p=r(2250),f=r.n(p),h=r(6226),d=r.n(h),m=r(14418),g=r.n(m),v=r(3665),y=r.n(v),b=r(11882),w=r.n(b),E=r(86),x=r.n(E),_=r(28222),S=r.n(_),A=r(76986),k=r.n(A),C=r(70586),O=r.n(C),j=r(1272),I=r(43393),N=r(84564),T=r.n(N),P=r(7710),R=r(47037),M=r.n(R),D=r(23279),L=r.n(D),B=r(36968),F=r.n(B),z=r(90242);const U="spec_update_spec",q="spec_update_url",V="spec_update_json",$="spec_update_param",W="spec_update_empty_param_inclusion",H="spec_validate_param",J="spec_set_response",K="spec_set_request",G="spec_set_mutated_request",Z="spec_log_request",Y="spec_clear_response",Q="spec_clear_request",X="spec_clear_validate_param",ee="spec_update_operation_meta_value",te="spec_update_resolved",re="spec_update_resolved_subtree",ne="set_scheme";function oe(e){const t=(r=e,M()(r)?r:"").replace(/\t/g," ");var r;if("string"==typeof e)return{type:U,payload:t}}function ae(e){return{type:te,payload:e}}function ie(e){return{type:q,payload:e}}function se(e){return{type:V,payload:e}}const le=e=>t=>{let{specActions:r,specSelectors:n,errActions:o}=t,{specStr:a}=n,i=null;try{e=e||a(),o.clear({source:"parser"}),i=j.ZP.load(e,{schema:j.A8})}catch(e){return console.error(e),o.newSpecErr({source:"parser",level:"error",message:e.reason,line:e.mark&&e.mark.line?e.mark.line+1:void 0})}return i&&"object"==typeof i?r.updateJsonSpec(i):{}};let ue=!1;const ce=(e,t)=>r=>{let{specActions:n,specSelectors:a,errActions:s,fn:{fetch:u,resolve:c,AST:p={}},getConfigs:f}=r;ue||(console.warn("specActions.resolveSpec is deprecated since v3.10.0 and will be removed in v4.0.0; use requestResolvedSubtree instead!"),ue=!0);const{modelPropertyMacro:h,parameterMacro:d,requestInterceptor:m,responseInterceptor:g}=f();void 0===e&&(e=a.specJson()),void 0===t&&(t=a.url());let v=p.getLineNumberForPath?p.getLineNumberForPath:()=>{},y=a.specStr();return c({fetch:u,spec:e,baseDoc:t,modelPropertyMacro:h,parameterMacro:d,requestInterceptor:m,responseInterceptor:g}).then((e=>{let{spec:t,errors:r}=e;if(s.clear({type:"thrown"}),o()(r)&&r.length>0){let e=i()(r).call(r,(e=>(console.error(e),e.line=e.fullPath?v(y,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",l()(e,"message",{enumerable:!0,value:e.message}),e)));s.newThrownErrBatch(e)}return n.updateResolved(t)}))};let pe=[];const fe=L()((async()=>{const e=pe.system;if(!e)return void console.error("debResolveSubtrees: don't have a system to operate on, aborting.");const{errActions:t,errSelectors:r,fn:{resolveSubtree:n,fetch:a,AST:s={}},specSelectors:u,specActions:p}=e;if(!n)return void console.error("Error: Swagger-Client did not provide a `resolveSubtree` method, doing nothing.");let h=s.getLineNumberForPath?s.getLineNumberForPath:()=>{};const m=u.specStr(),{modelPropertyMacro:v,parameterMacro:b,requestInterceptor:w,responseInterceptor:E}=e.getConfigs();try{var x=await c()(pe).call(pe,(async(e,s)=>{const{resultMap:c,specWithCurrentSubtrees:p}=await e,{errors:x,spec:_}=await n(p,s,{baseDoc:u.url(),modelPropertyMacro:v,parameterMacro:b,requestInterceptor:w,responseInterceptor:E});if(r.allErrors().size&&t.clearBy((e=>{var t;return"thrown"!==e.get("type")||"resolver"!==e.get("source")||!f()(t=e.get("fullPath")).call(t,((e,t)=>e===s[t]||void 0===s[t]))})),o()(x)&&x.length>0){let e=i()(x).call(x,(e=>(e.line=e.fullPath?h(m,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",l()(e,"message",{enumerable:!0,value:e.message}),e)));t.newThrownErrBatch(e)}var S,A;_&&u.isOAS3()&&"components"===s[0]&&"securitySchemes"===s[1]&&await d().all(i()(S=g()(A=y()(_)).call(A,(e=>"openIdConnect"===e.type))).call(S,(async e=>{const t={url:e.openIdConnectUrl,requestInterceptor:w,responseInterceptor:E};try{const r=await a(t);r instanceof Error||r.status>=400?console.error(r.statusText+" "+t.url):e.openIdConnectData=JSON.parse(r.text)}catch(e){console.error(e)}})));return F()(c,s,_),F()(p,s,_),{resultMap:c,specWithCurrentSubtrees:p}}),d().resolve({resultMap:(u.specResolvedSubtree([])||(0,I.Map)()).toJS(),specWithCurrentSubtrees:u.specJson().toJS()}));delete pe.system,pe=[]}catch(e){console.error(e)}p.updateResolvedSubtree([],x.resultMap)}),35),he=e=>t=>{var r;w()(r=i()(pe).call(pe,(e=>e.join("@@")))).call(r,e.join("@@"))>-1||(pe.push(e),pe.system=t,fe())};function de(e,t,r,n,o){return{type:$,payload:{path:e,value:n,paramName:t,paramIn:r,isXml:o}}}function me(e,t,r,n){return{type:$,payload:{path:e,param:t,value:r,isXml:n}}}const ge=(e,t)=>({type:re,payload:{path:e,value:t}}),ve=()=>({type:re,payload:{path:[],value:(0,I.Map)()}}),ye=(e,t)=>({type:H,payload:{pathMethod:e,isOAS3:t}}),be=(e,t,r,n)=>({type:W,payload:{pathMethod:e,paramName:t,paramIn:r,includeEmptyValue:n}});function we(e){return{type:X,payload:{pathMethod:e}}}function Ee(e,t){return{type:ee,payload:{path:e,value:t,key:"consumes_value"}}}function xe(e,t){return{type:ee,payload:{path:e,value:t,key:"produces_value"}}}const _e=(e,t,r)=>({payload:{path:e,method:t,res:r},type:J}),Se=(e,t,r)=>({payload:{path:e,method:t,req:r},type:K}),Ae=(e,t,r)=>({payload:{path:e,method:t,req:r},type:G}),ke=e=>({payload:e,type:Z}),Ce=e=>t=>{let{fn:r,specActions:n,specSelectors:a,getConfigs:s,oas3Selectors:l}=t,{pathName:u,method:c,operation:p}=e,{requestInterceptor:f,responseInterceptor:h}=s(),d=p.toJS();var m,v;p&&p.get("parameters")&&x()(m=g()(v=p.get("parameters")).call(v,(e=>e&&!0===e.get("allowEmptyValue")))).call(m,(t=>{if(a.parameterInclusionSettingFor([u,c],t.get("name"),t.get("in"))){e.parameters=e.parameters||{};const r=(0,z.cz)(t,e.parameters);(!r||r&&0===r.size)&&(e.parameters[t.get("name")]="")}}));if(e.contextUrl=T()(a.url()).toString(),d&&d.operationId?e.operationId=d.operationId:d&&u&&c&&(e.operationId=r.opId(d,u,c)),a.isOAS3()){const t=`${u}:${c}`;e.server=l.selectedServer(t)||l.selectedServer();const r=l.serverVariables({server:e.server,namespace:t}).toJS(),n=l.serverVariables({server:e.server}).toJS();e.serverVariables=S()(r).length?r:n,e.requestContentType=l.requestContentType(u,c),e.responseContentType=l.responseContentType(u,c)||"*/*";const a=l.requestBodyValue(u,c),s=l.requestBodyInclusionSetting(u,c);var y;if(a&&a.toJS)e.requestBody=g()(y=i()(a).call(a,(e=>I.Map.isMap(e)?e.get("value"):e))).call(y,((e,t)=>(o()(e)?0!==e.length:!(0,z.O2)(e))||s.get(t))).toJS();else e.requestBody=a}let b=k()({},e);b=r.buildRequest(b),n.setRequest(e.pathName,e.method,b);e.requestInterceptor=async t=>{let r=await f.apply(void 0,[t]),o=k()({},r);return n.setMutatedRequest(e.pathName,e.method,o),r},e.responseInterceptor=h;const w=O()();return r.execute(e).then((t=>{t.duration=O()()-w,n.setResponse(e.pathName,e.method,t)})).catch((t=>{"Failed to fetch"===t.message&&(t.name="",t.message='**Failed to fetch.** \n**Possible Reasons:** \n - CORS \n - Network Failure \n - URL scheme must be "http" or "https" for CORS request.'),n.setResponse(e.pathName,e.method,{error:!0,err:(0,P.serializeError)(t)})}))},Oe=function(){let{path:e,method:t,...r}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return n=>{let{fn:{fetch:o},specSelectors:a,specActions:i}=n,s=a.specJsonWithResolvedSubtrees().toJS(),l=a.operationScheme(e,t),{requestContentType:u,responseContentType:c}=a.contentTypeValues([e,t]).toJS(),p=/xml/i.test(u),f=a.parameterValues([e,t],p).toJS();return i.executeRequest({...r,fetch:o,spec:s,pathName:e,method:t,parameters:f,requestContentType:u,scheme:l,responseContentType:c})}};function je(e,t){return{type:Y,payload:{path:e,method:t}}}function Ie(e,t){return{type:Q,payload:{path:e,method:t}}}function Ne(e,t,r){return{type:ne,payload:{scheme:e,path:t,method:r}}}},37038:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>s});var n=r(20032),o=r(51228),a=r(33881),i=r(77508);function s(){return{statePlugins:{spec:{wrapActions:i,reducers:n.default,actions:o,selectors:a}}}}},20032:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>d});var n=r(24282),o=r.n(n),a=r(97606),i=r.n(a),s=r(76986),l=r.n(s),u=r(43393),c=r(90242),p=r(27504),f=r(33881),h=r(51228);const d={[h.UPDATE_SPEC]:(e,t)=>"string"==typeof t.payload?e.set("spec",t.payload):e,[h.UPDATE_URL]:(e,t)=>e.set("url",t.payload+""),[h.UPDATE_JSON]:(e,t)=>e.set("json",(0,c.oG)(t.payload)),[h.UPDATE_RESOLVED]:(e,t)=>e.setIn(["resolved"],(0,c.oG)(t.payload)),[h.UPDATE_RESOLVED_SUBTREE]:(e,t)=>{const{value:r,path:n}=t.payload;return e.setIn(["resolvedSubtrees",...n],(0,c.oG)(r))},[h.UPDATE_PARAM]:(e,t)=>{let{payload:r}=t,{path:n,paramName:o,paramIn:a,param:i,value:s,isXml:l}=r,u=i?(0,c.V9)(i):`${a}.${o}`;const p=l?"value_xml":"value";return e.setIn(["meta","paths",...n,"parameters",u,p],s)},[h.UPDATE_EMPTY_PARAM_INCLUSION]:(e,t)=>{let{payload:r}=t,{pathMethod:n,paramName:o,paramIn:a,includeEmptyValue:i}=r;if(!o||!a)return console.warn("Warning: UPDATE_EMPTY_PARAM_INCLUSION could not generate a paramKey."),e;const s=`${a}.${o}`;return e.setIn(["meta","paths",...n,"parameter_inclusions",s],i)},[h.VALIDATE_PARAMS]:(e,t)=>{let{payload:{pathMethod:r,isOAS3:n}}=t;const a=(0,f.specJsonWithResolvedSubtrees)(e).getIn(["paths",...r]),i=(0,f.parameterValues)(e,r).toJS();return e.updateIn(["meta","paths",...r,"parameters"],(0,u.fromJS)({}),(t=>{var s;return o()(s=a.get("parameters",(0,u.List)())).call(s,((t,o)=>{const a=(0,c.cz)(o,i),s=(0,f.parameterInclusionSettingFor)(e,r,o.get("name"),o.get("in")),l=(0,c.Ik)(o,a,{bypassRequiredCheck:s,isOAS3:n});return t.setIn([(0,c.V9)(o),"errors"],(0,u.fromJS)(l))}),t)}))},[h.CLEAR_VALIDATE_PARAMS]:(e,t)=>{let{payload:{pathMethod:r}}=t;return e.updateIn(["meta","paths",...r,"parameters"],(0,u.fromJS)([]),(e=>i()(e).call(e,(e=>e.set("errors",(0,u.fromJS)([]))))))},[h.SET_RESPONSE]:(e,t)=>{let r,{payload:{res:n,path:o,method:a}}=t;r=n.error?l()({error:!0,name:n.err.name,message:n.err.message,statusCode:n.err.statusCode},n.err.response):n,r.headers=r.headers||{};let i=e.setIn(["responses",o,a],(0,c.oG)(r));return p.Z.Blob&&n.data instanceof p.Z.Blob&&(i=i.setIn(["responses",o,a,"text"],n.data)),i},[h.SET_REQUEST]:(e,t)=>{let{payload:{req:r,path:n,method:o}}=t;return e.setIn(["requests",n,o],(0,c.oG)(r))},[h.SET_MUTATED_REQUEST]:(e,t)=>{let{payload:{req:r,path:n,method:o}}=t;return e.setIn(["mutatedRequests",n,o],(0,c.oG)(r))},[h.UPDATE_OPERATION_META_VALUE]:(e,t)=>{let{payload:{path:r,value:n,key:o}}=t,a=["paths",...r],i=["meta","paths",...r];return e.getIn(["json",...a])||e.getIn(["resolved",...a])||e.getIn(["resolvedSubtrees",...a])?e.setIn([...i,o],(0,u.fromJS)(n)):e},[h.CLEAR_RESPONSE]:(e,t)=>{let{payload:{path:r,method:n}}=t;return e.deleteIn(["responses",r,n])},[h.CLEAR_REQUEST]:(e,t)=>{let{payload:{path:r,method:n}}=t;return e.deleteIn(["requests",r,n])},[h.SET_SCHEME]:(e,t)=>{let{payload:{scheme:r,path:n,method:o}}=t;return n&&o?e.setIn(["scheme",n,o],r):n||o?void 0:e.setIn(["scheme","_defaultScheme"],r)}}},33881:(e,t,r)=>{"use strict";r.r(t),r.d(t,{lastError:()=>O,url:()=>j,specStr:()=>I,specSource:()=>N,specJson:()=>T,specResolved:()=>P,specResolvedSubtree:()=>R,specJsonWithResolvedSubtrees:()=>D,spec:()=>L,isOAS3:()=>B,info:()=>F,externalDocs:()=>z,version:()=>U,semver:()=>q,paths:()=>V,operations:()=>$,consumes:()=>W,produces:()=>H,security:()=>J,securityDefinitions:()=>K,findDefinition:()=>G,definitions:()=>Z,basePath:()=>Y,host:()=>Q,schemes:()=>X,operationsWithRootInherited:()=>ee,tags:()=>te,tagDetails:()=>re,operationsWithTags:()=>ne,taggedOperations:()=>oe,responses:()=>ae,requests:()=>ie,mutatedRequests:()=>se,responseFor:()=>le,requestFor:()=>ue,mutatedRequestFor:()=>ce,allowTryItOutFor:()=>pe,parameterWithMetaByIdentity:()=>fe,parameterInclusionSettingFor:()=>he,parameterWithMeta:()=>de,operationWithMeta:()=>me,getParameter:()=>ge,hasHost:()=>ve,parameterValues:()=>ye,parametersIncludeIn:()=>be,parametersIncludeType:()=>we,contentTypeValues:()=>Ee,currentProducesFor:()=>xe,producesOptionsFor:()=>_e,consumesOptionsFor:()=>Se,operationScheme:()=>Ae,canExecuteScheme:()=>ke,validationErrors:()=>Ce,validateBeforeExecute:()=>Oe,getOAS3RequiredRequestBodyContentType:()=>je,isMediaTypeSchemaPropertiesEqual:()=>Ie});var n=r(24278),o=r.n(n),a=r(86),i=r.n(a),s=r(11882),l=r.n(s),u=r(97606),c=r.n(u),p=r(14418),f=r.n(p),h=r(51679),d=r.n(h),m=r(24282),g=r.n(m),v=r(2578),y=r.n(v),b=r(92039),w=r.n(b),E=r(58309),x=r.n(E),_=r(20573),S=r(90242),A=r(43393);const k=["get","put","post","delete","options","head","patch","trace"],C=e=>e||(0,A.Map)(),O=(0,_.P1)(C,(e=>e.get("lastError"))),j=(0,_.P1)(C,(e=>e.get("url"))),I=(0,_.P1)(C,(e=>e.get("spec")||"")),N=(0,_.P1)(C,(e=>e.get("specSource")||"not-editor")),T=(0,_.P1)(C,(e=>e.get("json",(0,A.Map)()))),P=(0,_.P1)(C,(e=>e.get("resolved",(0,A.Map)()))),R=(e,t)=>e.getIn(["resolvedSubtrees",...t],void 0),M=(e,t)=>A.Map.isMap(e)&&A.Map.isMap(t)?t.get("$$ref")?t:(0,A.OrderedMap)().mergeWith(M,e,t):t,D=(0,_.P1)(C,(e=>(0,A.OrderedMap)().mergeWith(M,e.get("json"),e.get("resolvedSubtrees")))),L=e=>T(e),B=(0,_.P1)(L,(()=>!1)),F=(0,_.P1)(L,(e=>Ne(e&&e.get("info")))),z=(0,_.P1)(L,(e=>Ne(e&&e.get("externalDocs")))),U=(0,_.P1)(F,(e=>e&&e.get("version"))),q=(0,_.P1)(U,(e=>{var t;return o()(t=/v?([0-9]*)\.([0-9]*)\.([0-9]*)/i.exec(e)).call(t,1)})),V=(0,_.P1)(D,(e=>e.get("paths"))),$=(0,_.P1)(V,(e=>{if(!e||e.size<1)return(0,A.List)();let t=(0,A.List)();return e&&i()(e)?(i()(e).call(e,((e,r)=>{if(!e||!i()(e))return{};i()(e).call(e,((e,n)=>{l()(k).call(k,n)<0||(t=t.push((0,A.fromJS)({path:r,method:n,operation:e,id:`${n}-${r}`})))}))})),t):(0,A.List)()})),W=(0,_.P1)(L,(e=>(0,A.Set)(e.get("consumes")))),H=(0,_.P1)(L,(e=>(0,A.Set)(e.get("produces")))),J=(0,_.P1)(L,(e=>e.get("security",(0,A.List)()))),K=(0,_.P1)(L,(e=>e.get("securityDefinitions"))),G=(e,t)=>{const r=e.getIn(["resolvedSubtrees","definitions",t],null),n=e.getIn(["json","definitions",t],null);return r||n||null},Z=(0,_.P1)(L,(e=>{const t=e.get("definitions");return A.Map.isMap(t)?t:(0,A.Map)()})),Y=(0,_.P1)(L,(e=>e.get("basePath"))),Q=(0,_.P1)(L,(e=>e.get("host"))),X=(0,_.P1)(L,(e=>e.get("schemes",(0,A.Map)()))),ee=(0,_.P1)($,W,H,((e,t,r)=>c()(e).call(e,(e=>e.update("operation",(e=>{if(e){if(!A.Map.isMap(e))return;return e.withMutations((e=>(e.get("consumes")||e.update("consumes",(e=>(0,A.Set)(e).merge(t))),e.get("produces")||e.update("produces",(e=>(0,A.Set)(e).merge(r))),e)))}return(0,A.Map)()})))))),te=(0,_.P1)(L,(e=>{const t=e.get("tags",(0,A.List)());return A.List.isList(t)?f()(t).call(t,(e=>A.Map.isMap(e))):(0,A.List)()})),re=(e,t)=>{var r;let n=te(e)||(0,A.List)();return d()(r=f()(n).call(n,A.Map.isMap)).call(r,(e=>e.get("name")===t),(0,A.Map)())},ne=(0,_.P1)(ee,te,((e,t)=>g()(e).call(e,((e,t)=>{let r=(0,A.Set)(t.getIn(["operation","tags"]));return r.count()<1?e.update("default",(0,A.List)(),(e=>e.push(t))):g()(r).call(r,((e,r)=>e.update(r,(0,A.List)(),(e=>e.push(t)))),e)}),g()(t).call(t,((e,t)=>e.set(t.get("name"),(0,A.List)())),(0,A.OrderedMap)())))),oe=e=>t=>{var r;let{getConfigs:n}=t,{tagsSorter:o,operationsSorter:a}=n();return c()(r=ne(e).sortBy(((e,t)=>t),((e,t)=>{let r="function"==typeof o?o:S.wh.tagsSorter[o];return r?r(e,t):null}))).call(r,((t,r)=>{let n="function"==typeof a?a:S.wh.operationsSorter[a],o=n?y()(t).call(t,n):t;return(0,A.Map)({tagDetails:re(e,r),operations:o})}))},ae=(0,_.P1)(C,(e=>e.get("responses",(0,A.Map)()))),ie=(0,_.P1)(C,(e=>e.get("requests",(0,A.Map)()))),se=(0,_.P1)(C,(e=>e.get("mutatedRequests",(0,A.Map)()))),le=(e,t,r)=>ae(e).getIn([t,r],null),ue=(e,t,r)=>ie(e).getIn([t,r],null),ce=(e,t,r)=>se(e).getIn([t,r],null),pe=()=>!0,fe=(e,t,r)=>{const n=D(e).getIn(["paths",...t,"parameters"],(0,A.OrderedMap)()),o=e.getIn(["meta","paths",...t,"parameters"],(0,A.OrderedMap)()),a=c()(n).call(n,(e=>{const t=o.get(`${r.get("in")}.${r.get("name")}`),n=o.get(`${r.get("in")}.${r.get("name")}.hash-${r.hashCode()}`);return(0,A.OrderedMap)().merge(e,t,n)}));return d()(a).call(a,(e=>e.get("in")===r.get("in")&&e.get("name")===r.get("name")),(0,A.OrderedMap)())},he=(e,t,r,n)=>{const o=`${n}.${r}`;return e.getIn(["meta","paths",...t,"parameter_inclusions",o],!1)},de=(e,t,r,n)=>{const o=D(e).getIn(["paths",...t,"parameters"],(0,A.OrderedMap)()),a=d()(o).call(o,(e=>e.get("in")===n&&e.get("name")===r),(0,A.OrderedMap)());return fe(e,t,a)},me=(e,t,r)=>{var n;const o=D(e).getIn(["paths",t,r],(0,A.OrderedMap)()),a=e.getIn(["meta","paths",t,r],(0,A.OrderedMap)()),i=c()(n=o.get("parameters",(0,A.List)())).call(n,(n=>fe(e,[t,r],n)));return(0,A.OrderedMap)().merge(o,a).set("parameters",i)};function ge(e,t,r,n){t=t||[];let o=e.getIn(["meta","paths",...t,"parameters"],(0,A.fromJS)([]));return d()(o).call(o,(e=>A.Map.isMap(e)&&e.get("name")===r&&e.get("in")===n))||(0,A.Map)()}const ve=(0,_.P1)(L,(e=>{const t=e.get("host");return"string"==typeof t&&t.length>0&&"/"!==t[0]}));function ye(e,t,r){t=t||[];let n=me(e,...t).get("parameters",(0,A.List)());return g()(n).call(n,((e,t)=>{let n=r&&"body"===t.get("in")?t.get("value_xml"):t.get("value");return e.set((0,S.V9)(t,{allowHashes:!1}),n)}),(0,A.fromJS)({}))}function be(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(A.List.isList(e))return w()(e).call(e,(e=>A.Map.isMap(e)&&e.get("in")===t))}function we(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(A.List.isList(e))return w()(e).call(e,(e=>A.Map.isMap(e)&&e.get("type")===t))}function Ee(e,t){t=t||[];let r=D(e).getIn(["paths",...t],(0,A.fromJS)({})),n=e.getIn(["meta","paths",...t],(0,A.fromJS)({})),o=xe(e,t);const a=r.get("parameters")||new A.List,i=n.get("consumes_value")?n.get("consumes_value"):we(a,"file")?"multipart/form-data":we(a,"formData")?"application/x-www-form-urlencoded":void 0;return(0,A.fromJS)({requestContentType:i,responseContentType:o})}function xe(e,t){t=t||[];const r=D(e).getIn(["paths",...t],null);if(null===r)return;const n=e.getIn(["meta","paths",...t,"produces_value"],null),o=r.getIn(["produces",0],null);return n||o||"application/json"}function _e(e,t){t=t||[];const r=D(e),n=r.getIn(["paths",...t],null);if(null===n)return;const[o]=t,a=n.get("produces",null),i=r.getIn(["paths",o,"produces"],null),s=r.getIn(["produces"],null);return a||i||s}function Se(e,t){t=t||[];const r=D(e),n=r.getIn(["paths",...t],null);if(null===n)return;const[o]=t,a=n.get("consumes",null),i=r.getIn(["paths",o,"consumes"],null),s=r.getIn(["consumes"],null);return a||i||s}const Ae=(e,t,r)=>{let n=e.get("url").match(/^([a-z][a-z0-9+\-.]*):/),o=x()(n)?n[1]:null;return e.getIn(["scheme",t,r])||e.getIn(["scheme","_defaultScheme"])||o||""},ke=(e,t,r)=>{var n;return l()(n=["http","https"]).call(n,Ae(e,t,r))>-1},Ce=(e,t)=>{t=t||[];let r=e.getIn(["meta","paths",...t,"parameters"],(0,A.fromJS)([]));const n=[];return i()(r).call(r,(e=>{let t=e.get("errors");t&&t.count()&&i()(t).call(t,(e=>n.push(e)))})),n},Oe=(e,t)=>0===Ce(e,t).length,je=(e,t)=>{var r;let n={requestBody:!1,requestContentType:{}},o=e.getIn(["resolvedSubtrees","paths",...t,"requestBody"],(0,A.fromJS)([]));return o.size<1||(o.getIn(["required"])&&(n.requestBody=o.getIn(["required"])),i()(r=o.getIn(["content"]).entrySeq()).call(r,(e=>{const t=e[0];if(e[1].getIn(["schema","required"])){const r=e[1].getIn(["schema","required"]).toJS();n.requestContentType[t]=r}}))),n},Ie=(e,t,r,n)=>{if((r||n)&&r===n)return!0;let o=e.getIn(["resolvedSubtrees","paths",...t,"requestBody","content"],(0,A.fromJS)([]));if(o.size<2||!r||!n)return!1;let a=o.getIn([r,"schema","properties"],(0,A.fromJS)([])),i=o.getIn([n,"schema","properties"],(0,A.fromJS)([]));return!!a.equals(i)};function Ne(e){return A.Map.isMap(e)?e:new A.Map}},77508:(e,t,r)=>{"use strict";r.r(t),r.d(t,{updateSpec:()=>u,updateJsonSpec:()=>c,executeRequest:()=>p,validateParams:()=>f});var n=r(28222),o=r.n(n),a=r(86),i=r.n(a),s=r(27361),l=r.n(s);const u=(e,t)=>{let{specActions:r}=t;return function(){e(...arguments),r.parseToJson(...arguments)}},c=(e,t)=>{let{specActions:r}=t;return function(){for(var t=arguments.length,n=new Array(t),a=0;a{l()(u,[e]).$ref&&r.requestResolvedSubtree(["paths",e])})),r.requestResolvedSubtree(["components","securitySchemes"])}},p=(e,t)=>{let{specActions:r}=t;return t=>(r.logRequest(t),e(t))},f=(e,t)=>{let{specSelectors:r}=t;return t=>e(t,r.isOAS3())}},34852:(e,t,r)=>{"use strict";r.r(t),r.d(t,{loaded:()=>n});const n=(e,t)=>function(){e(...arguments);const r=t.getConfigs().withCredentials;void 0!==r&&(t.fn.fetch.withCredentials="string"==typeof r?"true"===r:!!r)}},48792:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>qr});var n={};r.r(n),r.d(n,{JsonPatchError:()=>Fe,_areEquals:()=>Ge,applyOperation:()=>$e,applyPatch:()=>We,applyReducer:()=>He,deepClone:()=>ze,getValueByPointer:()=>Ve,validate:()=>Ke,validator:()=>Je});var o={};r.r(o),r.d(o,{compare:()=>nt,generate:()=>tt,observe:()=>et,unobserve:()=>Xe});var a={};r.r(a),r.d(a,{cookie:()=>kr,header:()=>Ar,path:()=>xr,query:()=>_r});var i=r(80093),s=r.n(i),l=r(30222),u=r.n(l),c=r(36594),p=r.n(c),f=r(20474),h=r.n(f),d=r(67375),m=r.n(d),g=r(58118),v=r.n(g),y=r(74386),b=r.n(y),w=r(25110),E=r.n(w),x=r(35627),_=r.n(x),S=r(97606),A=r.n(S),k=r(28222),C=r.n(k),O=r(39022),j=r.n(O),I=r(2018),N=r.n(I),T=r(14418),P=r.n(T),R=(r(31905),r(80129)),M=r.n(R),D=r(1272);const L="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window,{FormData:B,Blob:F,File:z}=L;var U=r(15687),q=r.n(U),V=r(24278),$=r.n(V),W=function(e){return":/?#[]@!$&'()*+,;=".indexOf(e)>-1},H=function(e){return/^[a-z0-9\-._~]+$/i.test(e)};function J(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.escape,o=arguments.length>2?arguments[2]:void 0;return"number"==typeof e&&(e=e.toString()),"string"==typeof e&&e.length&&n?o?JSON.parse(e):A()(t=q()(e)).call(t,(function(e){var t,r;if(H(e))return e;if(W(e)&&"unsafe"===n)return e;var o=new TextEncoder;return A()(t=A()(r=E()(o.encode(e))).call(r,(function(e){var t;return $()(t="0".concat(e.toString(16).toUpperCase())).call(t,-2)}))).call(t,(function(e){return"%".concat(e)})).join("")})).join(""):e}function K(e){var t=e.value;return Array.isArray(t)?function(e){var t=e.key,r=e.value,n=e.style,o=e.explode,a=e.escape,i=function(e){return J(e,{escape:a})};if("simple"===n)return A()(r).call(r,(function(e){return i(e)})).join(",");if("label"===n)return".".concat(A()(r).call(r,(function(e){return i(e)})).join("."));if("matrix"===n)return A()(r).call(r,(function(e){return i(e)})).reduce((function(e,r){var n,a,i;return!e||o?j()(a=j()(i="".concat(e||"",";")).call(i,t,"=")).call(a,r):j()(n="".concat(e,",")).call(n,r)}),"");if("form"===n){var s=o?"&".concat(t,"="):",";return A()(r).call(r,(function(e){return i(e)})).join(s)}if("spaceDelimited"===n){var l=o?"".concat(t,"="):"";return A()(r).call(r,(function(e){return i(e)})).join(" ".concat(l))}if("pipeDelimited"===n){var u=o?"".concat(t,"="):"";return A()(r).call(r,(function(e){return i(e)})).join("|".concat(u))}return}(e):"object"===h()(t)?function(e){var t=e.key,r=e.value,n=e.style,o=e.explode,a=e.escape,i=function(e){return J(e,{escape:a})},s=C()(r);if("simple"===n)return s.reduce((function(e,t){var n,a,s,l=i(r[t]),u=o?"=":",",c=e?"".concat(e,","):"";return j()(n=j()(a=j()(s="".concat(c)).call(s,t)).call(a,u)).call(n,l)}),"");if("label"===n)return s.reduce((function(e,t){var n,a,s,l=i(r[t]),u=o?"=":".",c=e?"".concat(e,"."):".";return j()(n=j()(a=j()(s="".concat(c)).call(s,t)).call(a,u)).call(n,l)}),"");if("matrix"===n&&o)return s.reduce((function(e,t){var n,o,a=i(r[t]),s=e?"".concat(e,";"):";";return j()(n=j()(o="".concat(s)).call(o,t,"=")).call(n,a)}),"");if("matrix"===n)return s.reduce((function(e,n){var o,a,s=i(r[n]),l=e?"".concat(e,","):";".concat(t,"=");return j()(o=j()(a="".concat(l)).call(a,n,",")).call(o,s)}),"");if("form"===n)return s.reduce((function(e,t){var n,a,s,l,u=i(r[t]),c=e?j()(n="".concat(e)).call(n,o?"&":","):"",p=o?"=":",";return j()(a=j()(s=j()(l="".concat(c)).call(l,t)).call(s,p)).call(a,u)}),"");return}(e):function(e){var t,r=e.key,n=e.value,o=e.style,a=e.escape,i=function(e){return J(e,{escape:a})};if("simple"===o)return i(n);if("label"===o)return".".concat(i(n));if("matrix"===o)return j()(t=";".concat(r,"=")).call(t,i(n));if("form"===o)return i(n);if("deepObject"===o)return i(n,{},!0);return}(e)}const G=function(e,t){t.body=e};var Z={serializeRes:te,mergeInQueryOrForm:fe};function Y(e){return Q.apply(this,arguments)}function Q(){return Q=s()(u().mark((function e(t){var r,n,o,a,i,s=arguments;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=s.length>1&&void 0!==s[1]?s[1]:{},"object"===h()(t)&&(t=(r=t).url),r.headers=r.headers||{},Z.mergeInQueryOrForm(r),r.headers&&C()(r.headers).forEach((function(e){var t=r.headers[e];"string"==typeof t&&(r.headers[e]=t.replace(/\n+/g," "))})),!r.requestInterceptor){e.next=12;break}return e.next=8,r.requestInterceptor(r);case 8:if(e.t0=e.sent,e.t0){e.next=11;break}e.t0=r;case 11:r=e.t0;case 12:return n=r.headers["content-type"]||r.headers["Content-Type"],/multipart\/form-data/i.test(n)&&r.body instanceof B&&(delete r.headers["content-type"],delete r.headers["Content-Type"]),e.prev=14,e.next=17,(r.userFetch||fetch)(r.url,r);case 17:return o=e.sent,e.next=20,Z.serializeRes(o,t,r);case 20:if(o=e.sent,!r.responseInterceptor){e.next=28;break}return e.next=24,r.responseInterceptor(o);case 24:if(e.t1=e.sent,e.t1){e.next=27;break}e.t1=o;case 27:o=e.t1;case 28:e.next=39;break;case 30:if(e.prev=30,e.t2=e.catch(14),o){e.next=34;break}throw e.t2;case 34:throw(a=new Error(o.statusText||"response status is ".concat(o.status))).status=o.status,a.statusCode=o.status,a.responseError=e.t2,a;case 39:if(o.ok){e.next=45;break}throw(i=new Error(o.statusText||"response status is ".concat(o.status))).status=o.status,i.statusCode=o.status,i.response=o,i;case 45:return e.abrupt("return",o);case 46:case"end":return e.stop()}}),e,null,[[14,30]])}))),Q.apply(this,arguments)}var X=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return/(json|xml|yaml|text)\b/.test(e)};function ee(e,t){return t&&(0===t.indexOf("application/json")||t.indexOf("+json")>0)?JSON.parse(e):D.ZP.load(e)}function te(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.loadSpec,o=void 0!==n&&n,a={ok:e.ok,url:e.url||t,status:e.status,statusText:e.statusText,headers:ne(e.headers)},i=a.headers["content-type"],s=o||X(i),l=s?e.text:e.blob||e.buffer;return l.call(e).then((function(e){if(a.text=e,a.data=e,s)try{var t=ee(e,i);a.body=t,a.obj=t}catch(e){a.parseError=e}return a}))}function re(e){return v()(e).call(e,", ")?e.split(", "):e}function ne(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return"function"!=typeof b()(e)?{}:E()(b()(e).call(e)).reduce((function(e,t){var r=m()(t,2),n=r[0],o=r[1];return e[n]=re(o),e}),{})}function oe(e,t){return t||"undefined"==typeof navigator||(t=navigator),t&&"ReactNative"===t.product?!(!e||"object"!==h()(e)||"string"!=typeof e.uri):void 0!==z&&e instanceof z||(void 0!==F&&e instanceof F||(!!ArrayBuffer.isView(e)||null!==e&&"object"===h()(e)&&"function"==typeof e.pipe))}function ae(e,t){return Array.isArray(e)&&e.some((function(e){return oe(e,t)}))}var ie={form:",",spaceDelimited:"%20",pipeDelimited:"|"},se={csv:",",ssv:"%20",tsv:"%09",pipes:"|"};function le(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=t.collectionFormat,o=t.allowEmptyValue,a=t.serializationOption,i=t.encoding,s="object"!==h()(t)||Array.isArray(t)?t:t.value,l=r?function(e){return e.toString()}:function(e){return encodeURIComponent(e)},u=l(e);if(void 0===s&&o)return[[u,""]];if(oe(s)||ae(s))return[[u,s]];if(a)return ue(e,s,r,a);if(i){if([h()(i.style),h()(i.explode),h()(i.allowReserved)].some((function(e){return"undefined"!==e}))){var c=i.style,p=i.explode,f=i.allowReserved;return ue(e,s,r,{style:c,explode:p,allowReserved:f})}if(i.contentType){if("application/json"===i.contentType){var d="string"==typeof s?s:_()(s);return[[u,l(d)]]}return[[u,l(s.toString())]]}return"object"!==h()(s)?[[u,l(s)]]:Array.isArray(s)&&s.every((function(e){return"object"!==h()(e)}))?[[u,A()(s).call(s,l).join(",")]]:[[u,l(_()(s))]]}return"object"!==h()(s)?[[u,l(s)]]:Array.isArray(s)?"multi"===n?[[u,A()(s).call(s,l)]]:[[u,A()(s).call(s,l).join(se[n||"csv"])]]:[[u,""]]}function ue(e,t,r,n){var o,a,i,s=n.style||"form",l=void 0===n.explode?"form"===s:n.explode,u=!r&&(n&&n.allowReserved?"unsafe":"reserved"),c=function(e){return J(e,{escape:u})},p=r?function(e){return e}:function(e){return J(e,{escape:u})};return"object"!==h()(t)?[[p(e),c(t)]]:Array.isArray(t)?l?[[p(e),A()(t).call(t,c)]]:[[p(e),A()(t).call(t,c).join(ie[s])]]:"deepObject"===s?A()(a=C()(t)).call(a,(function(r){var n;return[p(j()(n="".concat(e,"[")).call(n,r,"]")),c(t[r])]})):l?A()(i=C()(t)).call(i,(function(e){return[p(e),c(t[e])]})):[[p(e),A()(o=C()(t)).call(o,(function(e){var r;return[j()(r="".concat(p(e),",")).call(r,c(t[e]))]})).join(",")]]}function ce(e){return N()(e).reduce((function(e,t){var r,n=m()(t,2),o=n[0],a=n[1],i=p()(le(o,a,!0));try{for(i.s();!(r=i.n()).done;){var s=m()(r.value,2),l=s[0],u=s[1];if(Array.isArray(u)){var c,f=p()(u);try{for(f.s();!(c=f.n()).done;){var h=c.value;if(ArrayBuffer.isView(h)){var d=new F([h]);e.append(l,d)}else e.append(l,h)}}catch(e){f.e(e)}finally{f.f()}}else if(ArrayBuffer.isView(u)){var g=new F([u]);e.append(l,g)}else e.append(l,u)}}catch(e){i.e(e)}finally{i.f()}return e}),new B)}function pe(e){var t=C()(e).reduce((function(t,r){var n,o=p()(le(r,e[r]));try{for(o.s();!(n=o.n()).done;){var a=m()(n.value,2),i=a[0],s=a[1];t[i]=s}}catch(e){o.e(e)}finally{o.f()}return t}),{});return M().stringify(t,{encode:!1,indices:!1})||""}function fe(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.url,r=void 0===t?"":t,n=e.query,o=e.form,a=function(){for(var e=arguments.length,t=new Array(e),r=0;r=48&&t<=57))return!1;r++}return!0}function Re(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Me(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function De(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(var t=0,r=e.length;t0&&"constructor"==s[u-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&void 0===p&&(void 0===l[f]?p=s.slice(0,u).join("/"):u==c-1&&(p=t.path),void 0!==p&&h(t,0,e,p)),u++,Array.isArray(l)){if("-"===f)f=l.length;else{if(r&&!Pe(f))throw new Fe("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,t,e);Pe(f)&&(f=~~f)}if(u>=c){if(r&&"add"===t.op&&f>l.length)throw new Fe("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,t,e);if(!1===(i=qe[t.op].call(t,l,f,e)).test)throw new Fe("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return i}}else if(u>=c){if(!1===(i=Ue[t.op].call(t,l,f,e)).test)throw new Fe("Test operation failed","TEST_OPERATION_FAILED",a,t,e);return i}if(l=l[f],r&&u0)throw new Fe('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new Fe("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new Fe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&De(e.value))throw new Fe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var o=e.path.split("/").length,a=n.split("/").length;if(o!==a+1&&o!==a)throw new Fe("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new Fe("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var i=Ke([{op:"_get",path:e.from,value:void 0}],r);if(i&&"OPERATION_PATH_UNRESOLVABLE"===i.name)throw new Fe("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function Ke(e,t,r){try{if(!Array.isArray(e))throw new Fe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)We(Te(t),Te(e),r||!0);else{r=r||Je;for(var n=0;n0&&(e.patches=[],e.callback&&e.callback(n)),n}function rt(e,t,r,n,o){if(t!==e){"function"==typeof t.toJSON&&(t=t.toJSON());for(var a=Ne(t),i=Ne(e),s=!1,l=i.length-1;l>=0;l--){var u=e[p=i[l]];if(!Ie(t,p)||void 0===t[p]&&void 0!==u&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(o&&r.push({op:"test",path:n+"/"+Re(p),value:Te(u)}),r.push({op:"remove",path:n+"/"+Re(p)}),s=!0):(o&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}),!0);else{var c=t[p];"object"==typeof u&&null!=u&&"object"==typeof c&&null!=c&&Array.isArray(u)===Array.isArray(c)?rt(u,c,r,n+"/"+Re(p),o):u!==c&&(!0,o&&r.push({op:"test",path:n+"/"+Re(p),value:Te(u)}),r.push({op:"replace",path:n+"/"+Re(p),value:Te(c)}))}}if(s||a.length!=i.length)for(l=0;l0){var o=t(e,r[r.length-1],r);o&&(n=j()(n).call(n,o))}if(Array.isArray(e)){var a=A()(e).call(e,(function(e,n){return pt(e,t,j()(r).call(r,n))}));a&&(n=j()(n).call(n,a))}else if(mt(e)){var i,s=A()(i=C()(e)).call(i,(function(n){return pt(e[n],t,j()(r).call(r,n))}));s&&(n=j()(n).call(n,s))}return n=ht(n)}function ft(e){return Array.isArray(e)?e:[e]}function ht(e){var t;return j()(t=[]).apply(t,q()(A()(e).call(e,(function(e){return Array.isArray(e)?ht(e):e}))))}function dt(e){return P()(e).call(e,(function(e){return void 0!==e}))}function mt(e){return e&&"object"===h()(e)}function gt(e){return e&&"function"==typeof e}function vt(e){if(wt(e)){var t=e.op;return"add"===t||"remove"===t||"replace"===t}return!1}function yt(e){return vt(e)||wt(e)&&"mutation"===e.type}function bt(e){return yt(e)&&("add"===e.op||"replace"===e.op||"merge"===e.op||"mergeDeep"===e.op)}function wt(e){return e&&"object"===h()(e)}function Et(e,t){try{return Ve(e,t)}catch(e){return console.error(e),{}}}var xt=r(28886),_t=r.n(xt),St=r(37659),At=r.n(St),kt=r(8575);function Ct(e,t){function r(){Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack;for(var e=arguments.length,r=new Array(e),n=0;n-1&&-1===Nt.indexOf(r)||Tt.indexOf(n)>-1||Pt.some((function(e){return n.indexOf(e)>-1}))}function Mt(e,t){var r,n=e.split("#"),o=m()(n,2),a=o[0],i=o[1],s=kt.resolve(a||"",t||"");return i?j()(r="".concat(s,"#")).call(r,i):s}var Dt="application/json, application/yaml",Lt=/^([a-z]+:\/\/|\/\/)/i,Bt=Ct("JSONRefError",(function(e,t,r){this.originalError=r,Ee()(this,t||{})})),Ft={},zt=new(_t()),Ut=[function(e){return"paths"===e[0]&&"responses"===e[3]&&"examples"===e[5]},function(e){return"paths"===e[0]&&"responses"===e[3]&&"content"===e[5]&&"example"===e[7]},function(e){return"paths"===e[0]&&"responses"===e[3]&&"content"===e[5]&&"examples"===e[7]&&"value"===e[9]},function(e){return"paths"===e[0]&&"requestBody"===e[3]&&"content"===e[4]&&"example"===e[6]},function(e){return"paths"===e[0]&&"requestBody"===e[3]&&"content"===e[4]&&"examples"===e[6]&&"value"===e[8]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"example"===e[4]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"example"===e[5]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"examples"===e[4]&&"value"===e[6]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"examples"===e[5]&&"value"===e[7]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"content"===e[4]&&"example"===e[6]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"content"===e[4]&&"examples"===e[6]&&"value"===e[8]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"content"===e[4]&&"example"===e[7]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"content"===e[5]&&"examples"===e[7]&&"value"===e[9]}],qt={key:"$ref",plugin:function(e,t,r,n){var o=n.getInstance(),a=$()(r).call(r,0,-1);if(!Rt(a)&&!function(e){return Ut.some((function(t){return t(e)}))}(a)){var i=n.getContext(r).baseDoc;if("string"!=typeof e)return new Bt("$ref: must be a string (JSON-Ref)",{$ref:e,baseDoc:i,fullPath:r});var s,l,u,c=Jt(e),p=c[0],f=c[1]||"";try{s=i||p?Wt(p,i):null}catch(t){return Ht(t,{pointer:f,$ref:e,basePath:s,fullPath:r})}if(function(e,t,r,n){var o,a,i=zt.get(n);i||(i={},zt.set(n,i));var s=function(e){if(0===e.length)return"";return"/".concat(A()(e).call(e,Xt).join("/"))}(r),l=j()(o="".concat(t||"","#")).call(o,e),u=s.replace(/allOf\/\d+\/?/g,""),c=n.contextTree.get([]).baseDoc;if(t===c&&er(u,e))return!0;var p="",f=r.some((function(e){var t;return p=j()(t="".concat(p,"/")).call(t,Xt(e)),i[p]&&i[p].some((function(e){return er(e,l)||er(l,e)}))}));if(f)return!0;return void(i[u]=j()(a=i[u]||[]).call(a,l))}(f,s,a,n)&&!o.useCircularStructures){var h=Mt(e,s);return e===h?null:it.replace(r,h)}if(null==s?(u=Yt(f),void 0===(l=n.get(u))&&(l=new Bt("Could not resolve reference: ".concat(e),{pointer:f,$ref:e,baseDoc:i,fullPath:r}))):l=null!=(l=Kt(s,f)).__value?l.__value:l.catch((function(t){throw Ht(t,{pointer:f,$ref:e,baseDoc:i,fullPath:r})})),l instanceof Error)return[it.remove(r),l];var d=Mt(e,s),m=it.replace(a,l,{$$ref:d});if(s&&s!==i)return[m,it.context(a,{baseDoc:s})];try{if(!function(e,t){var r=[e];return t.path.reduce((function(e,t){return r.push(e[t]),e[t]}),e),n(t.value);function n(e){return it.isObject(e)&&(r.indexOf(e)>=0||C()(e).some((function(t){return n(e[t])})))}}(n.state,m)||o.useCircularStructures)return m}catch(e){return null}}}},Vt=Ee()(qt,{docCache:Ft,absoluteify:Wt,clearCache:function(e){void 0!==e?delete Ft[e]:C()(Ft).forEach((function(e){delete Ft[e]}))},JSONRefError:Bt,wrapError:Ht,getDoc:Gt,split:Jt,extractFromDoc:Kt,fetchJSON:function(e){return fetch(e,{headers:{Accept:Dt},loadSpec:!0}).then((function(e){return e.text()})).then((function(e){return D.ZP.load(e)}))},extract:Zt,jsonPointerToArray:Yt,unescapeJsonPointerToken:Qt});const $t=Vt;function Wt(e,t){if(!Lt.test(e)){var r;if(!t)throw new Bt(j()(r="Tried to resolve a relative URL, without having a basePath. path: '".concat(e,"' basePath: '")).call(r,t,"'"));return kt.resolve(t,e)}return e}function Ht(e,t){var r,n;e&&e.response&&e.response.body?r=j()(n="".concat(e.response.body.code," ")).call(n,e.response.body.message):r=e.message;return new Bt("Could not resolve reference: ".concat(r),t,e)}function Jt(e){return(e+"").split("#")}function Kt(e,t){var r=Ft[e];if(r&&!it.isPromise(r))try{var n=Zt(t,r);return Ee()(Ae().resolve(n),{__value:n})}catch(e){return Ae().reject(e)}return Gt(e).then((function(e){return Zt(t,e)}))}function Gt(e){var t=Ft[e];return t?it.isPromise(t)?t:Ae().resolve(t):(Ft[e]=Vt.fetchJSON(e).then((function(t){return Ft[e]=t,t})),Ft[e])}function Zt(e,t){var r=Yt(e);if(r.length<1)return t;var n=it.getIn(t,r);if(void 0===n)throw new Bt("Could not resolve pointer: ".concat(e," does not exist in document"),{pointer:e});return n}function Yt(e){var t;if("string"!=typeof e)throw new TypeError("Expected a string, got a ".concat(h()(e)));return"/"===e[0]&&(e=e.substr(1)),""===e?[]:A()(t=e.split("/")).call(t,Qt)}function Qt(e){return"string"!=typeof e?e:new(At())("=".concat(e.replace(/~1/g,"/").replace(/~0/g,"~"))).get("")}function Xt(e){var t,r=new(At())([["",e.replace(/~/g,"~0").replace(/\//g,"~1")]]);return $()(t=r.toString()).call(t,1)}function er(e,t){if(!(r=t)||"/"===r||"#"===r)return!0;var r,n=e.charAt(t.length),o=$()(t).call(t,-1);return 0===e.indexOf(t)&&(!n||"/"===n||"#"===n)&&"#"!==o}const tr={key:"allOf",plugin:function(e,t,r,n,o){if(!o.meta||!o.meta.$$ref){var a=$()(r).call(r,0,-1);if(!Rt(a)){if(!Array.isArray(e)){var i=new TypeError("allOf must be an array");return i.fullPath=r,i}var s=!1,l=o.value;if(a.forEach((function(e){l&&(l=l[e])})),l=me()({},l),0!==C()(l).length){delete l.allOf;var u,c,p=[];if(p.push(n.replace(a,{})),e.forEach((function(e,t){if(!n.isObject(e)){if(s)return null;s=!0;var o=new TypeError("Elements in allOf must be objects");return o.fullPath=r,p.push(o)}p.push(n.mergeDeep(a,e));var i=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.specmap,o=r.getBaseUrlForNodePath,a=void 0===o?function(e){var r;return n.getContext(j()(r=[]).call(r,q()(t),q()(e))).baseDoc}:o,i=r.targetKeys,s=void 0===i?["$ref","$$ref"]:i,l=[];return jt()(e).forEach((function(){if(v()(s).call(s,this.key)&&"string"==typeof this.node){var e=this.path,r=j()(t).call(t,this.path),o=Mt(this.node,a(e));l.push(n.replace(r,o))}})),l}(e,$()(r).call(r,0,-1),{getBaseUrlForNodePath:function(e){var o;return n.getContext(j()(o=[]).call(o,q()(r),[t],q()(e))).baseDoc},specmap:n});p.push.apply(p,q()(i))})),l.example)p.push(n.remove(j()(u=[]).call(u,a,"example")));if(p.push(n.mergeDeep(a,l)),!l.$$ref)p.push(n.remove(j()(c=[]).call(c,a,"$$ref")));return p}}}}},rr={key:"parameters",plugin:function(e,t,r,n){if(Array.isArray(e)&&e.length){var o=Ee()([],e),a=$()(r).call(r,0,-1),i=me()({},it.getIn(n.spec,a));return e.forEach((function(e,t){try{o[t].default=n.parameterMacro(i,e)}catch(e){var a=new Error(e);return a.fullPath=r,a}})),it.replace(r,o)}return it.replace(r,e)}},nr={key:"properties",plugin:function(e,t,r,n){var o=me()({},e);for(var a in e)try{o[a].default=n.modelPropertyMacro(o[a])}catch(e){var i=new Error(e);return i.fullPath=r,i}return it.replace(r,o)}};var or=function(){function e(t){ve()(this,e),this.root=ar(t||{})}return be()(e,[{key:"set",value:function(e,t){var r=this.getParent(e,!0);if(r){var n=e[e.length-1],o=r.children;o[n]?ir(o[n],t,r):o[n]=ar(t,r)}else ir(this.root,t,null)}},{key:"get",value:function(e){if((e=e||[]).length<1)return this.root.value;for(var t,r,n=this.root,o=0;o1?r-1:0),o=1;o1?n-1:0),a=1;a0}))}},{key:"nextPromisedPatch",value:function(){var e;if(this.promisedPatches.length>0)return Ae().race(A()(e=this.promisedPatches).call(e,(function(e){return e.value})))}},{key:"getPluginHistory",value:function(e){var t=this.constructor.getPluginName(e);return this.pluginHistory[t]||[]}},{key:"getPluginRunCount",value:function(e){return this.getPluginHistory(e).length}},{key:"getPluginHistoryTip",value:function(e){var t=this.getPluginHistory(e);return t&&t[t.length-1]||{}}},{key:"getPluginMutationIndex",value:function(e){var t=this.getPluginHistoryTip(e).mutationIndex;return"number"!=typeof t?-1:t}},{key:"updatePluginHistory",value:function(e,t){var r=this.constructor.getPluginName(e);this.pluginHistory[r]=this.pluginHistory[r]||[],this.pluginHistory[r].push(t)}},{key:"updatePatches",value:function(e){var t=this;it.normalizeArray(e).forEach((function(e){if(e instanceof Error)t.errors.push(e);else try{if(!it.isObject(e))return void t.debug("updatePatches","Got a non-object patch",e);if(t.showDebug&&t.allPatches.push(e),it.isPromise(e.value))return t.promisedPatches.push(e),void t.promisedPatchThen(e);if(it.isContextPatch(e))return void t.setContext(e.path,e.value);if(it.isMutation(e))return void t.updateMutations(e)}catch(e){console.error(e),t.errors.push(e)}}))}},{key:"updateMutations",value:function(e){"object"===h()(e.value)&&!Array.isArray(e.value)&&this.allowMetaPatches&&(e.value=me()({},e.value));var t=it.applyPatch(this.state,e,{allowMetaPatches:this.allowMetaPatches});t&&(this.mutations.push(e),this.state=t)}},{key:"removePromisedPatch",value:function(e){var t,r=this.promisedPatches.indexOf(e);r<0?this.debug("Tried to remove a promisedPatch that isn't there!"):Ce()(t=this.promisedPatches).call(t,r,1)}},{key:"promisedPatchThen",value:function(e){var t=this;return e.value=e.value.then((function(r){var n=me()(me()({},e),{},{value:r});t.removePromisedPatch(e),t.updatePatches(n)})).catch((function(r){t.removePromisedPatch(e),t.updatePatches(r)})),e.value}},{key:"getMutations",value:function(e,t){var r;return e=e||0,"number"!=typeof t&&(t=this.mutations.length),$()(r=this.mutations).call(r,e,t)}},{key:"getCurrentMutations",value:function(){return this.getMutationsForPlugin(this.getCurrentPlugin())}},{key:"getMutationsForPlugin",value:function(e){var t=this.getPluginMutationIndex(e);return this.getMutations(t+1)}},{key:"getCurrentPlugin",value:function(){return this.currentPlugin}},{key:"getLib",value:function(){return this.libMethods}},{key:"_get",value:function(e){return it.getIn(this.state,e)}},{key:"_getContext",value:function(e){return this.contextTree.get(e)}},{key:"setContext",value:function(e,t){return this.contextTree.set(e,t)}},{key:"_hasRun",value:function(e){return this.getPluginRunCount(this.getCurrentPlugin())>(e||0)}},{key:"dispatch",value:function(){var e,t=this,r=this,n=this.nextPlugin();if(!n){var o=this.nextPromisedPatch();if(o)return o.then((function(){return t.dispatch()})).catch((function(){return t.dispatch()}));var a={spec:this.state,errors:this.errors};return this.showDebug&&(a.patches=this.allPatches),Ae().resolve(a)}if(r.pluginCount=r.pluginCount||{},r.pluginCount[n]=(r.pluginCount[n]||0)+1,r.pluginCount[n]>100)return Ae().resolve({spec:r.state,errors:j()(e=r.errors).call(e,new Error("We've reached a hard limit of ".concat(100," plugin runs")))});if(n!==this.currentPlugin&&this.promisedPatches.length){var i,s=A()(i=this.promisedPatches).call(i,(function(e){return e.value}));return Ae().all(A()(s).call(s,(function(e){return e.then(sr,sr)}))).then((function(){return t.dispatch()}))}return function(){r.currentPlugin=n;var e=r.getCurrentMutations(),t=r.mutations.length-1;try{if(n.isGenerator){var o,a=p()(n(e,r.getLib()));try{for(a.s();!(o=a.n()).done;){l(o.value)}}catch(e){a.e(e)}finally{a.f()}}else{l(n(e,r.getLib()))}}catch(e){console.error(e),l([Ee()(Object.create(e),{plugin:n})])}finally{r.updatePluginHistory(n,{mutationIndex:t})}return r.dispatch()}();function l(e){e&&(e=it.fullyNormalizeArray(e),r.updatePatches(e,n))}}}],[{key:"getPluginName",value:function(e){return e.pluginName}},{key:"getPatchesOfType",value:function(e,t){return P()(e).call(e,t)}}]),e}();var ur={refs:$t,allOf:tr,parameters:rr,properties:nr},cr=r(23159);function pr(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.requestInterceptor,n=t.responseInterceptor,o=e.withCredentials?"include":"same-origin";return function(t){return e({url:t,loadSpec:!0,requestInterceptor:r,responseInterceptor:n,headers:{Accept:Dt},credentials:o}).then((function(e){return e.body}))}}function fr(e){var t=e.fetch,r=e.spec,n=e.url,o=e.mode,a=e.allowMetaPatches,i=void 0===a||a,l=e.pathDiscriminator,c=e.modelPropertyMacro,p=e.parameterMacro,f=e.requestInterceptor,h=e.responseInterceptor,d=e.skipNormalization,m=e.useCircularStructures,g=e.http,v=e.baseDoc;return v=v||n,g=t||g||Y,r?y(r):pr(g,{requestInterceptor:f,responseInterceptor:h})(v).then(y);function y(e){v&&(ur.refs.docCache[v]=e),ur.refs.fetchJSON=pr(g,{requestInterceptor:f,responseInterceptor:h});var t,r=[ur.refs];return"function"==typeof p&&r.push(ur.parameters),"function"==typeof c&&r.push(ur.properties),"strict"!==o&&r.push(ur.allOf),(t={spec:e,context:{baseDoc:v},plugins:r,allowMetaPatches:i,pathDiscriminator:l,parameterMacro:p,modelPropertyMacro:c,useCircularStructures:m},new lr(t).dispatch()).then(d?function(){var e=s()(u().mark((function e(t){return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t);case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}():cr.K1)}}var hr=r(88436),dr=r.n(hr),mr=r(27361),gr=r.n(mr),vr=r(76489);function yr(e){return"[object Object]"===Object.prototype.toString.call(e)}function br(e){var t,r;return!1!==yr(e)&&(void 0===(t=e.constructor)||!1!==yr(r=t.prototype)&&!1!==r.hasOwnProperty("isPrototypeOf"))}const wr={body:function(e){var t=e.req,r=e.value;t.body=r},header:function(e){var t=e.req,r=e.parameter,n=e.value;t.headers=t.headers||{},void 0!==n&&(t.headers[r.name]=n)},query:function(e){var t=e.req,r=e.value,n=e.parameter;t.query=t.query||{},!1===r&&"boolean"===n.type&&(r="false");0===r&&["number","integer"].indexOf(n.type)>-1&&(r="0");if(r)t.query[n.name]={collectionFormat:n.collectionFormat,value:r};else if(n.allowEmptyValue&&void 0!==r){var o=n.name;t.query[o]=t.query[o]||{},t.query[o].allowEmptyValue=!0}},path:function(e){var t=e.req,r=e.value,n=e.parameter;t.url=t.url.split("{".concat(n.name,"}")).join(encodeURIComponent(r))},formData:function(e){var t=e.req,r=e.value,n=e.parameter;(r||n.allowEmptyValue)&&(t.form=t.form||{},t.form[n.name]={value:r,allowEmptyValue:n.allowEmptyValue,collectionFormat:n.collectionFormat})}};function Er(e,t){return v()(t).call(t,"application/json")?"string"==typeof e?e:_()(e):e.toString()}function xr(e){var t=e.req,r=e.value,n=e.parameter,o=n.name,a=n.style,i=n.explode,s=n.content;if(s){var l=C()(s)[0];t.url=t.url.split("{".concat(o,"}")).join(J(Er(r,l),{escape:!0}))}else{var u=K({key:n.name,value:r,style:a||"simple",explode:i||!1,escape:!0});t.url=t.url.split("{".concat(o,"}")).join(u)}}function _r(e){var t=e.req,r=e.value,n=e.parameter;if(t.query=t.query||{},n.content){var o=C()(n.content)[0];t.query[n.name]=Er(r,o)}else if(!1===r&&(r="false"),0===r&&(r="0"),r){var a=n.style,i=n.explode,s=n.allowReserved;t.query[n.name]={value:r,serializationOption:{style:a,explode:i,allowReserved:s}}}else if(n.allowEmptyValue&&void 0!==r){var l=n.name;t.query[l]=t.query[l]||{},t.query[l].allowEmptyValue=!0}}var Sr=["accept","authorization","content-type"];function Ar(e){var t=e.req,r=e.parameter,n=e.value;if(t.headers=t.headers||{},!(Sr.indexOf(r.name.toLowerCase())>-1))if(r.content){var o=C()(r.content)[0];t.headers[r.name]=Er(n,o)}else void 0!==n&&(t.headers[r.name]=K({key:r.name,value:n,style:r.style||"simple",explode:void 0!==r.explode&&r.explode,escape:!1}))}function kr(e){var t=e.req,r=e.parameter,n=e.value;t.headers=t.headers||{};var o=h()(n);if(r.content){var a,i=C()(r.content)[0];t.headers.Cookie=j()(a="".concat(r.name,"=")).call(a,Er(n,i))}else if("undefined"!==o){var s="object"===o&&!Array.isArray(n)&&r.explode?"":"".concat(r.name,"=");t.headers.Cookie=s+K({key:r.name,value:n,escape:!1,style:r.style||"form",explode:void 0!==r.explode&&r.explode})}}var Cr=r(92381),Or=r.n(Cr);const jr=(void 0!==Or()?Or():"undefined"!=typeof self?self:window).btoa;function Ir(e,t){var r=e.operation,n=e.requestBody,o=e.securities,a=e.spec,i=e.attachContentTypeForEmptyPayload,s=e.requestContentType;t=function(e){var t=e.request,r=e.securities,n=void 0===r?{}:r,o=e.operation,a=void 0===o?{}:o,i=e.spec,s=me()({},t),l=n.authorized,u=void 0===l?{}:l,c=a.security||i.security||[],p=u&&!!C()(u).length,f=gr()(i,["components","securitySchemes"])||{};if(s.headers=s.headers||{},s.query=s.query||{},!C()(n).length||!p||!c||Array.isArray(a.security)&&!a.security.length)return t;return c.forEach((function(e){C()(e).forEach((function(e){var t=u[e],r=f[e];if(t){var n=t.value||t,o=r.type;if(t)if("apiKey"===o)"query"===r.in&&(s.query[r.name]=n),"header"===r.in&&(s.headers[r.name]=n),"cookie"===r.in&&(s.cookies[r.name]=n);else if("http"===o){if(/^basic$/i.test(r.scheme)){var a,i=n.username||"",l=n.password||"",c=jr(j()(a="".concat(i,":")).call(a,l));s.headers.Authorization="Basic ".concat(c)}/^bearer$/i.test(r.scheme)&&(s.headers.Authorization="Bearer ".concat(n))}else if("oauth2"===o||"openIdConnect"===o){var p,h=t.token||{},d=h[r["x-tokenName"]||"access_token"],m=h.token_type;m&&"bearer"!==m.toLowerCase()||(m="Bearer"),s.headers.Authorization=j()(p="".concat(m," ")).call(p,d)}}}))})),s}({request:t,securities:o,operation:r,spec:a});var l=r.requestBody||{},u=C()(l.content||{}),c=s&&u.indexOf(s)>-1;if(n||i){if(s&&c)t.headers["Content-Type"]=s;else if(!s){var p=u[0];p&&(t.headers["Content-Type"]=p,s=p)}}else s&&c&&(t.headers["Content-Type"]=s);if(!e.responseContentType&&r.responses){var f,d=P()(f=N()(r.responses)).call(f,(function(e){var t=m()(e,2),r=t[0],n=t[1],o=parseInt(r,10);return o>=200&&o<300&&br(n.content)})).reduce((function(e,t){var r=m()(t,2)[1];return j()(e).call(e,C()(r.content))}),[]);d.length>0&&(t.headers.accept=d.join(", "))}if(n)if(s){if(u.indexOf(s)>-1)if("application/x-www-form-urlencoded"===s||"multipart/form-data"===s)if("object"===h()(n)){var g=(l.content[s]||{}).encoding||{};t.form={},C()(n).forEach((function(e){t.form[e]={value:n[e],encoding:g[e]||{}}}))}else t.form=n;else t.body=n}else t.body=n;return t}function Nr(e,t){var r,n,o=e.spec,a=e.operation,i=e.securities,s=e.requestContentType,l=e.responseContentType,u=e.attachContentTypeForEmptyPayload;if(t=function(e){var t=e.request,r=e.securities,n=void 0===r?{}:r,o=e.operation,a=void 0===o?{}:o,i=e.spec,s=me()({},t),l=n.authorized,u=void 0===l?{}:l,c=n.specSecurity,p=void 0===c?[]:c,f=a.security||p,h=u&&!!C()(u).length,d=i.securityDefinitions;if(s.headers=s.headers||{},s.query=s.query||{},!C()(n).length||!h||!f||Array.isArray(a.security)&&!a.security.length)return t;return f.forEach((function(e){C()(e).forEach((function(e){var t=u[e];if(t){var r=t.token,n=t.value||t,o=d[e],a=o.type,i=o["x-tokenName"]||"access_token",l=r&&r[i],c=r&&r.token_type;if(t)if("apiKey"===a){var p="query"===o.in?"query":"headers";s[p]=s[p]||{},s[p][o.name]=n}else if("basic"===a)if(n.header)s.headers.authorization=n.header;else{var f,h=n.username||"",m=n.password||"";n.base64=jr(j()(f="".concat(h,":")).call(f,m)),s.headers.authorization="Basic ".concat(n.base64)}else if("oauth2"===a&&l){var g;c=c&&"bearer"!==c.toLowerCase()?c:"Bearer",s.headers.authorization=j()(g="".concat(c," ")).call(g,l)}}}))})),s}({request:t,securities:i,operation:a,spec:o}),t.body||t.form||u)if(s)t.headers["Content-Type"]=s;else if(Array.isArray(a.consumes)){var c=m()(a.consumes,1);t.headers["Content-Type"]=c[0]}else if(Array.isArray(o.consumes)){var p=m()(o.consumes,1);t.headers["Content-Type"]=p[0]}else a.parameters&&P()(r=a.parameters).call(r,(function(e){return"file"===e.type})).length?t.headers["Content-Type"]="multipart/form-data":a.parameters&&P()(n=a.parameters).call(n,(function(e){return"formData"===e.in})).length&&(t.headers["Content-Type"]="application/x-www-form-urlencoded");else if(s){var f,h,d=a.parameters&&P()(f=a.parameters).call(f,(function(e){return"body"===e.in})).length>0,g=a.parameters&&P()(h=a.parameters).call(h,(function(e){return"formData"===e.in})).length>0;(d||g)&&(t.headers["Content-Type"]=s)}return!l&&Array.isArray(a.produces)&&a.produces.length>0&&(t.headers.accept=a.produces.join(", ")),t}var Tr=["http","fetch","spec","operationId","pathName","method","parameters","securities"],Pr=function(e){return Array.isArray(e)?e:[]},Rr=Ct("OperationNotFoundError",(function(e,t,r){this.originalError=r,Ee()(this,t||{})})),Mr={buildRequest:Lr};function Dr(e){var t=e.http,r=e.fetch,n=e.spec,o=e.operationId,a=e.pathName,i=e.method,s=e.parameters,l=e.securities,u=dr()(e,Tr),c=t||r||Y;a&&i&&!o&&(o=(0,cr.nc)(a,i));var p=Mr.buildRequest(me()({spec:n,operationId:o,parameters:s,securities:l,http:c},u));return p.body&&(br(p.body)||Array.isArray(p.body))&&(p.body=_()(p.body)),c(p)}function Lr(e){var t,r,n=e.spec,o=e.operationId,i=e.responseContentType,s=e.scheme,l=e.requestInterceptor,u=e.responseInterceptor,c=e.contextUrl,p=e.userFetch,f=e.server,h=e.serverVariables,d=e.http,g=e.signal,v=e.parameters,y=e.parameterBuilders,b=(0,cr.z6)(n);y||(y=b?a:wr);var w={url:"",credentials:d&&d.withCredentials?"include":"same-origin",headers:{},cookies:{}};g&&(w.signal=g),l&&(w.requestInterceptor=l),u&&(w.responseInterceptor=u),p&&(w.userFetch=p);var E=(0,cr.$r)(n,o);if(!E)throw new Rr("Operation ".concat(o," not found"));var x,_=E.operation,S=void 0===_?{}:_,k=E.method,O=E.pathName;if(w.url+=(x={spec:n,scheme:s,contextUrl:c,server:f,serverVariables:h,pathName:O,method:k},(0,cr.z6)(x.spec)?function(e){var t=e.spec,r=e.pathName,n=e.method,o=e.server,a=e.contextUrl,i=e.serverVariables,s=void 0===i?{}:i,l=gr()(t,["paths",r,(n||"").toLowerCase(),"servers"])||gr()(t,["paths",r,"servers"])||gr()(t,["servers"]),u="",c=null;if(o&&l&&l.length){var p=A()(l).call(l,(function(e){return e.url}));p.indexOf(o)>-1&&(u=o,c=l[p.indexOf(o)])}if(!u&&l&&l.length){u=l[0].url;var f=m()(l,1);c=f[0]}return u.indexOf("{")>-1&&function(e){for(var t,r=[],n=/{([^}]+)}/g;t=n.exec(e);)r.push(t[1]);return r}(u).forEach((function(e){if(c.variables&&c.variables[e]){var t=c.variables[e],r=s[e]||t.default,n=new RegExp("{".concat(e,"}"),"g");u=u.replace(n,r)}})),function(){var e,t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",o=r&&n?kt.parse(kt.resolve(n,r)):kt.parse(r),a=kt.parse(n),i=Br(o.protocol)||Br(a.protocol)||"",s=o.host||a.host,l=o.pathname||"";return"/"===(e=i&&s?j()(t="".concat(i,"://")).call(t,s+l):l)[e.length-1]?$()(e).call(e,0,-1):e}(u,a)}(x):function(e){var t,r,n=e.spec,o=e.scheme,a=e.contextUrl,i=void 0===a?"":a,s=kt.parse(i),l=Array.isArray(n.schemes)?n.schemes[0]:null,u=o||l||Br(s.protocol)||"http",c=n.host||s.host||"",p=n.basePath||"";return"/"===(t=u&&c?j()(r="".concat(u,"://")).call(r,c+p):p)[t.length-1]?$()(t).call(t,0,-1):t}(x)),!o)return delete w.cookies,w;w.url+=O,w.method="".concat(k).toUpperCase(),v=v||{};var I=n.paths[O]||{};i&&(w.headers.accept=i);var N=function(e){var t={};e.forEach((function(e){t[e.in]||(t[e.in]={}),t[e.in][e.name]=e}));var r=[];return C()(t).forEach((function(e){C()(t[e]).forEach((function(n){r.push(t[e][n])}))})),r}(j()(t=j()(r=[]).call(r,Pr(S.parameters))).call(t,Pr(I.parameters)));N.forEach((function(e){var t,r,o=y[e.in];if("body"===e.in&&e.schema&&e.schema.properties&&(t=v),void 0===(t=e&&e.name&&v[e.name]))t=e&&e.name&&v[j()(r="".concat(e.in,".")).call(r,e.name)];else if(function(e,t){return P()(t).call(t,(function(t){return t.name===e}))}(e.name,N).length>1){var a;console.warn(j()(a="Parameter '".concat(e.name,"' is ambiguous because the defined spec has more than one parameter with the name: '")).call(a,e.name,"' and the passed-in parameter values did not define an 'in' value."))}if(null!==t){if(void 0!==e.default&&void 0===t&&(t=e.default),void 0===t&&e.required&&!e.allowEmptyValue)throw new Error("Required parameter ".concat(e.name," is not provided"));if(b&&e.schema&&"object"===e.schema.type&&"string"==typeof t)try{t=JSON.parse(t)}catch(e){throw new Error("Could not parse object parameter value string as JSON")}o&&o({req:w,parameter:e,value:t,operation:S,spec:n})}}));var T=me()(me()({},e),{},{operation:S});if((w=b?Ir(T,w):Nr(T,w)).cookies&&C()(w.cookies).length){var R=C()(w.cookies).reduce((function(e,t){var r=w.cookies[t];return e+(e?"&":"")+vr.serialize(t,r)}),"");w.headers.Cookie=R}return w.cookies&&delete w.cookies,fe(w),w}var Br=function(e){return e?e.replace(/\W/g,""):null};function Fr(e,t){return zr.apply(this,arguments)}function zr(){return zr=s()(u().mark((function e(t,r){var n,o,a,i,s,l,c,p,f,h,d,m,g=arguments;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=g.length>2&&void 0!==g[2]?g[2]:{},o=n.returnEntireTree,a=n.baseDoc,i=n.requestInterceptor,s=n.responseInterceptor,l=n.parameterMacro,c=n.modelPropertyMacro,p=n.useCircularStructures,f={pathDiscriminator:r,baseDoc:a,requestInterceptor:i,responseInterceptor:s,parameterMacro:l,modelPropertyMacro:c,useCircularStructures:p},h=(0,cr.K1)({spec:t}),d=h.spec,e.next=6,fr(me()(me()({},f),{},{spec:d,allowMetaPatches:!0,skipNormalization:!0}));case 6:return m=e.sent,!o&&Array.isArray(r)&&r.length&&(m.spec=gr()(m.spec,r)||null),e.abrupt("return",m);case 9:case"end":return e.stop()}}),e)}))),zr.apply(this,arguments)}var Ur=r(34852);function qr(e){let{configs:t,getConfigs:r}=e;return{fn:{fetch:(n=Y,o=t.preFetch,a=t.postFetch,a=a||function(e){return e},o=o||function(e){return e},function(e){return"string"==typeof e&&(e={url:e}),Z.mergeInQueryOrForm(e),e=o(e),a(n(e))}),buildRequest:Lr,execute:Dr,resolve:fr,resolveSubtree:function(e,t,n){if(void 0===n){const e=r();n={modelPropertyMacro:e.modelPropertyMacro,parameterMacro:e.parameterMacro,requestInterceptor:e.requestInterceptor,responseInterceptor:e.responseInterceptor}}for(var o=arguments.length,a=new Array(o>3?o-3:0),i=3;i{"use strict";r.r(t),r.d(t,{default:()=>o});var n=r(90242);function o(){return{fn:{shallowEqualKeys:n.be}}}},48347:(e,t,r)=>{"use strict";r.r(t),r.d(t,{getDisplayName:()=>n});const n=e=>e.displayName||e.name||"Component"},73420:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u});var n=r(35627),o=r.n(n),a=r(90242),i=r(55776),s=r(48347),l=r(60314);const u=e=>{let{getComponents:t,getStore:r,getSystem:n}=e;const u=(c=(0,i.getComponent)(n,r,t),(0,a.HP)(c,(function(){for(var e=arguments.length,t=new Array(e),r=0;r(0,l.Z)(e,(function(){for(var e=arguments.length,t=new Array(e),r=0;r{"use strict";r.r(t),r.d(t,{getComponent:()=>ne,render:()=>re,withMappedContainer:()=>te});var n=r(23101),o=r.n(n),a=r(28222),i=r.n(a),s=r(67294),l=r(73935),u=r(97779),c=s.createContext(null);var p=function(e){e()},f=function(){return p},h={notify:function(){}};var d=function(){function e(e,t){this.store=e,this.parentSub=t,this.unsubscribe=null,this.listeners=h,this.handleChangeWrapper=this.handleChangeWrapper.bind(this)}var t=e.prototype;return t.addNestedSub=function(e){return this.trySubscribe(),this.listeners.subscribe(e)},t.notifyNestedSubs=function(){this.listeners.notify()},t.handleChangeWrapper=function(){this.onStateChange&&this.onStateChange()},t.isSubscribed=function(){return Boolean(this.unsubscribe)},t.trySubscribe=function(){this.unsubscribe||(this.unsubscribe=this.parentSub?this.parentSub.addNestedSub(this.handleChangeWrapper):this.store.subscribe(this.handleChangeWrapper),this.listeners=function(){var e=f(),t=null,r=null;return{clear:function(){t=null,r=null},notify:function(){e((function(){for(var e=t;e;)e.callback(),e=e.next}))},get:function(){for(var e=[],r=t;r;)e.push(r),r=r.next;return e},subscribe:function(e){var n=!0,o=r={callback:e,next:null,prev:r};return o.prev?o.prev.next=o:t=o,function(){n&&null!==t&&(n=!1,o.next?o.next.prev=o.prev:r=o.prev,o.prev?o.prev.next=o.next:t=o.next)}}}}())},t.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.listeners.clear(),this.listeners=h)},e}(),m="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement?s.useLayoutEffect:s.useEffect;const g=function(e){var t=e.store,r=e.context,n=e.children,o=(0,s.useMemo)((function(){var e=new d(t);return e.onStateChange=e.notifyNestedSubs,{store:t,subscription:e}}),[t]),a=(0,s.useMemo)((function(){return t.getState()}),[t]);m((function(){var e=o.subscription;return e.trySubscribe(),a!==t.getState()&&e.notifyNestedSubs(),function(){e.tryUnsubscribe(),e.onStateChange=null}}),[o,a]);var i=r||c;return s.createElement(i.Provider,{value:o},n)};var v=r(87462),y=r(63366),b=r(8679),w=r.n(b),E=r(72973),x=[],_=[null,null];function S(e,t){var r=e[1];return[t.payload,r+1]}function A(e,t,r){m((function(){return e.apply(void 0,t)}),r)}function k(e,t,r,n,o,a,i){e.current=n,t.current=o,r.current=!1,a.current&&(a.current=null,i())}function C(e,t,r,n,o,a,i,s,l,u){if(e){var c=!1,p=null,f=function(){if(!c){var e,r,f=t.getState();try{e=n(f,o.current)}catch(e){r=e,p=e}r||(p=null),e===a.current?i.current||l():(a.current=e,s.current=e,i.current=!0,u({type:"STORE_UPDATED",payload:{error:r}}))}};r.onStateChange=f,r.trySubscribe(),f();return function(){if(c=!0,r.tryUnsubscribe(),r.onStateChange=null,p)throw p}}}var O=function(){return[null,0]};function j(e,t){void 0===t&&(t={});var r=t,n=r.getDisplayName,o=void 0===n?function(e){return"ConnectAdvanced("+e+")"}:n,a=r.methodName,i=void 0===a?"connectAdvanced":a,l=r.renderCountProp,u=void 0===l?void 0:l,p=r.shouldHandleStateChanges,f=void 0===p||p,h=r.storeKey,m=void 0===h?"store":h,g=(r.withRef,r.forwardRef),b=void 0!==g&&g,j=r.context,I=void 0===j?c:j,N=(0,y.Z)(r,["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef","forwardRef","context"]),T=I;return function(t){var r=t.displayName||t.name||"Component",n=o(r),a=(0,v.Z)({},N,{getDisplayName:o,methodName:i,renderCountProp:u,shouldHandleStateChanges:f,storeKey:m,displayName:n,wrappedComponentName:r,WrappedComponent:t}),l=N.pure;var c=l?s.useMemo:function(e){return e()};function p(r){var n=(0,s.useMemo)((function(){var e=r.reactReduxForwardedRef,t=(0,y.Z)(r,["reactReduxForwardedRef"]);return[r.context,e,t]}),[r]),o=n[0],i=n[1],l=n[2],u=(0,s.useMemo)((function(){return o&&o.Consumer&&(0,E.isContextConsumer)(s.createElement(o.Consumer,null))?o:T}),[o,T]),p=(0,s.useContext)(u),h=Boolean(r.store)&&Boolean(r.store.getState)&&Boolean(r.store.dispatch);Boolean(p)&&Boolean(p.store);var m=h?r.store:p.store,g=(0,s.useMemo)((function(){return function(t){return e(t.dispatch,a)}(m)}),[m]),b=(0,s.useMemo)((function(){if(!f)return _;var e=new d(m,h?null:p.subscription),t=e.notifyNestedSubs.bind(e);return[e,t]}),[m,h,p]),w=b[0],j=b[1],I=(0,s.useMemo)((function(){return h?p:(0,v.Z)({},p,{subscription:w})}),[h,p,w]),N=(0,s.useReducer)(S,x,O),P=N[0][0],R=N[1];if(P&&P.error)throw P.error;var M=(0,s.useRef)(),D=(0,s.useRef)(l),L=(0,s.useRef)(),B=(0,s.useRef)(!1),F=c((function(){return L.current&&l===D.current?L.current:g(m.getState(),l)}),[m,P,l]);A(k,[D,M,B,l,F,L,j]),A(C,[f,m,w,g,D,M,B,L,j,R],[m,w,g]);var z=(0,s.useMemo)((function(){return s.createElement(t,(0,v.Z)({},F,{ref:i}))}),[i,t,F]);return(0,s.useMemo)((function(){return f?s.createElement(u.Provider,{value:I},z):z}),[u,z,I])}var h=l?s.memo(p):p;if(h.WrappedComponent=t,h.displayName=p.displayName=n,b){var g=s.forwardRef((function(e,t){return s.createElement(h,(0,v.Z)({},e,{reactReduxForwardedRef:t}))}));return g.displayName=n,g.WrappedComponent=t,w()(g,t)}return w()(h,t)}}function I(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!=e&&t!=t}function N(e,t){if(I(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(var o=0;o=0;n--){var o=t[n](e);if(o)return o}return function(t,n){throw new Error("Invalid value of type "+typeof e+" for "+r+" argument when connecting component "+n.wrappedComponentName+".")}}function V(e,t){return e===t}function $(e){var t=void 0===e?{}:e,r=t.connectHOC,n=void 0===r?j:r,o=t.mapStateToPropsFactories,a=void 0===o?D:o,i=t.mapDispatchToPropsFactories,s=void 0===i?M:i,l=t.mergePropsFactories,u=void 0===l?B:l,c=t.selectorFactory,p=void 0===c?U:c;return function(e,t,r,o){void 0===o&&(o={});var i=o,l=i.pure,c=void 0===l||l,f=i.areStatesEqual,h=void 0===f?V:f,d=i.areOwnPropsEqual,m=void 0===d?N:d,g=i.areStatePropsEqual,b=void 0===g?N:g,w=i.areMergedPropsEqual,E=void 0===w?N:w,x=(0,y.Z)(i,["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"]),_=q(e,a,"mapStateToProps"),S=q(t,s,"mapDispatchToProps"),A=q(r,u,"mergeProps");return n(p,(0,v.Z)({methodName:"connect",getDisplayName:function(e){return"Connect("+e+")"},shouldHandleStateChanges:Boolean(e),initMapStateToProps:_,initMapDispatchToProps:S,initMergeProps:A,pure:c,areStatesEqual:h,areOwnPropsEqual:m,areStatePropsEqual:b,areMergedPropsEqual:E},x))}}const W=$();var H;H=l.unstable_batchedUpdates,p=H;var J=r(57557),K=r.n(J),G=r(6557),Z=r.n(G);const Y=e=>t=>{const{fn:r}=e();class n extends s.Component{render(){return s.createElement(t,o()({},e(),this.props,this.context))}}return n.displayName=`WithSystem(${r.getDisplayName(t)})`,n},Q=(e,t)=>r=>{const{fn:n}=e();class a extends s.Component{render(){return s.createElement(g,{store:t},s.createElement(r,o()({},this.props,this.context)))}}return a.displayName=`WithRoot(${n.getDisplayName(r)})`,a},X=(e,t,r)=>(0,u.qC)(r?Q(e,r):Z(),W(((r,n)=>{var o;const a={...n,...e()},i=(null===(o=t.prototype)||void 0===o?void 0:o.mapStateToProps)||(e=>({state:e}));return i(r,a)})),Y(e))(t),ee=(e,t,r,n)=>{for(const o in t){const a=t[o];"function"==typeof a&&a(r[o],n[o],e())}},te=(e,t,r)=>(t,n)=>{const{fn:o}=e(),a=r(t,"root");class l extends s.Component{constructor(t,r){super(t,r),ee(e,n,t,{})}UNSAFE_componentWillReceiveProps(t){ee(e,n,t,this.props)}render(){const e=K()(this.props,n?i()(n):[]);return s.createElement(a,e)}}return l.displayName=`WithMappedContainer(${o.getDisplayName(a)})`,l},re=(e,t,r,n)=>o=>{const a=r(e,t,n)("App","root");l.render(s.createElement(a,null),o)},ne=(e,t,r)=>function(n,o){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("string"!=typeof n)throw new TypeError("Need a string, to fetch a component. Was given a "+typeof n);const i=r(n);return i?o?"root"===o?X(e,i,t()):X(e,i):i:(a.failSilently||e().log.warn("Could not find component:",n),null)}},33424:(e,t,r)=>{"use strict";r.d(t,{d3:()=>D,C2:()=>ee});var n=r(28222),o=r.n(n),a=r(58118),i=r.n(a),s=r(63366);function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=4?[t[0],t[1],t[2],t[3],"".concat(t[0],".").concat(t[1]),"".concat(t[0],".").concat(t[2]),"".concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[0]),"".concat(t[1],".").concat(t[2]),"".concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[1]),"".concat(t[2],".").concat(t[3]),"".concat(t[3],".").concat(t[0]),"".concat(t[3],".").concat(t[1]),"".concat(t[3],".").concat(t[2]),"".concat(t[0],".").concat(t[1],".").concat(t[2]),"".concat(t[0],".").concat(t[1],".").concat(t[3]),"".concat(t[0],".").concat(t[2],".").concat(t[1]),"".concat(t[0],".").concat(t[2],".").concat(t[3]),"".concat(t[0],".").concat(t[3],".").concat(t[1]),"".concat(t[0],".").concat(t[3],".").concat(t[2]),"".concat(t[1],".").concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[2],".").concat(t[0]),"".concat(t[1],".").concat(t[2],".").concat(t[3]),"".concat(t[1],".").concat(t[3],".").concat(t[0]),"".concat(t[1],".").concat(t[3],".").concat(t[2]),"".concat(t[2],".").concat(t[0],".").concat(t[1]),"".concat(t[2],".").concat(t[0],".").concat(t[3]),"".concat(t[2],".").concat(t[1],".").concat(t[0]),"".concat(t[2],".").concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[3],".").concat(t[0]),"".concat(t[2],".").concat(t[3],".").concat(t[1]),"".concat(t[3],".").concat(t[0],".").concat(t[1]),"".concat(t[3],".").concat(t[0],".").concat(t[2]),"".concat(t[3],".").concat(t[1],".").concat(t[0]),"".concat(t[3],".").concat(t[1],".").concat(t[2]),"".concat(t[3],".").concat(t[2],".").concat(t[0]),"".concat(t[3],".").concat(t[2],".").concat(t[1]),"".concat(t[0],".").concat(t[1],".").concat(t[2],".").concat(t[3]),"".concat(t[0],".").concat(t[1],".").concat(t[3],".").concat(t[2]),"".concat(t[0],".").concat(t[2],".").concat(t[1],".").concat(t[3]),"".concat(t[0],".").concat(t[2],".").concat(t[3],".").concat(t[1]),"".concat(t[0],".").concat(t[3],".").concat(t[1],".").concat(t[2]),"".concat(t[0],".").concat(t[3],".").concat(t[2],".").concat(t[1]),"".concat(t[1],".").concat(t[0],".").concat(t[2],".").concat(t[3]),"".concat(t[1],".").concat(t[0],".").concat(t[3],".").concat(t[2]),"".concat(t[1],".").concat(t[2],".").concat(t[0],".").concat(t[3]),"".concat(t[1],".").concat(t[2],".").concat(t[3],".").concat(t[0]),"".concat(t[1],".").concat(t[3],".").concat(t[0],".").concat(t[2]),"".concat(t[1],".").concat(t[3],".").concat(t[2],".").concat(t[0]),"".concat(t[2],".").concat(t[0],".").concat(t[1],".").concat(t[3]),"".concat(t[2],".").concat(t[0],".").concat(t[3],".").concat(t[1]),"".concat(t[2],".").concat(t[1],".").concat(t[0],".").concat(t[3]),"".concat(t[2],".").concat(t[1],".").concat(t[3],".").concat(t[0]),"".concat(t[2],".").concat(t[3],".").concat(t[0],".").concat(t[1]),"".concat(t[2],".").concat(t[3],".").concat(t[1],".").concat(t[0]),"".concat(t[3],".").concat(t[0],".").concat(t[1],".").concat(t[2]),"".concat(t[3],".").concat(t[0],".").concat(t[2],".").concat(t[1]),"".concat(t[3],".").concat(t[1],".").concat(t[0],".").concat(t[2]),"".concat(t[3],".").concat(t[1],".").concat(t[2],".").concat(t[0]),"".concat(t[3],".").concat(t[2],".").concat(t[0],".").concat(t[1]),"".concat(t[3],".").concat(t[2],".").concat(t[1],".").concat(t[0])]:void 0),m[n]}function v(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,n=e.filter((function(e){return"token"!==e})),o=g(n);return o.reduce((function(e,t){return d(d({},e),r[t])}),t)}function y(e){return e.join(" ")}function b(e){var t=e.node,r=e.stylesheet,n=e.style,o=void 0===n?{}:n,a=e.useInlineStyles,i=e.key,s=t.properties,l=t.type,u=t.tagName,c=t.value;if("text"===l)return c;if(u){var h,m=function(e,t){var r=0;return function(n){return r+=1,n.map((function(n,o){return b({node:n,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(r,"-").concat(o)})}))}}(r,a);if(a){var g=Object.keys(r).reduce((function(e,t){return t.split(".").forEach((function(t){e.includes(t)||e.push(t)})),e}),[]),w=s.className&&s.className.includes("token")?["token"]:[],E=s.className&&w.concat(s.className.filter((function(e){return!g.includes(e)})));h=d(d({},s),{},{className:y(E)||void 0,style:v(s.className,Object.assign({},s.style,o),r)})}else h=d(d({},s),{},{className:y(s.className)});var x=m(t.children);return p.createElement(u,(0,f.Z)({key:i},h),x)}}var w=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function E(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function x(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n=0;n2&&void 0!==arguments[2]?arguments[2]:[];return C({children:e,lineNumber:t,lineNumberStyle:s,largestLineNumber:i,showInlineLineNumbers:o,lineProps:r,className:a,showLineNumbers:n,wrapLongLines:l})}function m(e,t){if(n&&t&&o){var r=k(s,t,i);e.unshift(A(t,r))}return e}function g(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return t||n.length>0?d(e,r,n):m(e,r)}for(var v=function(){var e=c[h],t=e.children[0].value;if(t.match(_)){var r=t.split("\n");r.forEach((function(t,o){var i=n&&p.length+a,s={type:"text",value:"".concat(t,"\n")};if(0===o){var l=g(c.slice(f+1,h).concat(C({children:[s],className:e.properties.className})),i);p.push(l)}else if(o===r.length-1){var u=c[h+1]&&c[h+1].children&&c[h+1].children[0],d={type:"text",value:"".concat(t)};if(u){var m=C({children:[d],className:e.properties.className});c.splice(h+1,0,m)}else{var v=g([d],i,e.properties.className);p.push(v)}}else{var y=g([s],i,e.properties.className);p.push(y)}})),f=h}h++};h=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,w);q=q||T;var $=d?p.createElement(S,{containerStyle:b,codeStyle:u.style||{},numberStyle:_,startingLineNumber:y,codeString:U}):null,W=o.hljs||o['pre[class*="language-"]']||{backgroundColor:"#fff"},H=N(q)?"hljs":"prismjs",J=f?Object.assign({},V,{style:Object.assign({},W,i)}):Object.assign({},V,{className:V.className?"".concat(H," ").concat(V.className):H,style:Object.assign({},i)});if(u.style=x(x({},u.style),{},C?{whiteSpace:"pre-wrap"}:{whiteSpace:"pre"}),!q)return p.createElement(L,J,$,p.createElement(F,u,U));(void 0===A&&M||C)&&(A=!0),M=M||I;var K=[{type:"text",value:U}],G=function(e){var t=e.astGenerator,r=e.language,n=e.code,o=e.defaultCodeValue;if(N(t)){var a=function(e,t){return-1!==e.listLanguages().indexOf(t)}(t,r);return"text"===r?{value:o,language:"text"}:a?t.highlight(r,n):t.highlightAuto(n)}try{return r&&"text"!==r?{value:t.highlight(n,r)}:{value:o}}catch(e){return{value:o}}}({astGenerator:q,language:t,code:U,defaultCodeValue:K});null===G.language&&(G.value=K);var Z=j(G,A,R,d,g,y,G.value.length+y,_,C);return p.createElement(L,J,p.createElement(F,u,!g&&$,M({rows:Z,stylesheet:o,useInlineStyles:f})))});M.registerLanguage=R.registerLanguage;const D=M;var L=r(96344);const B=r.n(L)();var F=r(82026);const z=r.n(F)();var U=r(42157);const q=r.n(U)();var V=r(61519);const $=r.n(V)();var W=r(54587);const H=r.n(W)();var J=r(30786);const K=r.n(J)();var G=r(66336);const Z=r.n(G)(),Y={hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#333",color:"white"},"hljs-name":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-code":{fontStyle:"italic",color:"#888"},"hljs-emphasis":{fontStyle:"italic"},"hljs-tag":{color:"#62c8f3"},"hljs-variable":{color:"#ade5fc"},"hljs-template-variable":{color:"#ade5fc"},"hljs-selector-id":{color:"#ade5fc"},"hljs-selector-class":{color:"#ade5fc"},"hljs-string":{color:"#a2fca2"},"hljs-bullet":{color:"#d36363"},"hljs-type":{color:"#ffa"},"hljs-title":{color:"#ffa"},"hljs-section":{color:"#ffa"},"hljs-attribute":{color:"#ffa"},"hljs-quote":{color:"#ffa"},"hljs-built_in":{color:"#ffa"},"hljs-builtin-name":{color:"#ffa"},"hljs-number":{color:"#d36363"},"hljs-symbol":{color:"#d36363"},"hljs-keyword":{color:"#fcc28c"},"hljs-selector-tag":{color:"#fcc28c"},"hljs-literal":{color:"#fcc28c"},"hljs-comment":{color:"#888"},"hljs-deletion":{color:"#333",backgroundColor:"#fc9b9b"},"hljs-regexp":{color:"#c6b4f0"},"hljs-link":{color:"#c6b4f0"},"hljs-meta":{color:"#fc9b9b"},"hljs-addition":{backgroundColor:"#a2fca2",color:"#333"}};D.registerLanguage("json",z),D.registerLanguage("js",B),D.registerLanguage("xml",q),D.registerLanguage("yaml",H),D.registerLanguage("http",K),D.registerLanguage("bash",$),D.registerLanguage("powershell",Z),D.registerLanguage("javascript",B);const Q={agate:Y,arta:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#222",color:"#aaa"},"hljs-subst":{color:"#aaa"},"hljs-section":{color:"#fff",fontWeight:"bold"},"hljs-comment":{color:"#444"},"hljs-quote":{color:"#444"},"hljs-meta":{color:"#444"},"hljs-string":{color:"#ffcc33"},"hljs-symbol":{color:"#ffcc33"},"hljs-bullet":{color:"#ffcc33"},"hljs-regexp":{color:"#ffcc33"},"hljs-number":{color:"#00cc66"},"hljs-addition":{color:"#00cc66"},"hljs-built_in":{color:"#32aaee"},"hljs-builtin-name":{color:"#32aaee"},"hljs-literal":{color:"#32aaee"},"hljs-type":{color:"#32aaee"},"hljs-template-variable":{color:"#32aaee"},"hljs-attribute":{color:"#32aaee"},"hljs-link":{color:"#32aaee"},"hljs-keyword":{color:"#6644aa"},"hljs-selector-tag":{color:"#6644aa"},"hljs-name":{color:"#6644aa"},"hljs-selector-id":{color:"#6644aa"},"hljs-selector-class":{color:"#6644aa"},"hljs-title":{color:"#bb1166"},"hljs-variable":{color:"#bb1166"},"hljs-deletion":{color:"#bb1166"},"hljs-template-tag":{color:"#bb1166"},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},monokai:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#272822",color:"#ddd"},"hljs-tag":{color:"#f92672"},"hljs-keyword":{color:"#f92672",fontWeight:"bold"},"hljs-selector-tag":{color:"#f92672",fontWeight:"bold"},"hljs-literal":{color:"#f92672",fontWeight:"bold"},"hljs-strong":{color:"#f92672"},"hljs-name":{color:"#f92672"},"hljs-code":{color:"#66d9ef"},"hljs-class .hljs-title":{color:"white"},"hljs-attribute":{color:"#bf79db"},"hljs-symbol":{color:"#bf79db"},"hljs-regexp":{color:"#bf79db"},"hljs-link":{color:"#bf79db"},"hljs-string":{color:"#a6e22e"},"hljs-bullet":{color:"#a6e22e"},"hljs-subst":{color:"#a6e22e"},"hljs-title":{color:"#a6e22e",fontWeight:"bold"},"hljs-section":{color:"#a6e22e",fontWeight:"bold"},"hljs-emphasis":{color:"#a6e22e"},"hljs-type":{color:"#a6e22e",fontWeight:"bold"},"hljs-built_in":{color:"#a6e22e"},"hljs-builtin-name":{color:"#a6e22e"},"hljs-selector-attr":{color:"#a6e22e"},"hljs-selector-pseudo":{color:"#a6e22e"},"hljs-addition":{color:"#a6e22e"},"hljs-variable":{color:"#a6e22e"},"hljs-template-tag":{color:"#a6e22e"},"hljs-template-variable":{color:"#a6e22e"},"hljs-comment":{color:"#75715e"},"hljs-quote":{color:"#75715e"},"hljs-deletion":{color:"#75715e"},"hljs-meta":{color:"#75715e"},"hljs-doctag":{fontWeight:"bold"},"hljs-selector-id":{fontWeight:"bold"}},nord:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#2E3440",color:"#D8DEE9"},"hljs-subst":{color:"#D8DEE9"},"hljs-selector-tag":{color:"#81A1C1"},"hljs-selector-id":{color:"#8FBCBB",fontWeight:"bold"},"hljs-selector-class":{color:"#8FBCBB"},"hljs-selector-attr":{color:"#8FBCBB"},"hljs-selector-pseudo":{color:"#88C0D0"},"hljs-addition":{backgroundColor:"rgba(163, 190, 140, 0.5)"},"hljs-deletion":{backgroundColor:"rgba(191, 97, 106, 0.5)"},"hljs-built_in":{color:"#8FBCBB"},"hljs-type":{color:"#8FBCBB"},"hljs-class":{color:"#8FBCBB"},"hljs-function":{color:"#88C0D0"},"hljs-function > .hljs-title":{color:"#88C0D0"},"hljs-keyword":{color:"#81A1C1"},"hljs-literal":{color:"#81A1C1"},"hljs-symbol":{color:"#81A1C1"},"hljs-number":{color:"#B48EAD"},"hljs-regexp":{color:"#EBCB8B"},"hljs-string":{color:"#A3BE8C"},"hljs-title":{color:"#8FBCBB"},"hljs-params":{color:"#D8DEE9"},"hljs-bullet":{color:"#81A1C1"},"hljs-code":{color:"#8FBCBB"},"hljs-emphasis":{fontStyle:"italic"},"hljs-formula":{color:"#8FBCBB"},"hljs-strong":{fontWeight:"bold"},"hljs-link:hover":{textDecoration:"underline"},"hljs-quote":{color:"#4C566A"},"hljs-comment":{color:"#4C566A"},"hljs-doctag":{color:"#8FBCBB"},"hljs-meta":{color:"#5E81AC"},"hljs-meta-keyword":{color:"#5E81AC"},"hljs-meta-string":{color:"#A3BE8C"},"hljs-attr":{color:"#8FBCBB"},"hljs-attribute":{color:"#D8DEE9"},"hljs-builtin-name":{color:"#81A1C1"},"hljs-name":{color:"#81A1C1"},"hljs-section":{color:"#88C0D0"},"hljs-tag":{color:"#81A1C1"},"hljs-variable":{color:"#D8DEE9"},"hljs-template-variable":{color:"#D8DEE9"},"hljs-template-tag":{color:"#5E81AC"},"abnf .hljs-attribute":{color:"#88C0D0"},"abnf .hljs-symbol":{color:"#EBCB8B"},"apache .hljs-attribute":{color:"#88C0D0"},"apache .hljs-section":{color:"#81A1C1"},"arduino .hljs-built_in":{color:"#88C0D0"},"aspectj .hljs-meta":{color:"#D08770"},"aspectj > .hljs-title":{color:"#88C0D0"},"bnf .hljs-attribute":{color:"#8FBCBB"},"clojure .hljs-name":{color:"#88C0D0"},"clojure .hljs-symbol":{color:"#EBCB8B"},"coq .hljs-built_in":{color:"#88C0D0"},"cpp .hljs-meta-string":{color:"#8FBCBB"},"css .hljs-built_in":{color:"#88C0D0"},"css .hljs-keyword":{color:"#D08770"},"diff .hljs-meta":{color:"#8FBCBB"},"ebnf .hljs-attribute":{color:"#8FBCBB"},"glsl .hljs-built_in":{color:"#88C0D0"},"groovy .hljs-meta:not(:first-child)":{color:"#D08770"},"haxe .hljs-meta":{color:"#D08770"},"java .hljs-meta":{color:"#D08770"},"ldif .hljs-attribute":{color:"#8FBCBB"},"lisp .hljs-name":{color:"#88C0D0"},"lua .hljs-built_in":{color:"#88C0D0"},"moonscript .hljs-built_in":{color:"#88C0D0"},"nginx .hljs-attribute":{color:"#88C0D0"},"nginx .hljs-section":{color:"#5E81AC"},"pf .hljs-built_in":{color:"#88C0D0"},"processing .hljs-built_in":{color:"#88C0D0"},"scss .hljs-keyword":{color:"#81A1C1"},"stylus .hljs-keyword":{color:"#81A1C1"},"swift .hljs-meta":{color:"#D08770"},"vim .hljs-built_in":{color:"#88C0D0",fontStyle:"italic"},"yaml .hljs-meta":{color:"#D08770"}},obsidian:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#282b2e",color:"#e0e2e4"},"hljs-keyword":{color:"#93c763",fontWeight:"bold"},"hljs-selector-tag":{color:"#93c763",fontWeight:"bold"},"hljs-literal":{color:"#93c763",fontWeight:"bold"},"hljs-selector-id":{color:"#93c763"},"hljs-number":{color:"#ffcd22"},"hljs-attribute":{color:"#668bb0"},"hljs-code":{color:"white"},"hljs-class .hljs-title":{color:"white"},"hljs-section":{color:"white",fontWeight:"bold"},"hljs-regexp":{color:"#d39745"},"hljs-link":{color:"#d39745"},"hljs-meta":{color:"#557182"},"hljs-tag":{color:"#8cbbad"},"hljs-name":{color:"#8cbbad",fontWeight:"bold"},"hljs-bullet":{color:"#8cbbad"},"hljs-subst":{color:"#8cbbad"},"hljs-emphasis":{color:"#8cbbad"},"hljs-type":{color:"#8cbbad",fontWeight:"bold"},"hljs-built_in":{color:"#8cbbad"},"hljs-selector-attr":{color:"#8cbbad"},"hljs-selector-pseudo":{color:"#8cbbad"},"hljs-addition":{color:"#8cbbad"},"hljs-variable":{color:"#8cbbad"},"hljs-template-tag":{color:"#8cbbad"},"hljs-template-variable":{color:"#8cbbad"},"hljs-string":{color:"#ec7600"},"hljs-symbol":{color:"#ec7600"},"hljs-comment":{color:"#818e96"},"hljs-quote":{color:"#818e96"},"hljs-deletion":{color:"#818e96"},"hljs-selector-class":{color:"#A082BD"},"hljs-doctag":{fontWeight:"bold"},"hljs-title":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"}},"tomorrow-night":{"hljs-comment":{color:"#969896"},"hljs-quote":{color:"#969896"},"hljs-variable":{color:"#cc6666"},"hljs-template-variable":{color:"#cc6666"},"hljs-tag":{color:"#cc6666"},"hljs-name":{color:"#cc6666"},"hljs-selector-id":{color:"#cc6666"},"hljs-selector-class":{color:"#cc6666"},"hljs-regexp":{color:"#cc6666"},"hljs-deletion":{color:"#cc6666"},"hljs-number":{color:"#de935f"},"hljs-built_in":{color:"#de935f"},"hljs-builtin-name":{color:"#de935f"},"hljs-literal":{color:"#de935f"},"hljs-type":{color:"#de935f"},"hljs-params":{color:"#de935f"},"hljs-meta":{color:"#de935f"},"hljs-link":{color:"#de935f"},"hljs-attribute":{color:"#f0c674"},"hljs-string":{color:"#b5bd68"},"hljs-symbol":{color:"#b5bd68"},"hljs-bullet":{color:"#b5bd68"},"hljs-addition":{color:"#b5bd68"},"hljs-title":{color:"#81a2be"},"hljs-section":{color:"#81a2be"},"hljs-keyword":{color:"#b294bb"},"hljs-selector-tag":{color:"#b294bb"},hljs:{display:"block",overflowX:"auto",background:"#1d1f21",color:"#c5c8c6",padding:"0.5em"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}}},X=o()(Q),ee=e=>i()(X).call(X,e)?Q[e]:(console.warn(`Request style '${e}' is not available, returning default instead`),Y)},90242:(e,t,r)=>{"use strict";r.d(t,{mz:()=>pe,oG:()=>fe,AF:()=>he,LQ:()=>de,Kn:()=>me,Wl:()=>ge,kJ:()=>ve,HP:()=>ye,Ay:()=>be,Q2:()=>we,_5:()=>Ee,iQ:()=>xe,gp:()=>_e,DR:()=>Se,Zl:()=>Ae,Ik:()=>Ce,xi:()=>Pe,UG:()=>Re,r3:()=>Me,wh:()=>De,GZ:()=>Le,be:()=>Be,Nm:()=>Fe,hW:()=>ze,QG:()=>Ue,oJ:()=>qe,J6:()=>Ve,nX:()=>$e,po:()=>We,XV:()=>He,Pz:()=>Je,D$:()=>Ke,V9:()=>Ge,cz:()=>Ze,Uj:()=>Ye,Xb:()=>Qe,O2:()=>et});var n=r(58309),o=r.n(n),a=r(97606),i=r.n(a),s=r(74386),l=r.n(s),u=r(86),c=r.n(u),p=r(14418),f=r.n(p),h=r(28222),d=r.n(h),m=(r(11189),r(24282)),g=r.n(m),v=r(76986),y=r.n(v),b=r(2578),w=r.n(b),E=r(24278),x=r.n(E),_=(r(39022),r(92039)),S=r.n(_),A=(r(58118),r(35627)),k=r.n(A),C=r(11882),O=r.n(C),j=r(51679),I=r.n(j),N=r(27043),T=r.n(N),P=r(81607),R=r.n(P),M=r(43393),D=r.n(M),L=r(17967),B=r(68929),F=r.n(B),z=r(11700),U=r.n(z),q=r(88306),V=r.n(q),$=r(13311),W=r.n($),H=r(59704),J=r.n(H),K=r(77813),G=r.n(K),Z=r(23560),Y=r.n(Z),Q=r(57050),X=r(27504),ee=r(8269),te=r.n(ee),re=r(19069),ne=r(92282),oe=r.n(ne),ae=r(89072),ie=r.n(ae),se=r(1272),le=r(48764).Buffer;const ue="default",ce=e=>D().Iterable.isIterable(e);function pe(e){return me(e)?ce(e)?e.toJS():e:{}}function fe(e){var t,r;if(ce(e))return e;if(e instanceof X.Z.File)return e;if(!me(e))return e;if(o()(e))return i()(r=D().Seq(e)).call(r,fe).toList();if(Y()(l()(e))){var n;const t=function(e){if(!Y()(l()(e)))return e;const t={},r="_**[]",n={};for(let o of l()(e).call(e))if(t[o[0]]||n[o[0]]&&n[o[0]].containsMultiple){if(!n[o[0]]){n[o[0]]={containsMultiple:!0,length:1},t[`${o[0]}${r}${n[o[0]].length}`]=t[o[0]],delete t[o[0]]}n[o[0]].length+=1,t[`${o[0]}${r}${n[o[0]].length}`]=o[1]}else t[o[0]]=o[1];return t}(e);return i()(n=D().OrderedMap(t)).call(n,fe)}return i()(t=D().OrderedMap(e)).call(t,fe)}function he(e){return o()(e)?e:[e]}function de(e){return"function"==typeof e}function me(e){return!!e&&"object"==typeof e}function ge(e){return"function"==typeof e}function ve(e){return o()(e)}const ye=V();function be(e,t){var r;return g()(r=d()(e)).call(r,((r,n)=>(r[n]=t(e[n],n),r)),{})}function we(e,t){var r;return g()(r=d()(e)).call(r,((r,n)=>{let o=t(e[n],n);return o&&"object"==typeof o&&y()(r,o),r}),{})}function Ee(e){return t=>{let{dispatch:r,getState:n}=t;return t=>r=>"function"==typeof r?r(e()):t(r)}}function xe(e){var t;let r=e.keySeq();return r.contains(ue)?ue:w()(t=f()(r).call(r,(e=>"2"===(e+"")[0]))).call(t).first()}function _e(e,t){if(!D().Iterable.isIterable(e))return D().List();let r=e.getIn(o()(t)?t:[t]);return D().List.isList(r)?r:D().List()}function Se(e){let t,r=[/filename\*=[^']+'\w*'"([^"]+)";?/i,/filename\*=[^']+'\w*'([^;]+);?/i,/filename="([^;]*);?"/i,/filename=([^;]*);?/i];if(S()(r).call(r,(r=>(t=r.exec(e),null!==t))),null!==t&&t.length>1)try{return decodeURIComponent(t[1])}catch(e){console.error(e)}return null}function Ae(e){return t=e.replace(/\.[^./]*$/,""),U()(F()(t));var t}function ke(e,t,r,n,a){if(!t)return[];let s=[],l=t.get("nullable"),u=t.get("required"),p=t.get("maximum"),h=t.get("minimum"),d=t.get("type"),m=t.get("format"),g=t.get("maxLength"),v=t.get("minLength"),y=t.get("uniqueItems"),b=t.get("maxItems"),w=t.get("minItems"),E=t.get("pattern");const x=r||!0===u,_=null!=e;if(l&&null===e||!d||!(x||_&&"array"===d||!(!x&&!_)))return[];let A="string"===d&&e,k="array"===d&&o()(e)&&e.length,C="array"===d&&D().List.isList(e)&&e.count();const O=[A,k,C,"array"===d&&"string"==typeof e&&e,"file"===d&&e instanceof X.Z.File,"boolean"===d&&(e||!1===e),"number"===d&&(e||0===e),"integer"===d&&(e||0===e),"object"===d&&"object"==typeof e&&null!==e,"object"===d&&"string"==typeof e&&e],j=S()(O).call(O,(e=>!!e));if(x&&!j&&!n)return s.push("Required field is not provided"),s;if("object"===d&&(null===a||"application/json"===a)){let r=e;if("string"==typeof e)try{r=JSON.parse(e)}catch(e){return s.push("Parameter string value must be valid JSON"),s}var I;if(t&&t.has("required")&&ge(u.isList)&&u.isList()&&c()(u).call(u,(e=>{void 0===r[e]&&s.push({propKey:e,error:"Required property not found"})})),t&&t.has("properties"))c()(I=t.get("properties")).call(I,((e,t)=>{const o=ke(r[t],e,!1,n,a);s.push(...i()(o).call(o,(e=>({propKey:t,error:e}))))}))}if(E){let t=((e,t)=>{if(!new RegExp(t).test(e))return"Value must follow pattern "+t})(e,E);t&&s.push(t)}if(w&&"array"===d){let t=((e,t)=>{if(!e&&t>=1||e&&e.length{if(e&&e.length>t)return`Array must not contain more then ${t} item${1===t?"":"s"}`})(e,b);t&&s.push({needRemove:!0,error:t})}if(y&&"array"===d){let t=((e,t)=>{if(e&&("true"===t||!0===t)){const t=(0,M.fromJS)(e),r=t.toSet();if(e.length>r.size){let e=(0,M.Set)();if(c()(t).call(t,((r,n)=>{f()(t).call(t,(e=>ge(e.equals)?e.equals(r):e===r)).size>1&&(e=e.add(n))})),0!==e.size)return i()(e).call(e,(e=>({index:e,error:"No duplicates allowed."}))).toArray()}}})(e,y);t&&s.push(...t)}if(g||0===g){let t=((e,t)=>{if(e.length>t)return`Value must be no longer than ${t} character${1!==t?"s":""}`})(e,g);t&&s.push(t)}if(v){let t=((e,t)=>{if(e.length{if(e>t)return`Value must be less than ${t}`})(e,p);t&&s.push(t)}if(h||0===h){let t=((e,t)=>{if(e{if(isNaN(Date.parse(e)))return"Value must be a DateTime"})(e):"uuid"===m?(e=>{if(e=e.toString().toLowerCase(),!/^[{(]?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[)}]?$/.test(e))return"Value must be a Guid"})(e):(e=>{if(e&&"string"!=typeof e)return"Value must be a string"})(e),!t)return s;s.push(t)}else if("boolean"===d){let t=(e=>{if("true"!==e&&"false"!==e&&!0!==e&&!1!==e)return"Value must be a boolean"})(e);if(!t)return s;s.push(t)}else if("number"===d){let t=(e=>{if(!/^-?\d+(\.?\d+)?$/.test(e))return"Value must be a number"})(e);if(!t)return s;s.push(t)}else if("integer"===d){let t=(e=>{if(!/^-?\d+$/.test(e))return"Value must be an integer"})(e);if(!t)return s;s.push(t)}else if("array"===d){if(!k&&!C)return s;e&&c()(e).call(e,((e,r)=>{const o=ke(e,t.get("items"),!1,n,a);s.push(...i()(o).call(o,(e=>({index:r,error:e}))))}))}else if("file"===d){let t=(e=>{if(e&&!(e instanceof X.Z.File))return"Value must be a file"})(e);if(!t)return s;s.push(t)}return s}const Ce=function(e,t){let{isOAS3:r=!1,bypassRequiredCheck:n=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=e.get("required"),{schema:a,parameterContentMediaType:i}=(0,re.Z)(e,{isOAS3:r});return ke(t,a,o,n,i)},Oe=(e,t,r)=>{if(e&&!e.xml&&(e.xml={}),e&&!e.xml.name){if(!e.$$ref&&(e.type||e.items||e.properties||e.additionalProperties))return'\n\x3c!-- XML example cannot be generated; root element name is undefined --\x3e';if(e.$$ref){let t=e.$$ref.match(/\S*\/(\S+)$/);e.xml.name=t[1]}}return(0,Q.memoizedCreateXMLExample)(e,t,r)},je=[{when:/json/,shouldStringifyTypes:["string"]}],Ie=["object"],Ne=(e,t,r,n)=>{const o=(0,Q.memoizedSampleFromSchema)(e,t,n),a=typeof o,i=g()(je).call(je,((e,t)=>t.when.test(r)?[...e,...t.shouldStringifyTypes]:e),Ie);return J()(i,(e=>e===a))?k()(o,null,2):o},Te=(e,t,r,n)=>{const o=Ne(e,t,r,n);let a;try{a=se.ZP.dump(se.ZP.load(o),{lineWidth:-1},{schema:se.A8}),"\n"===a[a.length-1]&&(a=x()(a).call(a,0,a.length-1))}catch(e){return console.error(e),"error: could not generate yaml example"}return a.replace(/\t/g," ")},Pe=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;return e&&ge(e.toJS)&&(e=e.toJS()),n&&ge(n.toJS)&&(n=n.toJS()),/xml/.test(t)?Oe(e,r,n):/(yaml|yml)/.test(t)?Te(e,r,t,n):Ne(e,r,t,n)},Re=()=>{let e={},t=X.Z.location.search;if(!t)return{};if(""!=t){let r=t.substr(1).split("&");for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(t=r[t].split("="),e[decodeURIComponent(t[0])]=t[1]&&decodeURIComponent(t[1])||"")}return e},Me=e=>{let t;return t=e instanceof le?e:le.from(e.toString(),"utf-8"),t.toString("base64")},De={operationsSorter:{alpha:(e,t)=>e.get("path").localeCompare(t.get("path")),method:(e,t)=>e.get("method").localeCompare(t.get("method"))},tagsSorter:{alpha:(e,t)=>e.localeCompare(t)}},Le=e=>{let t=[];for(let r in e){let n=e[r];void 0!==n&&""!==n&&t.push([r,"=",encodeURIComponent(n).replace(/%20/g,"+")].join(""))}return t.join("&")},Be=(e,t,r)=>!!W()(r,(r=>G()(e[r],t[r])));function Fe(e){return"string"!=typeof e||""===e?"":(0,L.N)(e)}function ze(e){return!(!e||O()(e).call(e,"localhost")>=0||O()(e).call(e,"127.0.0.1")>=0||"none"===e)}function Ue(e){if(!D().OrderedMap.isOrderedMap(e))return null;if(!e.size)return null;const t=I()(e).call(e,((e,t)=>T()(t).call(t,"2")&&d()(e.get("content")||{}).length>0)),r=e.get("default")||D().OrderedMap(),n=(r.get("content")||D().OrderedMap()).keySeq().toJS().length?r:null;return t||n}const qe=e=>"string"==typeof e||e instanceof String?R()(e).call(e).replace(/\s/g,"%20"):"",Ve=e=>te()(qe(e).replace(/%20/g,"_")),$e=e=>f()(e).call(e,((e,t)=>/^x-/.test(t))),We=e=>f()(e).call(e,((e,t)=>/^pattern|maxLength|minLength|maximum|minimum/.test(t)));function He(e,t){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:()=>!0;if("object"!=typeof e||o()(e)||null===e||!t)return e;const a=y()({},e);return c()(r=d()(a)).call(r,(e=>{e===t&&n(a[e],e)?delete a[e]:a[e]=He(a[e],t,n)})),a}function Je(e){if("string"==typeof e)return e;if(e&&e.toJS&&(e=e.toJS()),"object"==typeof e&&null!==e)try{return k()(e,null,2)}catch(t){return String(e)}return null==e?"":e.toString()}function Ke(e){return"number"==typeof e?e.toString():e}function Ge(e){let{returnAll:t=!1,allowHashes:r=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!D().Map.isMap(e))throw new Error("paramToIdentifier: received a non-Im.Map parameter as input");const n=e.get("name"),o=e.get("in");let a=[];return e&&e.hashCode&&o&&n&&r&&a.push(`${o}.${n}.hash-${e.hashCode()}`),o&&n&&a.push(`${o}.${n}`),a.push(n),t?a:a[0]||""}function Ze(e,t){var r;const n=Ge(e,{returnAll:!0});return f()(r=i()(n).call(n,(e=>t[e]))).call(r,(e=>void 0!==e))[0]}function Ye(){return Xe(oe()(32).toString("base64"))}function Qe(e){return Xe(ie()("sha256").update(e).digest("base64"))}function Xe(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}const et=e=>!e||!(!ce(e)||!e.isEmpty())},2518:(e,t,r)=>{"use strict";function n(e){return function(e){try{return!!JSON.parse(e)}catch(e){return null}}(e)?"json":null}r.d(t,{O:()=>n})},27504:(e,t,r)=>{"use strict";r.d(t,{Z:()=>n});const n=function(){var e={location:{},history:{},open:()=>{},close:()=>{},File:function(){}};if("undefined"==typeof window)return e;try{e=window;for(var t of["File","Blob","FormData"])t in window&&(e[t]=window[t])}catch(e){console.error(e)}return e}()},19069:(e,t,r)=>{"use strict";r.d(t,{Z:()=>c});var n=r(14418),o=r.n(n),a=r(58118),i=r.n(a),s=r(43393),l=r.n(s);const u=l().Set.of("type","format","items","default","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","enum","multipleOf");function c(e){let{isOAS3:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!l().Map.isMap(e))return{schema:l().Map(),parameterContentMediaType:null};if(!t)return"body"===e.get("in")?{schema:e.get("schema",l().Map()),parameterContentMediaType:null}:{schema:o()(e).call(e,((e,t)=>i()(u).call(u,t))),parameterContentMediaType:null};if(e.get("content")){const t=e.get("content",l().Map({})).keySeq().first();return{schema:e.getIn(["content",t,"schema"],l().Map()),parameterContentMediaType:t}}return{schema:e.get("schema")?e.get("schema",l().Map()):l().Map(),parameterContentMediaType:null}}},60314:(e,t,r)=>{"use strict";r.d(t,{Z:()=>x});var n=r(58309),o=r.n(n),a=r(2250),i=r.n(a),s=r(25110),l=r.n(s),u=r(8712),c=r.n(u),p=r(51679),f=r.n(p),h=r(12373),d=r.n(h),m=r(18492),g=r.n(m),v=r(88306),y=r.n(v);const b=e=>t=>o()(e)&&o()(t)&&e.length===t.length&&i()(e).call(e,((e,r)=>e===t[r])),w=function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&void 0!==arguments[1]?arguments[1]:w;const{Cache:r}=y();y().Cache=E;const n=y()(e,t);return y().Cache=r,n}},79742:(e,t)=>{"use strict";t.byteLength=function(e){var t=l(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,a=l(e),i=a[0],s=a[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,i,s)),c=0,p=s>0?i-4:i;for(r=0;r>16&255,u[c++]=t>>8&255,u[c++]=255&t;2===s&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[c++]=255&t);1===s&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t);return u},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,a=[],i=16383,s=0,l=n-o;sl?l:s+i));1===o?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return a.join("")};for(var r=[],n=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=a.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,n){for(var o,a,i=[],s=t;s>18&63]+r[a>>12&63]+r[a>>6&63]+r[63&a]);return i.join("")}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},48764:(e,t,r)=>{"use strict";const n=r(79742),o=r(80645),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=function(e){+e!=e&&(e=0);return l.alloc(+e)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function s(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let n=s(r);const o=n.write(e,t);o!==r&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(G(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return f(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(G(e,ArrayBuffer)||e&&G(e.buffer,ArrayBuffer))return h(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(G(e,SharedArrayBuffer)||e&&G(e.buffer,SharedArrayBuffer)))return h(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return l.from(n,t,r);const o=function(e){if(l.isBuffer(e)){const t=0|d(e.length),r=s(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||Z(e.length)?s(0):f(e);if("Buffer"===e.type&&Array.isArray(e.data))return f(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return c(e),s(e<0?0:0|d(e))}function f(e){const t=e.length<0?0:0|d(e.length),r=s(t);for(let n=0;n=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function m(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return J(e).length;default:if(o)return n?-1:H(e).length;t=(""+t).toLowerCase(),o=!0}}function g(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return k(this,t,r);case"ascii":return O(this,t,r);case"latin1":case"binary":return j(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function v(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function y(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Z(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=l.from(t,n)),l.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,o);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,o){let a,i=1,s=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;i=2,s/=2,l/=2,r/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(o){let n=-1;for(a=r;as&&(r=s-l),a=r;a>=0;a--){let r=!0;for(let n=0;no&&(n=o):n=o;const a=t.length;let i;for(n>a/2&&(n=a/2),i=0;i>8,o=r%256,a.push(o),a.push(n);return a}(t,e.length-r),e,r,n)}function A(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function k(e,t,r){r=Math.min(e.length,r);const n=[];let o=t;for(;o239?4:t>223?3:t>191?2:1;if(o+i<=r){let r,n,s,l;switch(i){case 1:t<128&&(a=t);break;case 2:r=e[o+1],128==(192&r)&&(l=(31&t)<<6|63&r,l>127&&(a=l));break;case 3:r=e[o+1],n=e[o+2],128==(192&r)&&128==(192&n)&&(l=(15&t)<<12|(63&r)<<6|63&n,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:r=e[o+1],n=e[o+2],s=e[o+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(l=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,i=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),o+=i}return function(e){const t=e.length;if(t<=C)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(n,o)):Uint8Array.prototype.set.call(n,t,o);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,o)}o+=t.length}return n},l.byteLength=m,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(e+=" ... "),""},a&&(l.prototype[a]=l.prototype.inspect),l.prototype.compare=function(e,t,r,n,o){if(G(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let a=(o>>>=0)-(n>>>=0),i=(r>>>=0)-(t>>>=0);const s=Math.min(a,i),u=this.slice(n,o),c=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let a=!1;for(;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":case"latin1":case"binary":return x(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const C=4096;function O(e,t,r){let n="";r=Math.min(e.length,r);for(let o=t;on)&&(r=n);let o="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,r,n,o,a){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function R(e,t,r,n,o){q(t,n,o,e,r,7);let a=Number(t&BigInt(4294967295));e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a;let i=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,r}function M(e,t,r,n,o){q(t,n,o,e,r,7);let a=Number(t&BigInt(4294967295));e[r+7]=a,a>>=8,e[r+6]=a,a>>=8,e[r+5]=a,a>>=8,e[r+4]=a;let i=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=i,i>>=8,e[r+2]=i,i>>=8,e[r+1]=i,i>>=8,e[r]=i,r+8}function D(e,t,r,n,o,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,n,a){return t=+t,r>>>=0,a||D(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function B(e,t,r,n,a){return t=+t,r>>>=0,a||D(e,0,r,8),o.write(e,t,r,n,52,8),r+8}l.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||T(e,t,this.length);let n=this[e],o=1,a=0;for(;++a>>=0,t>>>=0,r||T(e,t,this.length);let n=this[e+--t],o=1;for(;t>0&&(o*=256);)n+=this[e+--t]*o;return n},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||T(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||$(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(o)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||$(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||T(e,t,this.length);let n=this[e],o=1,a=0;for(;++a=o&&(n-=Math.pow(2,8*t)),n},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||T(e,t,this.length);let n=t,o=1,a=this[e+--n];for(;n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*t)),a},l.prototype.readInt8=function(e,t){return e>>>=0,t||T(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||T(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt16BE=function(e,t){e>>>=0,t||T(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q((function(e){V(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||$(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||$(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||T(e,4,this.length),o.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||T(e,4,this.length),o.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||T(e,8,this.length),o.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||T(e,8,this.length),o.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){P(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,!n){P(this,e,t,r,Math.pow(2,8*r)-1,0)}let o=r-1,a=1;for(this[t+o]=255&e;--o>=0&&(a*=256);)this[t+o]=e/a&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=Q((function(e,t=0){return R(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeBigUInt64BE=Q((function(e,t=0){return M(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),l.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let o=0,a=1,i=0;for(this[t]=255&e;++o>0)-i&255;return t+r},l.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let o=r-1,a=1,i=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===i&&0!==this[t+o+1]&&(i=1),this[t+o]=(e/a>>0)-i&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=Q((function(e,t=0){return R(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeBigInt64BE=Q((function(e,t=0){return M(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),l.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return B(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return B(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,n){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,n,o,a){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(a+1)}${n}`:`>= -(2${n} ** ${8*(a+1)-1}${n}) and < 2 ** ${8*(a+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new F.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){V(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||$(t,e.length-(r+1))}(n,o,a)}function V(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function $(e,t,r){if(Math.floor(e)!==e)throw V(e,r),new F.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}z("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),z("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),z("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=U(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=U(o)),o+="n"),n+=` It must be ${t}. Received ${o}`,n}),RangeError);const W=/[^+/0-9A-Za-z-_]/g;function H(e,t){let r;t=t||1/0;const n=e.length;let o=null;const a=[];for(let i=0;i55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(i+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function J(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,r,n){let o;for(o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Z(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let o=0;o<16;++o)t[n+o]=e[r]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?X:e}function X(){throw new Error("BigInt not supported")}},21924:(e,t,r)=>{"use strict";var n=r(40210),o=r(55559),a=o(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&a(e,".prototype.")>-1?o(r):r}},55559:(e,t,r)=>{"use strict";var n=r(58612),o=r(40210),a=o("%Function.prototype.apply%"),i=o("%Function.prototype.call%"),s=o("%Reflect.apply%",!0)||n.call(i,a),l=o("%Object.getOwnPropertyDescriptor%",!0),u=o("%Object.defineProperty%",!0),c=o("%Math.max%");if(u)try{u({},"a",{value:1})}catch(e){u=null}e.exports=function(e){var t=s(n,i,arguments);if(l&&u){var r=l(t,"length");r.configurable&&u(t,"length",{value:1+c(0,e.length-(arguments.length-1))})}return t};var p=function(){return s(n,a,arguments)};u?u(e.exports,"apply",{value:p}):e.exports.apply=p},94184:(e,t)=>{var r;!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t{"use strict";t.parse=function(e,t){if("string"!=typeof e)throw new TypeError("argument str must be a string");var r={},n=(t||{}).decode||o,a=0;for(;a{"use strict";var n=r(11742),o={"text/plain":"Text","text/html":"Url",default:"Text"};e.exports=function(e,t){var r,a,i,s,l,u,c=!1;t||(t={}),r=t.debug||!1;try{if(i=n(),s=document.createRange(),l=document.getSelection(),(u=document.createElement("span")).textContent=e,u.style.all="unset",u.style.position="fixed",u.style.top=0,u.style.clip="rect(0, 0, 0, 0)",u.style.whiteSpace="pre",u.style.webkitUserSelect="text",u.style.MozUserSelect="text",u.style.msUserSelect="text",u.style.userSelect="text",u.addEventListener("copy",(function(n){if(n.stopPropagation(),t.format)if(n.preventDefault(),void 0===n.clipboardData){r&&console.warn("unable to use e.clipboardData"),r&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var a=o[t.format]||o.default;window.clipboardData.setData(a,e)}else n.clipboardData.clearData(),n.clipboardData.setData(t.format,e);t.onCopy&&(n.preventDefault(),t.onCopy(n.clipboardData))})),document.body.appendChild(u),s.selectNodeContents(u),l.addRange(s),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");c=!0}catch(n){r&&console.error("unable to copy using execCommand: ",n),r&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(t.format||"text",e),t.onCopy&&t.onCopy(window.clipboardData),c=!0}catch(n){r&&console.error("unable to copy using clipboardData: ",n),r&&console.error("falling back to prompt"),a=function(e){var t=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return e.replace(/#{\s*key\s*}/g,t)}("message"in t?t.message:"Copy to clipboard: #{key}, Enter"),window.prompt(a,e)}}finally{l&&("function"==typeof l.removeRange?l.removeRange(s):l.removeAllRanges()),u&&document.body.removeChild(u),i()}return c}},95299:(e,t,r)=>{var n=r(24848);e.exports=n},83450:(e,t,r)=>{var n=r(83363);e.exports=n},66820:(e,t,r)=>{var n=r(56243);e.exports=n},5023:(e,t,r)=>{var n=r(72369);e.exports=n},90093:(e,t,r)=>{var n=r(28196);e.exports=n},3688:(e,t,r)=>{var n=r(11955);e.exports=n},83838:(e,t,r)=>{var n=r(46279);e.exports=n},15684:(e,t,r)=>{var n=r(19373);e.exports=n},99826:(e,t,r)=>{var n=r(28427);e.exports=n},84234:(e,t,r)=>{var n=r(82073);e.exports=n},65362:(e,t,r)=>{var n=r(63383);e.exports=n},32271:(e,t,r)=>{var n=r(14471);e.exports=n},91254:(e,t,r)=>{var n=r(57396);e.exports=n},43536:(e,t,r)=>{var n=r(41910);e.exports=n},37331:(e,t,r)=>{var n=r(79427);e.exports=n},68522:(e,t,r)=>{var n=r(62857);e.exports=n},73151:(e,t,r)=>{var n=r(9534);e.exports=n},99565:(e,t,r)=>{var n=r(96507);e.exports=n},45012:(e,t,r)=>{var n=r(23059);e.exports=n},78690:(e,t,r)=>{var n=r(16670);e.exports=n},25626:(e,t,r)=>{var n=r(27460);e.exports=n},80281:(e,t,r)=>{var n=r(92547);e.exports=n},40031:(e,t,r)=>{var n=r(46509);e.exports=n},54493:(e,t,r)=>{r(77971),r(53242);var n=r(54058);e.exports=n.Array.from},24034:(e,t,r)=>{r(92737);var n=r(54058);e.exports=n.Array.isArray},15367:(e,t,r)=>{r(85906);var n=r(35703);e.exports=n("Array").concat},12710:(e,t,r)=>{r(66274),r(55967);var n=r(35703);e.exports=n("Array").entries},51459:(e,t,r)=>{r(48851);var n=r(35703);e.exports=n("Array").every},6172:(e,t,r)=>{r(80290);var n=r(35703);e.exports=n("Array").fill},62383:(e,t,r)=>{r(21501);var n=r(35703);e.exports=n("Array").filter},60009:(e,t,r)=>{r(44929);var n=r(35703);e.exports=n("Array").findIndex},17671:(e,t,r)=>{r(80833);var n=r(35703);e.exports=n("Array").find},99324:(e,t,r)=>{r(2437);var n=r(35703);e.exports=n("Array").forEach},80991:(e,t,r)=>{r(97690);var n=r(35703);e.exports=n("Array").includes},8700:(e,t,r)=>{r(99076);var n=r(35703);e.exports=n("Array").indexOf},95909:(e,t,r)=>{r(66274),r(55967);var n=r(35703);e.exports=n("Array").keys},6442:(e,t,r)=>{r(75915);var n=r(35703);e.exports=n("Array").lastIndexOf},23866:(e,t,r)=>{r(68787);var n=r(35703);e.exports=n("Array").map},52999:(e,t,r)=>{r(81876);var n=r(35703);e.exports=n("Array").reduce},91876:(e,t,r)=>{r(11490);var n=r(35703);e.exports=n("Array").reverse},24900:(e,t,r)=>{r(60186);var n=r(35703);e.exports=n("Array").slice},3824:(e,t,r)=>{r(36026);var n=r(35703);e.exports=n("Array").some},2948:(e,t,r)=>{r(4115);var n=r(35703);e.exports=n("Array").sort},78209:(e,t,r)=>{r(98611);var n=r(35703);e.exports=n("Array").splice},14423:(e,t,r)=>{r(66274),r(55967);var n=r(35703);e.exports=n("Array").values},81103:(e,t,r)=>{r(95160);var n=r(54058);e.exports=n.Date.now},27700:(e,t,r)=>{r(73381);var n=r(35703);e.exports=n("Function").bind},13830:(e,t,r)=>{r(66274),r(77971);var n=r(22902);e.exports=n},91031:(e,t,r)=>{r(52595),e.exports=r(21899)},16246:(e,t,r)=>{var n=r(7046),o=r(27700),a=Function.prototype;e.exports=function(e){var t=e.bind;return e===a||n(a,e)&&t===a.bind?o:t}},56043:(e,t,r)=>{var n=r(7046),o=r(15367),a=Array.prototype;e.exports=function(e){var t=e.concat;return e===a||n(a,e)&&t===a.concat?o:t}},13160:(e,t,r)=>{var n=r(7046),o=r(51459),a=Array.prototype;e.exports=function(e){var t=e.every;return e===a||n(a,e)&&t===a.every?o:t}},80446:(e,t,r)=>{var n=r(7046),o=r(6172),a=Array.prototype;e.exports=function(e){var t=e.fill;return e===a||n(a,e)&&t===a.fill?o:t}},2480:(e,t,r)=>{var n=r(7046),o=r(62383),a=Array.prototype;e.exports=function(e){var t=e.filter;return e===a||n(a,e)&&t===a.filter?o:t}},7147:(e,t,r)=>{var n=r(7046),o=r(60009),a=Array.prototype;e.exports=function(e){var t=e.findIndex;return e===a||n(a,e)&&t===a.findIndex?o:t}},32236:(e,t,r)=>{var n=r(7046),o=r(17671),a=Array.prototype;e.exports=function(e){var t=e.find;return e===a||n(a,e)&&t===a.find?o:t}},58557:(e,t,r)=>{var n=r(7046),o=r(80991),a=r(21631),i=Array.prototype,s=String.prototype;e.exports=function(e){var t=e.includes;return e===i||n(i,e)&&t===i.includes?o:"string"==typeof e||e===s||n(s,e)&&t===s.includes?a:t}},34570:(e,t,r)=>{var n=r(7046),o=r(8700),a=Array.prototype;e.exports=function(e){var t=e.indexOf;return e===a||n(a,e)&&t===a.indexOf?o:t}},57564:(e,t,r)=>{var n=r(7046),o=r(6442),a=Array.prototype;e.exports=function(e){var t=e.lastIndexOf;return e===a||n(a,e)&&t===a.lastIndexOf?o:t}},88287:(e,t,r)=>{var n=r(7046),o=r(23866),a=Array.prototype;e.exports=function(e){var t=e.map;return e===a||n(a,e)&&t===a.map?o:t}},68025:(e,t,r)=>{var n=r(7046),o=r(52999),a=Array.prototype;e.exports=function(e){var t=e.reduce;return e===a||n(a,e)&&t===a.reduce?o:t}},59257:(e,t,r)=>{var n=r(7046),o=r(80454),a=String.prototype;e.exports=function(e){var t=e.repeat;return"string"==typeof e||e===a||n(a,e)&&t===a.repeat?o:t}},91060:(e,t,r)=>{var n=r(7046),o=r(91876),a=Array.prototype;e.exports=function(e){var t=e.reverse;return e===a||n(a,e)&&t===a.reverse?o:t}},69601:(e,t,r)=>{var n=r(7046),o=r(24900),a=Array.prototype;e.exports=function(e){var t=e.slice;return e===a||n(a,e)&&t===a.slice?o:t}},28299:(e,t,r)=>{var n=r(7046),o=r(3824),a=Array.prototype;e.exports=function(e){var t=e.some;return e===a||n(a,e)&&t===a.some?o:t}},69355:(e,t,r)=>{var n=r(7046),o=r(2948),a=Array.prototype;e.exports=function(e){var t=e.sort;return e===a||n(a,e)&&t===a.sort?o:t}},18339:(e,t,r)=>{var n=r(7046),o=r(78209),a=Array.prototype;e.exports=function(e){var t=e.splice;return e===a||n(a,e)&&t===a.splice?o:t}},71611:(e,t,r)=>{var n=r(7046),o=r(3269),a=String.prototype;e.exports=function(e){var t=e.startsWith;return"string"==typeof e||e===a||n(a,e)&&t===a.startsWith?o:t}},62774:(e,t,r)=>{var n=r(7046),o=r(13348),a=String.prototype;e.exports=function(e){var t=e.trim;return"string"==typeof e||e===a||n(a,e)&&t===a.trim?o:t}},84426:(e,t,r)=>{r(32619);var n=r(54058),o=r(79730);n.JSON||(n.JSON={stringify:JSON.stringify}),e.exports=function(e,t,r){return o(n.JSON.stringify,null,arguments)}},91018:(e,t,r)=>{r(66274),r(37501),r(55967),r(77971);var n=r(54058);e.exports=n.Map},45999:(e,t,r)=>{r(49221);var n=r(54058);e.exports=n.Object.assign},35254:(e,t,r)=>{r(53882);var n=r(54058).Object;e.exports=function(e,t){return n.create(e,t)}},7702:(e,t,r)=>{r(74979);var n=r(54058).Object,o=e.exports=function(e,t){return n.defineProperties(e,t)};n.defineProperties.sham&&(o.sham=!0)},48171:(e,t,r)=>{r(86450);var n=r(54058).Object,o=e.exports=function(e,t,r){return n.defineProperty(e,t,r)};n.defineProperty.sham&&(o.sham=!0)},73081:(e,t,r)=>{r(94366);var n=r(54058);e.exports=n.Object.entries},286:(e,t,r)=>{r(46924);var n=r(54058).Object,o=e.exports=function(e,t){return n.getOwnPropertyDescriptor(e,t)};n.getOwnPropertyDescriptor.sham&&(o.sham=!0)},92766:(e,t,r)=>{r(88482);var n=r(54058);e.exports=n.Object.getOwnPropertyDescriptors},30498:(e,t,r)=>{r(35824);var n=r(54058);e.exports=n.Object.getOwnPropertySymbols},13966:(e,t,r)=>{r(17405);var n=r(54058);e.exports=n.Object.getPrototypeOf},48494:(e,t,r)=>{r(21724);var n=r(54058);e.exports=n.Object.keys},3065:(e,t,r)=>{r(90108);var n=r(54058);e.exports=n.Object.setPrototypeOf},98430:(e,t,r)=>{r(26614);var n=r(54058);e.exports=n.Object.values},52956:(e,t,r)=>{r(47627),r(66274),r(55967),r(98881),r(4560),r(91302),r(44349),r(77971);var n=r(54058);e.exports=n.Promise},21631:(e,t,r)=>{r(11035);var n=r(35703);e.exports=n("String").includes},80454:(e,t,r)=>{r(60986);var n=r(35703);e.exports=n("String").repeat},3269:(e,t,r)=>{r(94761);var n=r(35703);e.exports=n("String").startsWith},13348:(e,t,r)=>{r(57398);var n=r(35703);e.exports=n("String").trim},57473:(e,t,r)=>{r(85906),r(55967),r(35824),r(8555),r(52615),r(21732),r(35903),r(1825),r(28394),r(45915),r(61766),r(62737),r(89911),r(74315),r(63131),r(64714),r(70659),r(69120),r(79413),r(1502);var n=r(54058);e.exports=n.Symbol},24227:(e,t,r)=>{r(66274),r(55967),r(77971),r(1825);var n=r(11477);e.exports=n.f("iterator")},32304:(e,t,r)=>{r(66274),r(55967),r(54334);var n=r(54058);e.exports=n.WeakMap},27385:(e,t,r)=>{var n=r(95299);e.exports=n},81522:(e,t,r)=>{var n=r(83450);e.exports=n},32209:(e,t,r)=>{var n=r(66820);e.exports=n},30888:(e,t,r)=>{r(9668);var n=r(5023);e.exports=n},14122:(e,t,r)=>{var n=r(90093);e.exports=n},44442:(e,t,r)=>{var n=r(3688);e.exports=n},57152:(e,t,r)=>{var n=r(83838);e.exports=n},69447:(e,t,r)=>{var n=r(15684);e.exports=n},17579:(e,t,r)=>{var n=r(99826);e.exports=n},81493:(e,t,r)=>{var n=r(84234);e.exports=n},60269:(e,t,r)=>{var n=r(65362);e.exports=n},76094:(e,t,r)=>{var n=r(32271);e.exports=n},70573:(e,t,r)=>{var n=r(91254);e.exports=n},73685:(e,t,r)=>{var n=r(43536);e.exports=n},27533:(e,t,r)=>{var n=r(37331);e.exports=n},39057:(e,t,r)=>{var n=r(68522);e.exports=n},84710:(e,t,r)=>{var n=r(73151);e.exports=n},74303:(e,t,r)=>{var n=r(99565);e.exports=n},93799:(e,t,r)=>{var n=r(45012);e.exports=n},55122:(e,t,r)=>{var n=r(78690);e.exports=n},29531:(e,t,r)=>{var n=r(25626);r(89731),r(55708),r(30014),r(88731),e.exports=n},86600:(e,t,r)=>{var n=r(80281);r(28783),r(43975),r(65799),r(45414),r(46774),r(80620),r(36172),e.exports=n},9759:(e,t,r)=>{var n=r(40031);e.exports=n},24883:(e,t,r)=>{var n=r(21899),o=r(57475),a=r(69826),i=n.TypeError;e.exports=function(e){if(o(e))return e;throw i(a(e)+" is not a function")}},174:(e,t,r)=>{var n=r(21899),o=r(24284),a=r(69826),i=n.TypeError;e.exports=function(e){if(o(e))return e;throw i(a(e)+" is not a constructor")}},11851:(e,t,r)=>{var n=r(21899),o=r(57475),a=n.String,i=n.TypeError;e.exports=function(e){if("object"==typeof e||o(e))return e;throw i("Can't set "+a(e)+" as a prototype")}},18479:e=>{e.exports=function(){}},5743:(e,t,r)=>{var n=r(21899),o=r(7046),a=n.TypeError;e.exports=function(e,t){if(o(t,e))return e;throw a("Incorrect invocation")}},96059:(e,t,r)=>{var n=r(21899),o=r(10941),a=n.String,i=n.TypeError;e.exports=function(e){if(o(e))return e;throw i(a(e)+" is not an object")}},97135:(e,t,r)=>{var n=r(95981);e.exports=n((function(){if("function"==typeof ArrayBuffer){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}}))},91860:(e,t,r)=>{"use strict";var n=r(89678),o=r(59413),a=r(10623);e.exports=function(e){for(var t=n(this),r=a(t),i=arguments.length,s=o(i>1?arguments[1]:void 0,r),l=i>2?arguments[2]:void 0,u=void 0===l?r:o(l,r);u>s;)t[s++]=e;return t}},56837:(e,t,r)=>{"use strict";var n=r(3610).forEach,o=r(34194)("forEach");e.exports=o?[].forEach:function(e){return n(this,e,arguments.length>1?arguments[1]:void 0)}},11354:(e,t,r)=>{"use strict";var n=r(21899),o=r(86843),a=r(78834),i=r(89678),s=r(75196),l=r(6782),u=r(24284),c=r(10623),p=r(55449),f=r(53476),h=r(22902),d=n.Array;e.exports=function(e){var t=i(e),r=u(this),n=arguments.length,m=n>1?arguments[1]:void 0,g=void 0!==m;g&&(m=o(m,n>2?arguments[2]:void 0));var v,y,b,w,E,x,_=h(t),S=0;if(!_||this==d&&l(_))for(v=c(t),y=r?new this(v):d(v);v>S;S++)x=g?m(t[S],S):t[S],p(y,S,x);else for(E=(w=f(t,_)).next,y=r?new this:[];!(b=a(E,w)).done;S++)x=g?s(w,m,[b.value,S],!0):b.value,p(y,S,x);return y.length=S,y}},31692:(e,t,r)=>{var n=r(74529),o=r(59413),a=r(10623),i=function(e){return function(t,r,i){var s,l=n(t),u=a(l),c=o(i,u);if(e&&r!=r){for(;u>c;)if((s=l[c++])!=s)return!0}else for(;u>c;c++)if((e||c in l)&&l[c]===r)return e||c||0;return!e&&-1}};e.exports={includes:i(!0),indexOf:i(!1)}},3610:(e,t,r)=>{var n=r(86843),o=r(95329),a=r(37026),i=r(89678),s=r(10623),l=r(64692),u=o([].push),c=function(e){var t=1==e,r=2==e,o=3==e,c=4==e,p=6==e,f=7==e,h=5==e||p;return function(d,m,g,v){for(var y,b,w=i(d),E=a(w),x=n(m,g),_=s(E),S=0,A=v||l,k=t?A(d,_):r||f?A(d,0):void 0;_>S;S++)if((h||S in E)&&(b=x(y=E[S],S,w),e))if(t)k[S]=b;else if(b)switch(e){case 3:return!0;case 5:return y;case 6:return S;case 2:u(k,y)}else switch(e){case 4:return!1;case 7:u(k,y)}return p?-1:o||c?c:k}};e.exports={forEach:c(0),map:c(1),filter:c(2),some:c(3),every:c(4),find:c(5),findIndex:c(6),filterReject:c(7)}},67145:(e,t,r)=>{"use strict";var n=r(79730),o=r(74529),a=r(62435),i=r(10623),s=r(34194),l=Math.min,u=[].lastIndexOf,c=!!u&&1/[1].lastIndexOf(1,-0)<0,p=s("lastIndexOf"),f=c||!p;e.exports=f?function(e){if(c)return n(u,this,arguments)||0;var t=o(this),r=i(t),s=r-1;for(arguments.length>1&&(s=l(s,a(arguments[1]))),s<0&&(s=r+s);s>=0;s--)if(s in t&&t[s]===e)return s||0;return-1}:u},50568:(e,t,r)=>{var n=r(95981),o=r(99813),a=r(53385),i=o("species");e.exports=function(e){return a>=51||!n((function(){var t=[];return(t.constructor={})[i]=function(){return{foo:1}},1!==t[e](Boolean).foo}))}},34194:(e,t,r)=>{"use strict";var n=r(95981);e.exports=function(e,t){var r=[][e];return!!r&&n((function(){r.call(null,t||function(){throw 1},1)}))}},46499:(e,t,r)=>{var n=r(21899),o=r(24883),a=r(89678),i=r(37026),s=r(10623),l=n.TypeError,u=function(e){return function(t,r,n,u){o(r);var c=a(t),p=i(c),f=s(c),h=e?f-1:0,d=e?-1:1;if(n<2)for(;;){if(h in p){u=p[h],h+=d;break}if(h+=d,e?h<0:f<=h)throw l("Reduce of empty array with no initial value")}for(;e?h>=0:f>h;h+=d)h in p&&(u=r(u,p[h],h,c));return u}};e.exports={left:u(!1),right:u(!0)}},15790:(e,t,r)=>{var n=r(21899),o=r(59413),a=r(10623),i=r(55449),s=n.Array,l=Math.max;e.exports=function(e,t,r){for(var n=a(e),u=o(t,n),c=o(void 0===r?n:r,n),p=s(l(c-u,0)),f=0;u{var n=r(95329);e.exports=n([].slice)},61388:(e,t,r)=>{var n=r(15790),o=Math.floor,a=function(e,t){var r=e.length,l=o(r/2);return r<8?i(e,t):s(e,a(n(e,0,l),t),a(n(e,l),t),t)},i=function(e,t){for(var r,n,o=e.length,a=1;a0;)e[n]=e[--n];n!==a++&&(e[n]=r)}return e},s=function(e,t,r,n){for(var o=t.length,a=r.length,i=0,s=0;i{var n=r(21899),o=r(1052),a=r(24284),i=r(10941),s=r(99813)("species"),l=n.Array;e.exports=function(e){var t;return o(e)&&(t=e.constructor,(a(t)&&(t===l||o(t.prototype))||i(t)&&null===(t=t[s]))&&(t=void 0)),void 0===t?l:t}},64692:(e,t,r)=>{var n=r(5693);e.exports=function(e,t){return new(n(e))(0===t?0:t)}},75196:(e,t,r)=>{var n=r(96059),o=r(7609);e.exports=function(e,t,r,a){try{return a?t(n(r)[0],r[1]):t(r)}catch(t){o(e,"throw",t)}}},21385:(e,t,r)=>{var n=r(99813)("iterator"),o=!1;try{var a=0,i={next:function(){return{done:!!a++}},return:function(){o=!0}};i[n]=function(){return this},Array.from(i,(function(){throw 2}))}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var r=!1;try{var a={};a[n]=function(){return{next:function(){return{done:r=!0}}}},e(a)}catch(e){}return r}},82532:(e,t,r)=>{var n=r(95329),o=n({}.toString),a=n("".slice);e.exports=function(e){return a(o(e),8,-1)}},9697:(e,t,r)=>{var n=r(21899),o=r(22885),a=r(57475),i=r(82532),s=r(99813)("toStringTag"),l=n.Object,u="Arguments"==i(function(){return arguments}());e.exports=o?i:function(e){var t,r,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=l(e),s))?r:u?i(t):"Object"==(n=i(t))&&a(t.callee)?"Arguments":n}},38694:(e,t,r)=>{var n=r(95329)("".replace),o=String(Error("zxcasd").stack),a=/\n\s*at [^:]*:[^\n]*/,i=a.test(o);e.exports=function(e,t){if(i&&"string"==typeof e)for(;t--;)e=n(e,a,"");return e}},85616:(e,t,r)=>{"use strict";var n=r(65988).f,o=r(29290),a=r(87524),i=r(86843),s=r(5743),l=r(93091),u=r(47771),c=r(94431),p=r(55746),f=r(21647).fastKey,h=r(45402),d=h.set,m=h.getterFor;e.exports={getConstructor:function(e,t,r,u){var c=e((function(e,n){s(e,h),d(e,{type:t,index:o(null),first:void 0,last:void 0,size:0}),p||(e.size=0),null!=n&&l(n,e[u],{that:e,AS_ENTRIES:r})})),h=c.prototype,g=m(t),v=function(e,t,r){var n,o,a=g(e),i=y(e,t);return i?i.value=r:(a.last=i={index:o=f(t,!0),key:t,value:r,previous:n=a.last,next:void 0,removed:!1},a.first||(a.first=i),n&&(n.next=i),p?a.size++:e.size++,"F"!==o&&(a.index[o]=i)),e},y=function(e,t){var r,n=g(e),o=f(t);if("F"!==o)return n.index[o];for(r=n.first;r;r=r.next)if(r.key==t)return r};return a(h,{clear:function(){for(var e=g(this),t=e.index,r=e.first;r;)r.removed=!0,r.previous&&(r.previous=r.previous.next=void 0),delete t[r.index],r=r.next;e.first=e.last=void 0,p?e.size=0:this.size=0},delete:function(e){var t=this,r=g(t),n=y(t,e);if(n){var o=n.next,a=n.previous;delete r.index[n.index],n.removed=!0,a&&(a.next=o),o&&(o.previous=a),r.first==n&&(r.first=o),r.last==n&&(r.last=a),p?r.size--:t.size--}return!!n},forEach:function(e){for(var t,r=g(this),n=i(e,arguments.length>1?arguments[1]:void 0);t=t?t.next:r.first;)for(n(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!y(this,e)}}),a(h,r?{get:function(e){var t=y(this,e);return t&&t.value},set:function(e,t){return v(this,0===e?0:e,t)}}:{add:function(e){return v(this,e=0===e?0:e,e)}}),p&&n(h,"size",{get:function(){return g(this).size}}),c},setStrong:function(e,t,r){var n=t+" Iterator",o=m(t),a=m(n);u(e,t,(function(e,t){d(this,{type:n,target:e,state:o(e),kind:t,last:void 0})}),(function(){for(var e=a(this),t=e.kind,r=e.last;r&&r.removed;)r=r.previous;return e.target&&(e.last=r=r?r.next:e.state.first)?"keys"==t?{value:r.key,done:!1}:"values"==t?{value:r.value,done:!1}:{value:[r.key,r.value],done:!1}:(e.target=void 0,{value:void 0,done:!0})}),r?"entries":"values",!r,!0),c(t)}}},8850:(e,t,r)=>{"use strict";var n=r(95329),o=r(87524),a=r(21647).getWeakData,i=r(96059),s=r(10941),l=r(5743),u=r(93091),c=r(3610),p=r(90953),f=r(45402),h=f.set,d=f.getterFor,m=c.find,g=c.findIndex,v=n([].splice),y=0,b=function(e){return e.frozen||(e.frozen=new w)},w=function(){this.entries=[]},E=function(e,t){return m(e.entries,(function(e){return e[0]===t}))};w.prototype={get:function(e){var t=E(this,e);if(t)return t[1]},has:function(e){return!!E(this,e)},set:function(e,t){var r=E(this,e);r?r[1]=t:this.entries.push([e,t])},delete:function(e){var t=g(this.entries,(function(t){return t[0]===e}));return~t&&v(this.entries,t,1),!!~t}},e.exports={getConstructor:function(e,t,r,n){var c=e((function(e,o){l(e,f),h(e,{type:t,id:y++,frozen:void 0}),null!=o&&u(o,e[n],{that:e,AS_ENTRIES:r})})),f=c.prototype,m=d(t),g=function(e,t,r){var n=m(e),o=a(i(t),!0);return!0===o?b(n).set(t,r):o[n.id]=r,e};return o(f,{delete:function(e){var t=m(this);if(!s(e))return!1;var r=a(e);return!0===r?b(t).delete(e):r&&p(r,t.id)&&delete r[t.id]},has:function(e){var t=m(this);if(!s(e))return!1;var r=a(e);return!0===r?b(t).has(e):r&&p(r,t.id)}}),o(f,r?{get:function(e){var t=m(this);if(s(e)){var r=a(e);return!0===r?b(t).get(e):r?r[t.id]:void 0}},set:function(e,t){return g(this,e,t)}}:{add:function(e){return g(this,e,!0)}}),c}}},24683:(e,t,r)=>{"use strict";var n=r(76887),o=r(21899),a=r(21647),i=r(95981),s=r(32029),l=r(93091),u=r(5743),c=r(57475),p=r(10941),f=r(90904),h=r(65988).f,d=r(3610).forEach,m=r(55746),g=r(45402),v=g.set,y=g.getterFor;e.exports=function(e,t,r){var g,b=-1!==e.indexOf("Map"),w=-1!==e.indexOf("Weak"),E=b?"set":"add",x=o[e],_=x&&x.prototype,S={};if(m&&c(x)&&(w||_.forEach&&!i((function(){(new x).entries().next()})))){var A=(g=t((function(t,r){v(u(t,A),{type:e,collection:new x}),null!=r&&l(r,t[E],{that:t,AS_ENTRIES:b})}))).prototype,k=y(e);d(["add","clear","delete","forEach","get","has","set","keys","values","entries"],(function(e){var t="add"==e||"set"==e;!(e in _)||w&&"clear"==e||s(A,e,(function(r,n){var o=k(this).collection;if(!t&&w&&!p(r))return"get"==e&&void 0;var a=o[e](0===r?0:r,n);return t?this:a}))})),w||h(A,"size",{configurable:!0,get:function(){return k(this).collection.size}})}else g=r.getConstructor(t,e,b,E),a.enable();return f(g,e,!1,!0),S[e]=g,n({global:!0,forced:!0},S),w||r.setStrong(g,e,b),g}},23489:(e,t,r)=>{var n=r(90953),o=r(31136),a=r(49677),i=r(65988);e.exports=function(e,t,r){for(var s=o(t),l=i.f,u=a.f,c=0;c{var n=r(99813)("match");e.exports=function(e){var t=/./;try{"/./"[e](t)}catch(r){try{return t[n]=!1,"/./"[e](t)}catch(e){}}return!1}},64160:(e,t,r)=>{var n=r(95981);e.exports=!n((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}))},31046:(e,t,r)=>{"use strict";var n=r(35143).IteratorPrototype,o=r(29290),a=r(31887),i=r(90904),s=r(12077),l=function(){return this};e.exports=function(e,t,r,u){var c=t+" Iterator";return e.prototype=o(n,{next:a(+!u,r)}),i(e,c,!1,!0),s[c]=l,e}},32029:(e,t,r)=>{var n=r(55746),o=r(65988),a=r(31887);e.exports=n?function(e,t,r){return o.f(e,t,a(1,r))}:function(e,t,r){return e[t]=r,e}},31887:e=>{e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},55449:(e,t,r)=>{"use strict";var n=r(83894),o=r(65988),a=r(31887);e.exports=function(e,t,r){var i=n(t);i in e?o.f(e,i,a(0,r)):e[i]=r}},47771:(e,t,r)=>{"use strict";var n=r(76887),o=r(78834),a=r(82529),i=r(79417),s=r(57475),l=r(31046),u=r(249),c=r(88929),p=r(90904),f=r(32029),h=r(99754),d=r(99813),m=r(12077),g=r(35143),v=i.PROPER,y=i.CONFIGURABLE,b=g.IteratorPrototype,w=g.BUGGY_SAFARI_ITERATORS,E=d("iterator"),x="keys",_="values",S="entries",A=function(){return this};e.exports=function(e,t,r,i,d,g,k){l(r,t,i);var C,O,j,I=function(e){if(e===d&&M)return M;if(!w&&e in P)return P[e];switch(e){case x:case _:case S:return function(){return new r(this,e)}}return function(){return new r(this)}},N=t+" Iterator",T=!1,P=e.prototype,R=P[E]||P["@@iterator"]||d&&P[d],M=!w&&R||I(d),D="Array"==t&&P.entries||R;if(D&&(C=u(D.call(new e)))!==Object.prototype&&C.next&&(a||u(C)===b||(c?c(C,b):s(C[E])||h(C,E,A)),p(C,N,!0,!0),a&&(m[N]=A)),v&&d==_&&R&&R.name!==_&&(!a&&y?f(P,"name",_):(T=!0,M=function(){return o(R,this)})),d)if(O={values:I(_),keys:g?M:I(x),entries:I(S)},k)for(j in O)(w||T||!(j in P))&&h(P,j,O[j]);else n({target:t,proto:!0,forced:w||T},O);return a&&!k||P[E]===M||h(P,E,M,{name:d}),m[t]=M,O}},66349:(e,t,r)=>{var n=r(54058),o=r(90953),a=r(11477),i=r(65988).f;e.exports=function(e){var t=n.Symbol||(n.Symbol={});o(t,e)||i(t,e,{value:a.f(e)})}},55746:(e,t,r)=>{var n=r(95981);e.exports=!n((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},61333:(e,t,r)=>{var n=r(21899),o=r(10941),a=n.document,i=o(a)&&o(a.createElement);e.exports=function(e){return i?a.createElement(e):{}}},63281:e=>{e.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},34342:(e,t,r)=>{var n=r(2861).match(/firefox\/(\d+)/i);e.exports=!!n&&+n[1]},23321:e=>{e.exports="object"==typeof window},81046:(e,t,r)=>{var n=r(2861);e.exports=/MSIE|Trident/.test(n)},4470:(e,t,r)=>{var n=r(2861),o=r(21899);e.exports=/ipad|iphone|ipod/i.test(n)&&void 0!==o.Pebble},22749:(e,t,r)=>{var n=r(2861);e.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(n)},6049:(e,t,r)=>{var n=r(82532),o=r(21899);e.exports="process"==n(o.process)},58045:(e,t,r)=>{var n=r(2861);e.exports=/web0s(?!.*chrome)/i.test(n)},2861:(e,t,r)=>{var n=r(626);e.exports=n("navigator","userAgent")||""},53385:(e,t,r)=>{var n,o,a=r(21899),i=r(2861),s=a.process,l=a.Deno,u=s&&s.versions||l&&l.version,c=u&&u.v8;c&&(o=(n=c.split("."))[0]>0&&n[0]<4?1:+(n[0]+n[1])),!o&&i&&(!(n=i.match(/Edge\/(\d+)/))||n[1]>=74)&&(n=i.match(/Chrome\/(\d+)/))&&(o=+n[1]),e.exports=o},18938:(e,t,r)=>{var n=r(2861).match(/AppleWebKit\/(\d+)\./);e.exports=!!n&&+n[1]},35703:(e,t,r)=>{var n=r(54058);e.exports=function(e){return n[e+"Prototype"]}},56759:e=>{e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},18780:(e,t,r)=>{var n=r(95981),o=r(31887);e.exports=!n((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",o(1,7)),7!==e.stack)}))},76887:(e,t,r)=>{"use strict";var n=r(21899),o=r(79730),a=r(95329),i=r(57475),s=r(49677).f,l=r(37252),u=r(54058),c=r(86843),p=r(32029),f=r(90953),h=function(e){var t=function(r,n,a){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(r);case 2:return new e(r,n)}return new e(r,n,a)}return o(e,this,arguments)};return t.prototype=e.prototype,t};e.exports=function(e,t){var r,o,d,m,g,v,y,b,w=e.target,E=e.global,x=e.stat,_=e.proto,S=E?n:x?n[w]:(n[w]||{}).prototype,A=E?u:u[w]||p(u,w,{})[w],k=A.prototype;for(d in t)r=!l(E?d:w+(x?".":"#")+d,e.forced)&&S&&f(S,d),g=A[d],r&&(v=e.noTargetGet?(b=s(S,d))&&b.value:S[d]),m=r&&v?v:t[d],r&&typeof g==typeof m||(y=e.bind&&r?c(m,n):e.wrap&&r?h(m):_&&i(m)?a(m):m,(e.sham||m&&m.sham||g&&g.sham)&&p(y,"sham",!0),p(A,d,y),_&&(f(u,o=w+"Prototype")||p(u,o,{}),p(u[o],d,m),e.real&&k&&!k[d]&&p(k,d,m)))}},95981:e=>{e.exports=function(e){try{return!!e()}catch(e){return!0}}},45602:(e,t,r)=>{var n=r(95981);e.exports=!n((function(){return Object.isExtensible(Object.preventExtensions({}))}))},79730:(e,t,r)=>{var n=r(18285),o=Function.prototype,a=o.apply,i=o.call;e.exports="object"==typeof Reflect&&Reflect.apply||(n?i.bind(a):function(){return i.apply(a,arguments)})},86843:(e,t,r)=>{var n=r(95329),o=r(24883),a=r(18285),i=n(n.bind);e.exports=function(e,t){return o(e),void 0===t?e:a?i(e,t):function(){return e.apply(t,arguments)}}},18285:(e,t,r)=>{var n=r(95981);e.exports=!n((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}))},98308:(e,t,r)=>{"use strict";var n=r(21899),o=r(95329),a=r(24883),i=r(10941),s=r(90953),l=r(93765),u=r(18285),c=n.Function,p=o([].concat),f=o([].join),h={},d=function(e,t,r){if(!s(h,t)){for(var n=[],o=0;o{var n=r(18285),o=Function.prototype.call;e.exports=n?o.bind(o):function(){return o.apply(o,arguments)}},79417:(e,t,r)=>{var n=r(55746),o=r(90953),a=Function.prototype,i=n&&Object.getOwnPropertyDescriptor,s=o(a,"name"),l=s&&"something"===function(){}.name,u=s&&(!n||n&&i(a,"name").configurable);e.exports={EXISTS:s,PROPER:l,CONFIGURABLE:u}},95329:(e,t,r)=>{var n=r(18285),o=Function.prototype,a=o.bind,i=o.call,s=n&&a.bind(i,i);e.exports=n?function(e){return e&&s(e)}:function(e){return e&&function(){return i.apply(e,arguments)}}},626:(e,t,r)=>{var n=r(54058),o=r(21899),a=r(57475),i=function(e){return a(e)?e:void 0};e.exports=function(e,t){return arguments.length<2?i(n[e])||i(o[e]):n[e]&&n[e][t]||o[e]&&o[e][t]}},22902:(e,t,r)=>{var n=r(9697),o=r(14229),a=r(12077),i=r(99813)("iterator");e.exports=function(e){if(null!=e)return o(e,i)||o(e,"@@iterator")||a[n(e)]}},53476:(e,t,r)=>{var n=r(21899),o=r(78834),a=r(24883),i=r(96059),s=r(69826),l=r(22902),u=n.TypeError;e.exports=function(e,t){var r=arguments.length<2?l(e):t;if(a(r))return i(o(r,e));throw u(s(e)+" is not iterable")}},14229:(e,t,r)=>{var n=r(24883);e.exports=function(e,t){var r=e[t];return null==r?void 0:n(r)}},21899:(e,t,r)=>{var n=function(e){return e&&e.Math==Math&&e};e.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof r.g&&r.g)||function(){return this}()||Function("return this")()},90953:(e,t,r)=>{var n=r(95329),o=r(89678),a=n({}.hasOwnProperty);e.exports=Object.hasOwn||function(e,t){return a(o(e),t)}},27748:e=>{e.exports={}},34845:(e,t,r)=>{var n=r(21899);e.exports=function(e,t){var r=n.console;r&&r.error&&(1==arguments.length?r.error(e):r.error(e,t))}},15463:(e,t,r)=>{var n=r(626);e.exports=n("document","documentElement")},2840:(e,t,r)=>{var n=r(55746),o=r(95981),a=r(61333);e.exports=!n&&!o((function(){return 7!=Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a}))},37026:(e,t,r)=>{var n=r(21899),o=r(95329),a=r(95981),i=r(82532),s=n.Object,l=o("".split);e.exports=a((function(){return!s("z").propertyIsEnumerable(0)}))?function(e){return"String"==i(e)?l(e,""):s(e)}:s},81302:(e,t,r)=>{var n=r(95329),o=r(57475),a=r(63030),i=n(Function.toString);o(a.inspectSource)||(a.inspectSource=function(e){return i(e)}),e.exports=a.inspectSource},53794:(e,t,r)=>{var n=r(10941),o=r(32029);e.exports=function(e,t){n(t)&&"cause"in t&&o(e,"cause",t.cause)}},21647:(e,t,r)=>{var n=r(76887),o=r(95329),a=r(27748),i=r(10941),s=r(90953),l=r(65988).f,u=r(10946),c=r(684),p=r(91584),f=r(99418),h=r(45602),d=!1,m=f("meta"),g=0,v=function(e){l(e,m,{value:{objectID:"O"+g++,weakData:{}}})},y=e.exports={enable:function(){y.enable=function(){},d=!0;var e=u.f,t=o([].splice),r={};r[m]=1,e(r).length&&(u.f=function(r){for(var n=e(r),o=0,a=n.length;o{var n,o,a,i=r(38019),s=r(21899),l=r(95329),u=r(10941),c=r(32029),p=r(90953),f=r(63030),h=r(44262),d=r(27748),m="Object already initialized",g=s.TypeError,v=s.WeakMap;if(i||f.state){var y=f.state||(f.state=new v),b=l(y.get),w=l(y.has),E=l(y.set);n=function(e,t){if(w(y,e))throw new g(m);return t.facade=e,E(y,e,t),t},o=function(e){return b(y,e)||{}},a=function(e){return w(y,e)}}else{var x=h("state");d[x]=!0,n=function(e,t){if(p(e,x))throw new g(m);return t.facade=e,c(e,x,t),t},o=function(e){return p(e,x)?e[x]:{}},a=function(e){return p(e,x)}}e.exports={set:n,get:o,has:a,enforce:function(e){return a(e)?o(e):n(e,{})},getterFor:function(e){return function(t){var r;if(!u(t)||(r=o(t)).type!==e)throw g("Incompatible receiver, "+e+" required");return r}}}},6782:(e,t,r)=>{var n=r(99813),o=r(12077),a=n("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(o.Array===e||i[a]===e)}},1052:(e,t,r)=>{var n=r(82532);e.exports=Array.isArray||function(e){return"Array"==n(e)}},57475:e=>{e.exports=function(e){return"function"==typeof e}},24284:(e,t,r)=>{var n=r(95329),o=r(95981),a=r(57475),i=r(9697),s=r(626),l=r(81302),u=function(){},c=[],p=s("Reflect","construct"),f=/^\s*(?:class|function)\b/,h=n(f.exec),d=!f.exec(u),m=function(e){if(!a(e))return!1;try{return p(u,c,e),!0}catch(e){return!1}},g=function(e){if(!a(e))return!1;switch(i(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return d||!!h(f,l(e))}catch(e){return!0}};g.sham=!0,e.exports=!p||o((function(){var e;return m(m.call)||!m(Object)||!m((function(){e=!0}))||e}))?g:m},37252:(e,t,r)=>{var n=r(95981),o=r(57475),a=/#|\.prototype\./,i=function(e,t){var r=l[s(e)];return r==c||r!=u&&(o(t)?n(t):!!t)},s=i.normalize=function(e){return String(e).replace(a,".").toLowerCase()},l=i.data={},u=i.NATIVE="N",c=i.POLYFILL="P";e.exports=i},10941:(e,t,r)=>{var n=r(57475);e.exports=function(e){return"object"==typeof e?null!==e:n(e)}},82529:e=>{e.exports=!0},60685:(e,t,r)=>{var n=r(10941),o=r(82532),a=r(99813)("match");e.exports=function(e){var t;return n(e)&&(void 0!==(t=e[a])?!!t:"RegExp"==o(e))}},56664:(e,t,r)=>{var n=r(21899),o=r(626),a=r(57475),i=r(7046),s=r(32302),l=n.Object;e.exports=s?function(e){return"symbol"==typeof e}:function(e){var t=o("Symbol");return a(t)&&i(t.prototype,l(e))}},93091:(e,t,r)=>{var n=r(21899),o=r(86843),a=r(78834),i=r(96059),s=r(69826),l=r(6782),u=r(10623),c=r(7046),p=r(53476),f=r(22902),h=r(7609),d=n.TypeError,m=function(e,t){this.stopped=e,this.result=t},g=m.prototype;e.exports=function(e,t,r){var n,v,y,b,w,E,x,_=r&&r.that,S=!(!r||!r.AS_ENTRIES),A=!(!r||!r.IS_ITERATOR),k=!(!r||!r.INTERRUPTED),C=o(t,_),O=function(e){return n&&h(n,"normal",e),new m(!0,e)},j=function(e){return S?(i(e),k?C(e[0],e[1],O):C(e[0],e[1])):k?C(e,O):C(e)};if(A)n=e;else{if(!(v=f(e)))throw d(s(e)+" is not iterable");if(l(v)){for(y=0,b=u(e);b>y;y++)if((w=j(e[y]))&&c(g,w))return w;return new m(!1)}n=p(e,v)}for(E=n.next;!(x=a(E,n)).done;){try{w=j(x.value)}catch(e){h(n,"throw",e)}if("object"==typeof w&&w&&c(g,w))return w}return new m(!1)}},7609:(e,t,r)=>{var n=r(78834),o=r(96059),a=r(14229);e.exports=function(e,t,r){var i,s;o(e);try{if(!(i=a(e,"return"))){if("throw"===t)throw r;return r}i=n(i,e)}catch(e){s=!0,i=e}if("throw"===t)throw r;if(s)throw i;return o(i),r}},35143:(e,t,r)=>{"use strict";var n,o,a,i=r(95981),s=r(57475),l=r(29290),u=r(249),c=r(99754),p=r(99813),f=r(82529),h=p("iterator"),d=!1;[].keys&&("next"in(a=[].keys())?(o=u(u(a)))!==Object.prototype&&(n=o):d=!0),null==n||i((function(){var e={};return n[h].call(e)!==e}))?n={}:f&&(n=l(n)),s(n[h])||c(n,h,(function(){return this})),e.exports={IteratorPrototype:n,BUGGY_SAFARI_ITERATORS:d}},12077:e=>{e.exports={}},10623:(e,t,r)=>{var n=r(43057);e.exports=function(e){return n(e.length)}},66132:(e,t,r)=>{var n,o,a,i,s,l,u,c,p=r(21899),f=r(86843),h=r(49677).f,d=r(42941).set,m=r(22749),g=r(4470),v=r(58045),y=r(6049),b=p.MutationObserver||p.WebKitMutationObserver,w=p.document,E=p.process,x=p.Promise,_=h(p,"queueMicrotask"),S=_&&_.value;S||(n=function(){var e,t;for(y&&(e=E.domain)&&e.exit();o;){t=o.fn,o=o.next;try{t()}catch(e){throw o?i():a=void 0,e}}a=void 0,e&&e.enter()},m||y||v||!b||!w?!g&&x&&x.resolve?((u=x.resolve(void 0)).constructor=x,c=f(u.then,u),i=function(){c(n)}):y?i=function(){E.nextTick(n)}:(d=f(d,p),i=function(){d(n)}):(s=!0,l=w.createTextNode(""),new b(n).observe(l,{characterData:!0}),i=function(){l.data=s=!s})),e.exports=S||function(e){var t={fn:e,next:void 0};a&&(a.next=t),o||(o=t,i()),a=t}},19297:(e,t,r)=>{var n=r(21899);e.exports=n.Promise},72497:(e,t,r)=>{var n=r(53385),o=r(95981);e.exports=!!Object.getOwnPropertySymbols&&!o((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&n&&n<41}))},28468:(e,t,r)=>{var n=r(95981),o=r(99813),a=r(82529),i=o("iterator");e.exports=!n((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,r="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),r+=n+e})),a&&!e.toJSON||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[i]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==r||"x"!==new URL("http://x",void 0).host}))},38019:(e,t,r)=>{var n=r(21899),o=r(57475),a=r(81302),i=n.WeakMap;e.exports=o(i)&&/native code/.test(a(i))},69520:(e,t,r)=>{"use strict";var n=r(24883),o=function(e){var t,r;this.promise=new e((function(e,n){if(void 0!==t||void 0!==r)throw TypeError("Bad Promise constructor");t=e,r=n})),this.resolve=n(t),this.reject=n(r)};e.exports.f=function(e){return new o(e)}},14649:(e,t,r)=>{var n=r(85803);e.exports=function(e,t){return void 0===e?arguments.length<2?"":t:n(e)}},70344:(e,t,r)=>{var n=r(21899),o=r(60685),a=n.TypeError;e.exports=function(e){if(o(e))throw a("The method doesn't accept regular expressions");return e}},24420:(e,t,r)=>{"use strict";var n=r(55746),o=r(95329),a=r(78834),i=r(95981),s=r(14771),l=r(87857),u=r(36760),c=r(89678),p=r(37026),f=Object.assign,h=Object.defineProperty,d=o([].concat);e.exports=!f||i((function(){if(n&&1!==f({b:1},f(h({},"a",{enumerable:!0,get:function(){h(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},r=Symbol(),o="abcdefghijklmnopqrst";return e[r]=7,o.split("").forEach((function(e){t[e]=e})),7!=f({},e)[r]||s(f({},t)).join("")!=o}))?function(e,t){for(var r=c(e),o=arguments.length,i=1,f=l.f,h=u.f;o>i;)for(var m,g=p(arguments[i++]),v=f?d(s(g),f(g)):s(g),y=v.length,b=0;y>b;)m=v[b++],n&&!a(h,g,m)||(r[m]=g[m]);return r}:f},29290:(e,t,r)=>{var n,o=r(96059),a=r(59938),i=r(56759),s=r(27748),l=r(15463),u=r(61333),c=r(44262),p=c("IE_PROTO"),f=function(){},h=function(e){return"