diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..101afd1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** +- OS: [e.g. iOS] +- Browser [e.g. chrome, safari] +- Version [e.g. 22] + +**Smartphone (please complete the following information):** +- Device: [e.g. iPhone6] +- OS: [e.g. iOS8.1] +- Browser [e.g. stock browser, safari] +- Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..24473de --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/.github/funding.yml b/.github/funding.yml new file mode 100644 index 0000000..758470e --- /dev/null +++ b/.github/funding.yml @@ -0,0 +1 @@ +github: [YidiDev, coal-rock] \ No newline at end of file diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 0000000..3d7182e --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,20 @@ +name-template: 'v Release $NEXT_PATCH_VERSION 🌈' +tag-template: 'v$NEXT_PATCH_VERSION' +categories: + - title: '🚀 Features' + labels: + - 'feature' + - 'enhancement' + - title: '🐛 Bug Fixes' + labels: + - 'fix' + - 'bugfix' + - 'bug' + - title: '🧰 Maintenance' + label: 'chore' +change-template: '- $TITLE @$AUTHOR (#$NUMBER)' +change-title-escapes: '\<*_&' +template: | + ## Changes + + $CHANGES \ No newline at end of file diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml new file mode 100644 index 0000000..cbd2d33 --- /dev/null +++ b/.github/workflows/create-release.yml @@ -0,0 +1,31 @@ +name: Create Release + +on: + push: + tags: + - 'v*.*.*' + +permissions: + contents: write + pull-requests: read + +jobs: + create_release: + name: Create Release + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Generate Release Notes and Publish + id: generate_release_notes + uses: release-drafter/release-drafter@v6 + with: + config-name: 'release-drafter.yml' + name: "Release ${{ github.ref_name }}" + tag: ${{ github.ref_name }} + publish: true + prerelease: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..b9b2873 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,31 @@ +name: Tests + +on: + push: + branches: + - dev + - main + pull_request: + branches: + - dev + - main + +jobs: + test: + runs-on: ubuntu-latest + + if: "!contains(github.event.head_commit.message, '[skip ci]')" + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install Docker Compose + run: | + sudo apt-get update + sudo apt-get install -y docker-compose + + - name: Build and Test with Docker Compose + run: | + cd "${GITHUB_WORKSPACE}" + docker-compose up --build --abort-on-container-exit \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b9f4981 --- /dev/null +++ b/.gitignore @@ -0,0 +1,94 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build output +*.test +*.out + +# Go workspace folders and build cache +/pkg/ +/bin/ +/cmd/ + +# Go module download cache (go version 1.11+) +# It's common to store modules in the GOPATH/pkg/mod directory. +# Uncomment if using modules. +# /vendor/ + +# Standard Go build generated files +*.a +*.o +*.obj + +# Editor specific files +*~ + +# Logs & debugging +*.log + +# IDE specific files (JetBrains GoLand) +.idea/ +*.iml + +# JetBrains Project-specific settings +.idea/* + +# Mac and Linux specific files +.DS_Store +.Trashes +._* +.Spotlight-V100 +.fseventsd + +# Windows specific files +Thumbs.db +desktop.ini +$RECYCLE.BIN/ + +# Editor backup/swap files +*.swp +*.swo +*.tmp +*.bak +*.orig + +# Dependency directories +vendor/ + +# Ignore local environment configuration +.env +.env.local +.env.* + +# IDE specific settings and metadata folders +.vscode/ +.venv/ + +# GoLand run configurations +.idea/runConfigurations/ + +# GoLand specific cache directories +.idea/workspace.xml +.idea/assetWizardSettings.xml +.idea/tasks.xml +.idea/vcs.xml +.idea/gradle.xml +.idea/misc.xml +.idea/modules.xml + +# GoLand local history +.idea/localHistory + +# Go workspace specific directories (for GOPATH) +Godeps/ + + +*db +/coverage + +/tmp +example/tmp diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..c9388a5 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders 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, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +yididev@gmail.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a28022d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,88 @@ +# Contributing to Go Advanced Admin + +We welcome contributions to the Go Advanced Admin Library project! Whether you are reporting a bug, suggesting an enhancement, or creating a pull request, we appreciate your support and are here to help make the process as smooth as possible. + +## How to Contribute + +### Reporting Bugs + +If you encounter a bug or have a question, please open an issue on GitHub. When reporting a bug, provide as much detail as possible to help us diagnose and fix the issue efficiently. This includes: + +- A clear and descriptive title. +- Steps to reproduce the issue. +- Expected behavior. +- Actual behavior. +- Relevant logs, screenshots, or code snippets. + +### Suggesting Enhancements + +Enhancement suggestions are also welcome! Please open an issue and describe your idea in detail. Consider including: + +- A clear and descriptive title. +- A detailed description of the enhancement and why it would be useful. +- Any examples or code snippets if applicable. + +### Submitting Pull Requests + +To implement a new feature, fix a bug, or improve documentation: + +1. **Fork the Repository** + + Create a personal fork of the repository on GitHub. + +2. **Clone the Fork** + + ```sh + git clone https://github.com/go-advanced-admin/web-echo.git + cd web-echo + ``` + +3. **Create a New Branch** + + Use a descriptive branch name that includes the purpose of the branch: + + ```sh + git checkout -b feature/your-feature-name + ``` + +4. **Make Changes** + + Implement your changes following the project's coding style. + +5. **Commit Changes** + + Write a concise commit message: + + ```sh + git commit -am 'Add feature/bugfix-xyz' + ``` + +6. **Push the Branch** + + Push your branch to your fork on GitHub: + + ```sh + git push origin feature/your-feature-name + ``` + +7. **Create a Pull Request** + + Open a pull request on the original repository. Include a clear and descriptive title and a detailed description of your changes. + +### Code Style and Standards + +Please follow these conventions to maintain consistency: + +- Use **Go** coding conventions. +- Write **unit tests** for new features and bug fixes. +- Ensure existing tests pass by running `go test ./...`. + +### Code of Conduct + +By participating in this project, you agree to abide by the [Code of Conduct](CODE_OF_CONDUCT.md). + +## Questions + +If you have any questions or need further assistance, feel free to open an issue or reach out to the maintainers of this project. + +Thank you for contributing! \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5a54c78 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,7 @@ +Copyright 2024 Go Advanced Admin + +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. \ No newline at end of file diff --git a/README.md b/README.md index 8e03fd4..d980971 100644 --- a/README.md +++ b/README.md @@ -1 +1,23 @@ -# orm-gorm \ No newline at end of file +# Go Advanced Admin ORM GORM + +A Highly Customizable Advanced Admin Panel for Go (Still in development a lot) GORM Integration + +[![go report card](https://goreportcard.com/badge/github.com/go-advanced-admin/web-echo "go report card")](https://goreportcard.com/report/github.com/go-advanced-admin/web-echo) +[![Go](https://github.com/go-advanced-admin/web-echo/actions/workflows/tests.yml/badge.svg)](https://github.com/go-advanced-admin/web-echo/actions/workflows/tests.yml) +[![MIT license](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://opensource.org/licenses/MIT) +[![Go.Dev reference](https://img.shields.io/badge/go.dev-reference-blue?logo=go&logoColor=white)](https://pkg.go.dev/github.com/go-advanced-admin/web-echo?tab=doc) + +## Installation + +Add the module to your project by running: + +```sh +go get github.com/go-advanced-admin/orm-gorm +``` + +## Contributing +Contributions are always welcome! If you're interested in contributing to the project, please take a look at our [Contributing Guidelines](CONTRIBUTING.md) file for guidelines on how to get started. We appreciate your help in improving the library! + +Special Thank you to the following current maintainers: +- [Yidi Sprei](https://github.com/YidiDev) +- [{{ Insert preferred name }}](https://github.com/coal-rock) \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..3664f39 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,41 @@ +# Security Policy + +## Supported Versions + +We release patches for security vulnerabilities affecting supported versions of the project. Our current policy is: + +| Version | Supported | +| ------- | ------------------ | +| 1.0.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +We take all security vulnerabilities seriously. If you discover a security issue, please report it to us privately. Do not create a public issue. Here’s how you can report a security vulnerability: + +1. **Email us directly at**: [yididev@gmail.com](mailto:yididev@gmail.com) +2. Provide a detailed description of the vulnerability, including steps to reproduce it. +3. Include any relevant logs or screenshots that can help in identifying and solving the issue. + +## Handling Security Issues + +1. **Acknowledgment**: We will acknowledge the receipt of your report within 48 hours and communicate with you to understand and validate the issue. +2. **Assessment**: We will conduct a thorough assessment of the vulnerability to determine its impact and the urgency of the fix. +3. **Resolution**: We aim to resolve critical security issues within 7 days. After the resolution, we will issue a patch and update the affected parties. +4. **Disclosure**: Once a fix is implemented, we will publicly disclose the nature of the vulnerability and encourage users to update to the patched version. + +## Best Practices for Users + +1. **Keep your software updated**: Always use the latest version of `go-advanced-admin` and all its projects to ensure you have the latest security patches and improvements. +2. **Review and Audit**: Regularly review and audit the dependencies of your project for potential vulnerabilities. +3. **Limit Scope**: Follow the principle of least privilege by limiting the scope of access and permissions of applications using this library. + +## Public Disclosure + +We believe in responsible disclosure and will work with researchers and users to ensure vulnerabilities are patched before any details are released. We appreciate your cooperation in keeping our library secure. + +## Contact + +If you have any questions or need further information regarding our security policy, do not hesitate to contact us at [yididev@gmail.com](mailto:yididev@gmail.com). + +Thank you for helping us keep `go-advanced-admin` secure. \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..32bc0c1 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,7 @@ +services: + root-tests: + build: + context: . + dockerfile: testing/Dockerfile-root + volumes: + - .:/app diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..dbe00b7 --- /dev/null +++ b/go.mod @@ -0,0 +1,11 @@ +module github.com/go-advanced-admin/orm-gorm + +go 1.23.1 + +require gorm.io/gorm v1.25.12 + +require ( + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + golang.org/x/text v0.14.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..61ad400 --- /dev/null +++ b/go.sum @@ -0,0 +1,8 @@ +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= +gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= diff --git a/integrator.go b/integrator.go new file mode 100644 index 0000000..bde0457 --- /dev/null +++ b/integrator.go @@ -0,0 +1,316 @@ +package admingorm + +import ( + "fmt" + "gorm.io/gorm" + "reflect" + "strings" +) + +type Integrator struct { + DB *gorm.DB +} + +func NewIntegrator(db *gorm.DB) *Integrator { + return &Integrator{DB: db} +} + +func (i *Integrator) GetPrimaryKeyValue(model interface{}) (interface{}, error) { + modelValue := reflect.ValueOf(model) + + if modelValue.Kind() == reflect.Ptr { + if modelValue.IsNil() { + return nil, fmt.Errorf("model pointer is nil") + } + modelValue = modelValue.Elem() + } else if modelValue.Kind() != reflect.Struct { + return nil, fmt.Errorf("model is neither a struct nor a pointer to a struct") + } + + modelType := modelValue.Type() + + stmt := &gorm.Statement{DB: i.DB} + err := stmt.Parse(reflect.New(modelType).Interface()) + if err != nil { + return nil, fmt.Errorf("failed to parse model: %v", err) + } + + primaryField := stmt.Schema.PrioritizedPrimaryField + if primaryField == nil { + return nil, fmt.Errorf("no primary field found for model %s", modelType.Name()) + } + + primaryKeyValue := modelValue.FieldByName(primaryField.Name) + if !primaryKeyValue.IsValid() { + return nil, fmt.Errorf("primary key field %s not found in model %s", primaryField.Name, modelType.Name()) + } + + return primaryKeyValue.Interface(), nil +} + +func (i *Integrator) GetPrimaryKeyType(model interface{}) (reflect.Type, error) { + modelValue := reflect.ValueOf(model) + + if modelValue.Kind() == reflect.Ptr { + if modelValue.IsNil() { + return nil, fmt.Errorf("model pointer is nil") + } + modelValue = modelValue.Elem() + } else if modelValue.Kind() != reflect.Struct { + return nil, fmt.Errorf("model is neither a struct nor a pointer to a struct") + } + + modelType := modelValue.Type() + + stmt := &gorm.Statement{DB: i.DB} + err := stmt.Parse(reflect.New(modelType).Interface()) + if err != nil { + return nil, fmt.Errorf("failed to parse model: %v", err) + } + + primaryField := stmt.Schema.PrioritizedPrimaryField + if primaryField == nil { + return nil, fmt.Errorf("no primary field found for model %s", modelType.Name()) + } + + primaryKeyField, found := modelType.FieldByName(primaryField.Name) + + if !found { + return nil, fmt.Errorf("primary key field %s not found in model %s", primaryField.Name, modelType.Name()) + } + + return primaryKeyField.Type, nil +} + +func (i *Integrator) FetchInstances(model interface{}) (interface{}, error) { + modelType := reflect.TypeOf(model).Elem() + sliceType := reflect.SliceOf(modelType) + instances := reflect.New(sliceType).Interface() + + err := i.DB.Find(instances, model).Error + if err != nil { + return nil, err + } + + return instances, nil +} + +func (i *Integrator) FetchInstancesOnlyFields(model interface{}, fields []string) (interface{}, error) { + modelType := reflect.TypeOf(model).Elem() + sliceType := reflect.SliceOf(modelType) + instances := reflect.New(sliceType).Interface() + + selectFields := make([]string, len(fields)) + for idx, fieldName := range fields { + field, found := modelType.FieldByName(fieldName) + if found { + selectFields[idx] = getGormColumnName(field) + } else { + return nil, fmt.Errorf("field %s not foun in model", fieldName) + } + } + + selectFieldStr := strings.Join(selectFields, ", ") + + err := i.DB.Select(selectFieldStr).Find(instances, model).Error + if err != nil { + return nil, err + } + + return instances, nil +} + +func (i *Integrator) FetchInstancesOnlyFieldWithSearch(model interface{}, fields []string, query string, searchFields []string) (interface{}, error) { + modelType := reflect.TypeOf(model).Elem() + sliceType := reflect.SliceOf(modelType) + instances := reflect.New(sliceType).Interface() + + selectFields := make([]string, len(fields)) + for idx, fieldName := range fields { + field, found := modelType.FieldByName(fieldName) + if found { + selectFields[idx] = getGormColumnName(field) + } else { + return nil, fmt.Errorf("field %s not found in model", fieldName) + } + } + selectFieldStr := strings.Join(selectFields, ", ") + + var searchConditions []string + var searchArgs []interface{} + for _, searchField := range searchFields { + field, found := modelType.FieldByName(searchField) + if found { + columnName := getGormColumnName(field) + searchConditions = append(searchConditions, fmt.Sprintf("%s LIKE ?", columnName)) + searchArgs = append(searchArgs, "%"+query+"%") + } else { + return nil, fmt.Errorf("field %s not found in model", searchField) + } + } + searchConditionStr := strings.Join(searchConditions, " OR ") + + err := i.DB.Select(selectFieldStr).Where(searchConditionStr, searchArgs...).Find(instances, model).Error + if err != nil { + return nil, err + } + + return instances, nil +} + +func (i *Integrator) DeleteInstance(model interface{}, instanceID interface{}) error { + modelType := reflect.TypeOf(model).Elem() + + stmt := &gorm.Statement{DB: i.DB} + err := stmt.Parse(model) + if err != nil { + return fmt.Errorf("failed to parse model: %v", err) + } + + primaryField := stmt.Schema.PrioritizedPrimaryField + if primaryField == nil { + return fmt.Errorf("no primary field found for model %s", modelType.Name()) + } + + primaryKey := primaryField.DBName + + condition := map[string]interface{}{primaryKey: instanceID} + + result := i.DB.Where(condition).Delete(model) + if result.Error != nil { + return result.Error + } + + fmt.Printf("Deleted %d instances of %s\n", result.RowsAffected, modelType.Name()) + + if result.RowsAffected == 0 { + return fmt.Errorf("no instance found with %s = %v", primaryKey, instanceID) + } + + return nil +} + +func (i *Integrator) FetchInstanceOnlyFields(model interface{}, id interface{}, fields []string) (interface{}, error) { + modelType := reflect.TypeOf(model).Elem() + instance := reflect.New(modelType).Interface() + + selectFields := make([]string, len(fields)) + for idx, fieldName := range fields { + field, found := modelType.FieldByName(fieldName) + if found { + selectFields[idx] = getGormColumnName(field) + } else { + return nil, fmt.Errorf("field %s not found in model", fieldName) + } + } + selectFieldStr := strings.Join(selectFields, ", ") + + stmt := &gorm.Statement{DB: i.DB} + err := stmt.Parse(model) + if err != nil { + return nil, fmt.Errorf("failed to parse model: %v", err) + } + + primaryField := stmt.Schema.PrioritizedPrimaryField + if primaryField == nil { + return nil, fmt.Errorf("no primary field found for model %s", modelType.Name()) + } + + primaryKey := primaryField.DBName + err = i.DB.Select(selectFieldStr).Where(fmt.Sprintf("%s = ?", primaryKey), id).First(instance, model).Error + if err != nil { + return nil, err + } + + return instance, nil +} + +func (i *Integrator) FetchInstance(model interface{}, instanceID interface{}) (interface{}, error) { + modelType := reflect.TypeOf(model).Elem() + instance := reflect.New(modelType).Interface() + + stmt := &gorm.Statement{DB: i.DB} + err := stmt.Parse(model) + if err != nil { + return nil, fmt.Errorf("failed to parse model: %v", err) + } + + primaryField := stmt.Schema.PrioritizedPrimaryField + if primaryField == nil { + return nil, fmt.Errorf("no primary field found for model %s", modelType.Name()) + } + + primaryKey := primaryField.DBName + err = i.DB.Where(fmt.Sprintf("%s = ?", primaryKey), instanceID).First(instance, model).Error + if err != nil { + return nil, err + } + + return instance, nil +} + +func (i *Integrator) CreateInstance(instance interface{}) error { + return i.DB.Create(instance).Error +} + +func (i *Integrator) UpdateInstance(instance interface{}, primaryKey interface{}) error { + modelType := reflect.TypeOf(instance).Elem() + + stmt := &gorm.Statement{DB: i.DB} + if err := stmt.Parse(instance); err != nil { + return fmt.Errorf("failed to parse model: %v", err) + } + + primaryField := stmt.Schema.PrioritizedPrimaryField + if primaryField == nil { + return fmt.Errorf("no primary field found for model %s", modelType.Name()) + } + + primaryKeyDBName := primaryField.DBName + + return i.DB.Model(instance).Where(fmt.Sprintf("%s = ?", primaryKeyDBName), primaryKey).Save(instance).Error +} + +func (i *Integrator) CreateInstanceOnlyFields(instance interface{}, fields []string) error { + if len(fields) == 0 { + return i.DB.Create(instance).Error + } + + return i.DB.Select(fields).Create(instance).Error +} + +func (i *Integrator) UpdateInstanceOnlyFields(instance interface{}, fields []string, primaryKey interface{}) error { + modelType := reflect.TypeOf(instance).Elem() + modelValue := reflect.ValueOf(instance).Elem() + + stmt := &gorm.Statement{DB: i.DB} + if err := stmt.Parse(instance); err != nil { + return fmt.Errorf("failed to parse model: %v", err) + } + + primaryField := stmt.Schema.PrioritizedPrimaryField + if primaryField == nil { + return fmt.Errorf("no primary field found for model %s", modelType.Name()) + } + + primaryKeyDBName := primaryField.DBName + + if len(fields) == 0 { + return i.DB.Model(instance).Where(fmt.Sprintf("%s = ?", primaryKeyDBName), primaryKey).Save(instance).Error + } + + updateData := make(map[string]interface{}) + for _, fieldName := range fields { + fieldValue := modelValue.FieldByName(fieldName) + if !fieldValue.IsValid() { + return fmt.Errorf("field %s not found in model", fieldName) + } + updateData[fieldName] = fieldValue.Interface() + } + if _, exists := updateData[primaryField.Name]; !exists { + updateData[primaryField.Name] = primaryKey + fields = append(fields, primaryField.Name) + } + + return i.DB.Model(instance).Where(fmt.Sprintf("%s = ?", primaryKeyDBName), primaryKey).Select(fields).Updates(updateData).Error +} diff --git a/testing/Dockerfile-root b/testing/Dockerfile-root new file mode 100644 index 0000000..5945aa2 --- /dev/null +++ b/testing/Dockerfile-root @@ -0,0 +1,11 @@ +FROM golang:1.23 + +WORKDIR /app + +COPY ../go.mod go.sum ./ + +RUN go mod download && go mod verify + +COPY .. . + +CMD ["go", "test", "-v", "./..."] diff --git a/utils.go b/utils.go new file mode 100644 index 0000000..ebd1ace --- /dev/null +++ b/utils.go @@ -0,0 +1,20 @@ +package admingorm + +import ( + "reflect" + "strings" +) + +func getGormColumnName(structField reflect.StructField) string { + tag, ok := structField.Tag.Lookup("gorm") + if !ok { + return structField.Name + } + tagParts := strings.Split(tag, ";") + for _, part := range tagParts { + if strings.HasPrefix(part, "column:") { + return strings.TrimPrefix(part, "column:") + } + } + return structField.Name +}