diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..922ee27 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @hashicorp/terraform-devex diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..0c8b092 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,5 @@ +# Code of Conduct + +HashiCorp Community Guidelines apply to you when interacting with the community here on GitHub and contributing code. + +Please read the full text at https://www.hashicorp.com/community-guidelines diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..73bb4d3 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,15 @@ +# See GitHub's documentation for more information on this file: +# https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates +version: 2 +updates: + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "daily" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + # TODO: Dependabot only updates hashicorp GHAs in the template repository, the following lines can be removed for consumers of this template + allow: + - dependency-name: "hashicorp/*" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..31a4295 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,41 @@ +# Terraform Provider release workflow. +name: Release + +# This GitHub action creates a release when a tag that matches the pattern +# "v*" (e.g. v0.1.0) is created. +on: + push: + tags: + - 'v*' + +# Releases need permissions to read and write the repository contents. +# GitHub considers creating releases and uploading assets as writing contents. +permissions: + contents: write + +jobs: + goreleaser: + runs-on: linux + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + with: + # Allow goreleaser to access older tag information. + fetch-depth: 0 + - uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0 + with: + go-version-file: 'go.mod' + cache: true + - name: Import GPG key + uses: crazy-max/ghaction-import-gpg@01dd5d3ca463c7f10f7f4f7b4f177225ac661ee4 # v6.1.0 + id: import_gpg + with: + gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} + passphrase: ${{ secrets.PASSPHRASE }} + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@7ec5c2b0c6cdda6e8bbb49444bc797dd33d74dd8 # v5.0.0 + with: + args: release --clean + env: + # GitHub sets the GITHUB_TOKEN secret automatically. + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..7827c97 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,85 @@ +# Terraform Provider testing workflow. +name: Tests + +# This GitHub action runs your tests for each pull request and push. +# Optionally, you can turn it on using a schedule for regular testing. +on: + pull_request: + paths-ignore: + - 'README.md' + push: + paths-ignore: + - 'README.md' + +# Testing only needs permissions to read the repository contents. +permissions: + contents: read + +jobs: + # Ensure project builds before running testing matrix + build: + name: Build + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0 + with: + go-version-file: 'go.mod' + cache: true + - run: go mod download + - run: go build -v . + - name: Run linters + uses: golangci/golangci-lint-action@3cfe3a4abbb849e10058ce4af15d205b6da42804 # v4.0.0 + with: + version: latest + + generate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0 + with: + go-version-file: 'go.mod' + cache: true + - uses: hashicorp/setup-terraform@651471c36a6092792c552e8b1bef71e592b462d8 # v3.1.1 + with: + terraform_version: '1.9.4' + terraform_wrapper: false + - run: go generate ./... + - name: git diff + run: | + git diff --compact-summary --exit-code || \ + (echo; echo "Unexpected difference in directories after code generation. Run 'go generate ./...' command and commit."; exit 1) + + # Run acceptance tests in a matrix with Terraform CLI versions + test: + name: Terraform Provider Acceptance Tests + needs: build + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + # list whatever Terraform versions here you would like to support + terraform: + - '1.5.*' + - '1.6.*' + - '1.7.*' + - '1.8.*' + - '1.9.*' + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0 + with: + go-version-file: 'go.mod' + cache: true + - uses: hashicorp/setup-terraform@651471c36a6092792c552e8b1bef71e592b462d8 # v3.1.1 + with: + terraform_version: ${{ matrix.terraform }} + terraform_wrapper: false + - run: go mod download + - env: + TF_ACC: "1" + run: go test -v -cover ./internal/provider/ + timeout-minutes: 10 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1eac76d --- /dev/null +++ b/.gitignore @@ -0,0 +1,36 @@ +*.dll +*.exe +.DS_Store +example.tf +terraform.tfplan +terraform.tfstate +bin/ +dist/ +modules-dev/ +/pkg/ +website/.vagrant +website/.bundle +website/build +website/node_modules +.vagrant/ +*.backup +./*.tfstate +.terraform/ +*.log +*.bak +*~ +.*.swp +.idea +*.iml +*.test +*.iml + +website/vendor + +# Test exclusions +!command/test-fixtures/**/*.tfstate +!command/test-fixtures/**/.terraform/ + +# Keep windows files with windows line endings +*.winfile eol=crlf +examples/provider-install-verification diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..b68e0b5 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,27 @@ +# Visit https://golangci-lint.run/ for usage documentation +# and information on other useful linters +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + +linters: + disable-all: true + enable: + - durationcheck + - errcheck + - exportloopref + - forcetypeassert + - godot + - gofmt + - gosimple + - ineffassign + - makezero + - misspell + - nilerr + - predeclared + - staticcheck + - tenv + - unconvert + - unparam + - unused + - govet \ No newline at end of file diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..caa09b0 --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,61 @@ +# yaml-language-server: $schema=https://goreleaser.com/static/schema.json +# See https://goreleaser.com/customization/ for more information +version: 2 +before: + hooks: + - go generate ./... + - go mod tidy +builds: + - env: + # goreleaser does not work with CGO, it could also complicate + # usage by users in CI/CD systems like Terraform Cloud where + # they are unable to install libraries. + - CGO_ENABLED=0 + mod_timestamp: "{{ .CommitTimestamp }}" + flags: + - -trimpath + ldflags: + - "-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}" + goos: + # - freebsd + # - windows + - linux + - darwin + goarch: + - amd64 + - arm64 + # - '386' + # - arm + # ignore: + # - goos: darwin + # goarch: '386' + binary: "{{ .ProjectName }}_v{{ .Version }}" +archives: + - format: zip + name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" +checksum: + extra_files: + - glob: "terraform-registry-manifest.json" + name_template: "{{ .ProjectName }}_{{ .Version }}_manifest.json" + name_template: "{{ .ProjectName }}_{{ .Version }}_SHA256SUMS" + algorithm: sha256 +signs: + - artifacts: checksum + args: + # if you are using this in a GitHub action or some other automated pipeline, you + # need to pass the batch flag to indicate its not interactive. + - "--batch" + - "--local-user" + - "{{ .Env.GPG_FINGERPRINT }}" # set this environment variable for your signing key + - "--output" + - "${signature}" + - "--detach-sign" + - "${artifact}" +release: + extra_files: + - glob: "terraform-registry-manifest.json" + name_template: "{{ .ProjectName }}_{{ .Version }}_manifest.json" + # If you want to manually examine the release before its live, uncomment this line: + # draft: true +changelog: + disable: true diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..b76e247 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.1.0 (Unreleased) + +FEATURES: diff --git a/GNUmakefile b/GNUmakefile new file mode 100644 index 0000000..7771cd6 --- /dev/null +++ b/GNUmakefile @@ -0,0 +1,6 @@ +default: testacc + +# Run acceptance tests +.PHONY: testacc +testacc: + TF_ACC=1 go test ./... -v $(TESTARGS) -timeout 120m diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..452b9ca --- /dev/null +++ b/LICENSE @@ -0,0 +1,375 @@ +Copyright (c) 2024 Teo, Inc. (Celest) + +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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb038b7 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Turso Terraform Provider + +Terraform provider for [Turso](https://turso.tech). diff --git a/docs/data-sources/database.md b/docs/data-sources/database.md new file mode 100644 index 0000000..4c50f3d --- /dev/null +++ b/docs/data-sources/database.md @@ -0,0 +1,25 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "turso_database Data Source - turso" +subcategory: "" +description: |- + Database data source +--- + +# turso_database (Data Source) + +Database data source + + + + +## Schema + +### Required + +- `name` (String) The name of the new database. Must contain only lowercase letters, numbers, dashes. No longer than 32 characters. + +### Read-Only + +- `db_id` (String) The database universal unique identifier (UUID). +- `hostname` (String) The DNS hostname used for client libSQL and HTTP connections. diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..736c470 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,30 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "turso Provider" +subcategory: "" +description: |- + +--- + +# turso Provider + + + +## Example Usage + +```terraform +provider "turso" { + api_token = "" +} +``` + + +## Schema + +### Required + +- `organization` (String) The name of the Turso organization + +### Optional + +- `api_token` (String, Sensitive) The API token to authenticate with Turso API. If not provided, the TURSO_API_TOKEN environment variable will be used. Finally, `turso auth token` is used to get the token. diff --git a/docs/resources/database.md b/docs/resources/database.md new file mode 100644 index 0000000..d680446 --- /dev/null +++ b/docs/resources/database.md @@ -0,0 +1,80 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "turso_database Resource - turso" +subcategory: "" +description: |- + Database resource +--- + +# turso_database (Resource) + +Database resource + +## Example Usage + +```terraform +resource "turso_database" "example" { + group = "a-group" + name = "a-database" +} +``` + + +## Schema + +### Required + +- `group` (String) The name of the group where the database should be created. The group must already exist. +- `name` (String) The name of the new database. Must contain only lowercase letters, numbers, dashes. No longer than 32 characters. + +### Optional + +- `allow_attach` (Boolean) Allow attaching databases to this database. +- `block_reads` (Boolean) Block all read queries to the database. +- `block_writes` (Boolean) Block all write queries to the database. +- `is_schema` (Boolean) Mark this database as the parent schema database that updates child databases with any schema changes. +- `schema` (String) The name of the parent database to use as the schema. +- `seed` (Attributes) Seed configuration for the new database. (see [below for nested schema](#nestedatt--seed)) +- `size_limit` (String) The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb. + +### Read-Only + +- `db_id` (String) The database universal unique identifier (UUID). +- `hostname` (String) The DNS hostname used for client libSQL and HTTP connections. +- `instances` (Attributes Map) The instance configurations for the database. (see [below for nested schema](#nestedatt--instances)) +- `primary_region` (String) The location code for the primary region this database is located. +- `type` (String) The string representing the object type. Default: `logical`. +- `version` (String) The current libSQL version the database is running. + + +### Nested Schema for `seed` + +Required: + +- `type` (String) The type of seed to be used to create a new database. + +Optional: + +- `name` (String) The name of the existing database when `database` is used as a seed type. +- `timestamp` (String) A formatted ISO 8601 recovery point to create a database from. This must be within the last 24 hours, or 30 days on the scaler plan. +- `url` (String) The URL returned by [upload dump](https://docs.turso.tech/api-reference/databases/upload-dump) can be used with the `dump` seed type. + + + +### Nested Schema for `instances` + +Read-Only: + +- `hostname` (String) The DNS hostname used for client libSQL and HTTP connections (specific to this instance only). +- `name` (String) The name of the instance (location code). +- `region` (String) The location code for the region this instance is located. +- `type` (String) The type of database instance. One of: `primary` or `replica`. +- `uuid` (String) The instance universal unique identifier (UUID). + +## Import + +Import is supported using the following syntax: + +```shell +terraform import turso_database.example_database database_name +``` diff --git a/docs/resources/database_token.md b/docs/resources/database_token.md new file mode 100644 index 0000000..d3ba884 --- /dev/null +++ b/docs/resources/database_token.md @@ -0,0 +1,34 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "turso_database_token Resource - turso" +subcategory: "" +description: |- + Database token resource +--- + +# turso_database_token (Resource) + +Database token resource + + + + +## Schema + +### Required + +- `database` (String) The name of the database. + +### Optional + +- `expiration` (String) Expiration time for the token. If not provided, defaults to "never". + +A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, +such as "300s", "-1.5h" or "2h45m". + +Valid time units are "s", "m", "h"." + +### Read-Only + +- `expires_at` (String) The computed expiration time of the token. +- `token` (String, Sensitive) The database authorization token (JWT). diff --git a/docs/resources/group.md b/docs/resources/group.md new file mode 100644 index 0000000..48faf9c --- /dev/null +++ b/docs/resources/group.md @@ -0,0 +1,31 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "turso_group Resource - turso" +subcategory: "" +description: |- + Turso group resource +--- + +# turso_group (Resource) + +Turso group resource + + + + +## Schema + +### Required + +- `locations` (Set of String) The locations of the group. +- `name` (String) The name of the group. + +### Optional + +- `primary` (String) The primary location of the group. Required if multiple `locations` are specified. + +### Read-Only + +- `archived` (Boolean) Groups on the free tier go to sleep after some inactivity. +- `uuid` (String) The group universal unique identifier (UUID). +- `version` (String) The current libSQL server version the databases in that group are running. diff --git a/docs/resources/group_token.md b/docs/resources/group_token.md new file mode 100644 index 0000000..cc776a0 --- /dev/null +++ b/docs/resources/group_token.md @@ -0,0 +1,34 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "turso_group_token Resource - turso" +subcategory: "" +description: |- + Group token resource +--- + +# turso_group_token (Resource) + +Group token resource + + + + +## Schema + +### Required + +- `group` (String) The name of the group. + +### Optional + +- `expiration` (String) Expiration time for the token. If not provided, defaults to "never". + +A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, +such as "300s", "-1.5h" or "2h45m". + +Valid time units are "s", "m", "h"." + +### Read-Only + +- `expires_at` (String) The computed expiration time of the token. +- `token` (String, Sensitive) The group authorization token (JWT). diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..026c42c --- /dev/null +++ b/examples/README.md @@ -0,0 +1,9 @@ +# Examples + +This directory contains examples that are mostly used for documentation, but can also be run/tested manually via the Terraform CLI. + +The document generation tool looks for files in the following locations by default. All other *.tf files besides the ones mentioned below are ignored by the documentation tool. This is useful for creating examples that can run and/or ar testable even if some parts are not relevant for the documentation. + +* **provider/provider.tf** example file for the provider index page +* **data-sources/`full data source name`/data-source.tf** example file for the named data source page +* **resources/`full resource name`/resource.tf** example file for the named data source page diff --git a/examples/data-sources/turso_database/resource.tf b/examples/data-sources/turso_database/resource.tf new file mode 100644 index 0000000..87e40c7 --- /dev/null +++ b/examples/data-sources/turso_database/resource.tf @@ -0,0 +1,3 @@ +data "turso_database" "example" { + name = "a-database" +} diff --git a/examples/provider/provider.tf b/examples/provider/provider.tf new file mode 100644 index 0000000..1e13dee --- /dev/null +++ b/examples/provider/provider.tf @@ -0,0 +1,3 @@ +provider "turso" { + api_token = "" +} diff --git a/examples/resources/turso_database/import.sh b/examples/resources/turso_database/import.sh new file mode 100644 index 0000000..93ab67b --- /dev/null +++ b/examples/resources/turso_database/import.sh @@ -0,0 +1 @@ +terraform import turso_database.example_database database_name \ No newline at end of file diff --git a/examples/resources/turso_database/resource.tf b/examples/resources/turso_database/resource.tf new file mode 100644 index 0000000..9d80e29 --- /dev/null +++ b/examples/resources/turso_database/resource.tf @@ -0,0 +1,4 @@ +resource "turso_database" "example" { + group = "a-group" + name = "a-database" +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a03c083 --- /dev/null +++ b/go.mod @@ -0,0 +1,97 @@ +module github.com/celest-dev/terraform-provider-turso + +go 1.22.4 + +require ( + github.com/hashicorp/terraform-plugin-docs v0.19.4 + github.com/hashicorp/terraform-plugin-framework v1.10.0 + github.com/hashicorp/terraform-plugin-framework-timetypes v0.4.0 + github.com/hashicorp/terraform-plugin-framework-validators v0.13.0 + github.com/hashicorp/terraform-plugin-go v0.23.0 + github.com/hashicorp/terraform-plugin-log v0.9.0 + github.com/hashicorp/terraform-plugin-testing v1.9.0 + github.com/tursodatabase/libsql-client-go v0.0.0-20240723183952-b944339d7e70 +) + +require ( + github.com/BurntSushi/toml v1.2.1 // indirect + github.com/Kunde21/markdownfmt/v3 v3.1.0 // indirect + github.com/Masterminds/goutils v1.1.1 // indirect + github.com/Masterminds/semver/v3 v3.2.1 // indirect + github.com/Masterminds/sprig/v3 v3.2.3 // indirect + github.com/Microsoft/go-winio v0.6.2 // indirect + github.com/ProtonMail/go-crypto v1.1.0-alpha.2 // indirect + github.com/agext/levenshtein v1.2.2 // indirect + github.com/antlr4-go/antlr/v4 v4.13.1 // indirect + github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect + github.com/armon/go-radix v1.0.0 // indirect + github.com/bgentry/speakeasy v0.1.0 // indirect + github.com/bmatcuk/doublestar/v4 v4.6.1 // indirect + github.com/cloudflare/circl v1.3.7 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/fatih/color v1.17.0 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/cli v1.1.6 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-checkpoint v0.5.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect + github.com/hashicorp/go-hclog v1.6.3 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-plugin v1.6.0 // indirect + github.com/hashicorp/go-retryablehttp v0.7.7 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect + github.com/hashicorp/go-version v1.7.0 // indirect + github.com/hashicorp/hc-install v0.8.0 // indirect + github.com/hashicorp/hcl/v2 v2.21.0 // indirect + github.com/hashicorp/logutils v1.0.0 // indirect + github.com/hashicorp/terraform-exec v0.21.0 // indirect + github.com/hashicorp/terraform-json v0.22.1 // indirect + github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0 // indirect + github.com/hashicorp/terraform-registry-address v0.2.3 // indirect + github.com/hashicorp/terraform-svchost v0.1.1 // indirect + github.com/hashicorp/yamux v0.1.1 // indirect + github.com/huandu/xstrings v1.3.3 // indirect + github.com/imdario/mergo v0.3.15 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/mitchellh/copystructure v1.2.0 // indirect + github.com/mitchellh/go-testing-interface v1.14.1 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mitchellh/reflectwalk v1.0.2 // indirect + github.com/oklog/run v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/posener/complete v1.2.3 // indirect + github.com/rivo/uniseg v0.2.0 // indirect + github.com/shopspring/decimal v1.3.1 // indirect + github.com/spf13/cast v1.5.0 // indirect + github.com/stretchr/testify v1.9.0 // indirect + github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect + github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect + github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect + github.com/yuin/goldmark v1.7.1 // indirect + github.com/yuin/goldmark-meta v1.1.0 // indirect + github.com/zclconf/go-cty v1.14.4 // indirect + go.abhg.dev/goldmark/frontmatter v0.2.0 // indirect + golang.org/x/crypto v0.25.0 // indirect + golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect + golang.org/x/mod v0.19.0 // indirect + golang.org/x/net v0.27.0 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.23.0 // indirect + golang.org/x/text v0.16.0 // indirect + golang.org/x/tools v0.23.0 // indirect + google.golang.org/appengine v1.6.8 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect + google.golang.org/grpc v1.65.0 // indirect + google.golang.org/protobuf v1.34.2 // 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 + nhooyr.io/websocket v1.8.10 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..ec745fb --- /dev/null +++ b/go.sum @@ -0,0 +1,304 @@ +dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= +dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= +github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak= +github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/Kunde21/markdownfmt/v3 v3.1.0 h1:KiZu9LKs+wFFBQKhrZJrFZwtLnCCWJahL+S+E/3VnM0= +github.com/Kunde21/markdownfmt/v3 v3.1.0/go.mod h1:tPXN1RTyOzJwhfHoon9wUr4HGYmWgVxSQN6VBJDkrVc= +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= +github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= +github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= +github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= +github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/ProtonMail/go-crypto v1.1.0-alpha.2 h1:bkyFVUP+ROOARdgCiJzNQo2V2kiB97LyUpzH9P6Hrlg= +github.com/ProtonMail/go-crypto v1.1.0-alpha.2/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE= +github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE= +github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= +github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= +github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= +github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= +github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= +github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= +github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bmatcuk/doublestar/v4 v4.6.1 h1:FH9SifrbvJhnlQpztAx++wlkk70QBf0iBWDwNy7PA4I= +github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= +github.com/bufbuild/protocompile v0.4.0/go.mod h1:3v93+mbWn/v3xzN+31nwkJfrEpAUwp+BagBSZWx+TP8= +github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= +github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= +github.com/cyphar/filepath-securejoin v0.2.4/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= +github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= +github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4= +github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI= +github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= +github.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps= +github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= +github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic= +github.com/go-git/go-billy/v5 v5.5.0 h1:yEY4yhzCDuMGSv83oGxiBotRzhwhNr8VZyphhiu+mTU= +github.com/go-git/go-billy/v5 v5.5.0/go.mod h1:hmexnoNsr2SJU1Ju67OaNz5ASJY3+sHgFRpCtpDCKow= +github.com/go-git/go-git/v5 v5.12.0 h1:7Md+ndsjrzZxbddRDZjF14qK+NN56sy6wkqaVrjZtys= +github.com/go-git/go-git/v5 v5.12.0/go.mod h1:FTM9VKtnI2m65hNI/TenDDDnUf2Q9FHnXYjuz9i5OEY= +github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= +github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +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/uuid v1.1.1/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/hashicorp/cli v1.1.6 h1:CMOV+/LJfL1tXCOKrgAX0uRKnzjj/mpmqNXloRSy2K8= +github.com/hashicorp/cli v1.1.6/go.mod h1:MPon5QYlgjjo0BSoAiN0ESeT5fRzDjVRp+uioJ0piz4= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= +github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 h1:1/D3zfFHttUKaCaGKZ/dR2roBXv0vKbSCnssIldfQdI= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320/go.mod h1:EiZBMaudVLy8fmjf9Npq1dq9RalhveqZG5w/yz3mHWs= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-plugin v1.6.0 h1:wgd4KxHJTVGGqWBq4QPB1i5BZNEx9BR8+OFmHDmTk8A= +github.com/hashicorp/go-plugin v1.6.0/go.mod h1:lBS5MtSSBZk0SHc66KACcjjlU6WzEVP/8pwz68aMkCI= +github.com/hashicorp/go-retryablehttp v0.7.7 h1:C8hUCYzor8PIfXHa4UrZkU4VvK8o9ISHxT2Q8+VepXU= +github.com/hashicorp/go-retryablehttp v0.7.7/go.mod h1:pkQpWZeYWskR+D1tR2O5OcBFOxfA7DoAO6xtkuQnHTk= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY= +github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/hc-install v0.8.0 h1:LdpZeXkZYMQhoKPCecJHlKvUkQFixN/nvyR1CdfOLjI= +github.com/hashicorp/hc-install v0.8.0/go.mod h1:+MwJYjDfCruSD/udvBmRB22Nlkwwkwf5sAB6uTIhSaU= +github.com/hashicorp/hcl/v2 v2.21.0 h1:lve4q/o/2rqwYOgUg3y3V2YPyD1/zkCLGjIV74Jit14= +github.com/hashicorp/hcl/v2 v2.21.0/go.mod h1:62ZYHrXgPoX8xBnzl8QzbWq4dyDsDtfCRgIq1rbJEvA= +github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/terraform-exec v0.21.0 h1:uNkLAe95ey5Uux6KJdua6+cv8asgILFVWkd/RG0D2XQ= +github.com/hashicorp/terraform-exec v0.21.0/go.mod h1:1PPeMYou+KDUSSeRE9szMZ/oHf4fYUmB923Wzbq1ICg= +github.com/hashicorp/terraform-json v0.22.1 h1:xft84GZR0QzjPVWs4lRUwvTcPnegqlyS7orfb5Ltvec= +github.com/hashicorp/terraform-json v0.22.1/go.mod h1:JbWSQCLFSXFFhg42T7l9iJwdGXBYV8fmmD6o/ML4p3A= +github.com/hashicorp/terraform-plugin-docs v0.19.4 h1:G3Bgo7J22OMtegIgn8Cd/CaSeyEljqjH3G39w28JK4c= +github.com/hashicorp/terraform-plugin-docs v0.19.4/go.mod h1:4pLASsatTmRynVzsjEhbXZ6s7xBlUw/2Kt0zfrq8HxA= +github.com/hashicorp/terraform-plugin-framework v1.10.0 h1:xXhICE2Fns1RYZxEQebwkB2+kXouLC932Li9qelozrc= +github.com/hashicorp/terraform-plugin-framework v1.10.0/go.mod h1:qBXLDn69kM97NNVi/MQ9qgd1uWWsVftGSnygYG1tImM= +github.com/hashicorp/terraform-plugin-framework-timetypes v0.4.0 h1:XLI93Oqw2/KTzYjgCXrUnm8LBkGAiHC/mDQg5g5Vob4= +github.com/hashicorp/terraform-plugin-framework-timetypes v0.4.0/go.mod h1:mGuieb3bqKFYwEYB4lCMt302Z3siyv4PFYk/41wAUps= +github.com/hashicorp/terraform-plugin-framework-validators v0.13.0 h1:bxZfGo9DIUoLLtHMElsu+zwqI4IsMZQBRRy4iLzZJ8E= +github.com/hashicorp/terraform-plugin-framework-validators v0.13.0/go.mod h1:wGeI02gEhj9nPANU62F2jCaHjXulejm/X+af4PdZaNo= +github.com/hashicorp/terraform-plugin-go v0.23.0 h1:AALVuU1gD1kPb48aPQUjug9Ir/125t+AAurhqphJ2Co= +github.com/hashicorp/terraform-plugin-go v0.23.0/go.mod h1:1E3Cr9h2vMlahWMbsSEcNrOCxovCZhOOIXjFHbjc/lQ= +github.com/hashicorp/terraform-plugin-log v0.9.0 h1:i7hOA+vdAItN1/7UrfBqBwvYPQ9TFvymaRGZED3FCV0= +github.com/hashicorp/terraform-plugin-log v0.9.0/go.mod h1:rKL8egZQ/eXSyDqzLUuwUYLVdlYeamldAHSxjUFADow= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0 h1:kJiWGx2kiQVo97Y5IOGR4EMcZ8DtMswHhUuFibsCQQE= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.34.0/go.mod h1:sl/UoabMc37HA6ICVMmGO+/0wofkVIRxf+BMb/dnoIg= +github.com/hashicorp/terraform-plugin-testing v1.9.0 h1:xOsQRqqlHKXpFq6etTxih3ubdK3HVDtfE1IY7Rpd37o= +github.com/hashicorp/terraform-plugin-testing v1.9.0/go.mod h1:fhhVx/8+XNJZTD5o3b4stfZ6+q7z9+lIWigIYdT6/44= +github.com/hashicorp/terraform-registry-address v0.2.3 h1:2TAiKJ1A3MAkZlH1YI/aTVcLZRu7JseiXNRHbOAyoTI= +github.com/hashicorp/terraform-registry-address v0.2.3/go.mod h1:lFHA76T8jfQteVfT7caREqguFrW3c4MFSPhZB7HHgUM= +github.com/hashicorp/terraform-svchost v0.1.1 h1:EZZimZ1GxdqFRinZ1tpJwVxxt49xc/S52uzrw4x0jKQ= +github.com/hashicorp/terraform-svchost v0.1.1/go.mod h1:mNsjQfZyf/Jhz35v6/0LWcv26+X7JPS+buii2c9/ctc= +github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE= +github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ= +github.com/huandu/xstrings v1.3.3 h1:/Gcsuc1x8JVbJ9/rlye4xZnVAbEkGauT8lbebqcQws4= +github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM= +github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= +github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= +github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= +github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= +github.com/jhump/protoreflect v1.15.1/go.mod h1:jD/2GMKKE6OqX8qTjhADU1e6DShO+gavG9e0Q693nKo= +github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4= +github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.12/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-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.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.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= +github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= +github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= +github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= +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/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= +github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= +github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= +github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo= +github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8= +github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= +github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/skeema/knownhosts v1.2.2 h1:Iug2P4fLmDw9f41PB6thxUkNUkJzB5i+1/exaj40L3A= +github.com/skeema/knownhosts v1.2.2/go.mod h1:xYbVRSPxqBZFrdmDyMmsOs+uX1UZC3nTN3ThzgDxUwo= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= +github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/tursodatabase/libsql-client-go v0.0.0-20240723183952-b944339d7e70 h1:G0aOKAhfrB73zLWzSBMHtYH97YTg4A+sXrTMx3UxAOI= +github.com/tursodatabase/libsql-client-go v0.0.0-20240723183952-b944339d7e70/go.mod h1:3Y9LlWC05q63NdmViO+2qV22LUjpfYLZWEYfE7ndpmU= +github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI= +github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= +github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= +github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= +github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= +github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= +github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.7.1 h1:3bajkSilaCbjdKVsKdZjZCLBNPL9pYzrCakKaf4U49U= +github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +github.com/yuin/goldmark-meta v1.1.0 h1:pWw+JLHGZe8Rk0EGsMVssiNb/AaPMHfSRszZeUeiOUc= +github.com/yuin/goldmark-meta v1.1.0/go.mod h1:U4spWENafuA7Zyg+Lj5RqK/MF+ovMYtBvXi1lBb2VP0= +github.com/zclconf/go-cty v1.14.4 h1:uXXczd9QDGsgu0i/QFR/hzI5NYCHLf6NQw/atrbnhq8= +github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= +github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo= +github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM= +go.abhg.dev/goldmark/frontmatter v0.2.0 h1:P8kPG0YkL12+aYk2yU3xHv4tcXzeVnN+gU0tJ5JnxRw= +go.abhg.dev/goldmark/frontmatter v0.2.0/go.mod h1:XqrEkZuM57djk7zrlRUB02x8I5J0px76YjkOzhB4YlU= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= +golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30= +golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M= +golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= +golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= +golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= +golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= +golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/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-20220503163025-988cb79eb6c6/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.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= +golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +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.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= +golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 h1:e7S5W7MGGLaSu8j3YjdezkZ+m1/Nm0uRVRMEMGk26Xs= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= +google.golang.org/grpc v1.65.0 h1:bs/cUb4lp1G5iImFFd3u5ixQzweKizoZJAwBNLR42lc= +google.golang.org/grpc v1.65.0/go.mod h1:WgYC2ypjlB0EiQi6wdKixMqukr6lBc0Vo+oOgjrM5ZQ= +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.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= +gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +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.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nhooyr.io/websocket v1.8.10 h1:mv4p+MnGrLDcPlBoWsvPP7XCzTYMXP9F9eIGoKbgx7Q= +nhooyr.io/websocket v1.8.10/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= diff --git a/internal/provider/data_database.go b/internal/provider/data_database.go new file mode 100644 index 0000000..fbb3963 --- /dev/null +++ b/internal/provider/data_database.go @@ -0,0 +1,99 @@ +package provider + +import ( + "context" + "fmt" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +var _ datasource.DataSource = &DatabaseDataSource{} + +func NewDatabaseDataSource() datasource.DataSource { + return &DatabaseDataSource{} +} + +// DatabaseDataSource defines the data source implementation. +type DatabaseDataSource struct { + client *tursoadmin.Client +} + +// DatabaseDataSourceModel describes the data source data model. +type DatabaseDataSourceModel struct { + Name types.String `tfsdk:"name"` + + // Computed + DbId types.String `tfsdk:"db_id"` + Hostname types.String `tfsdk:"hostname"` +} + +func (d *DatabaseDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_database" +} + +func (d *DatabaseDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Database data source", + + Attributes: map[string]schema.Attribute{ + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the new database. Must contain only lowercase letters, numbers, dashes. No longer than 32 characters.", + Required: true, + }, + "db_id": schema.StringAttribute{ + MarkdownDescription: "The database universal unique identifier (UUID).", + Computed: true, + }, + "hostname": schema.StringAttribute{ + MarkdownDescription: "The DNS hostname used for client libSQL and HTTP connections.", + Computed: true, + }, + }, + } +} + +func (d *DatabaseDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*tursoadmin.Client) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Data Source Configure Type", + fmt.Sprintf("Expected *http.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + d.client = client +} + +func (d *DatabaseDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var data DatabaseDataSourceModel + + // Read Terraform configuration data into the model + resp.Diagnostics.Append(req.Config.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + res, err := d.client.GetDatabase(ctx, data.Name.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read database, got error: %s", err.Error())) + return + } + + data.DbId = types.StringValue(res.ID) + data.Hostname = types.StringValue(res.Hostname) + + // Save data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go new file mode 100644 index 0000000..147e91d --- /dev/null +++ b/internal/provider/provider.go @@ -0,0 +1,120 @@ +package provider + +import ( + "context" + "os" + "os/exec" + "strings" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/function" + "github.com/hashicorp/terraform-plugin-framework/provider" + "github.com/hashicorp/terraform-plugin-framework/provider/schema" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// Ensure TursoProvider satisfies various provider interfaces. +var _ provider.Provider = &TursoProvider{} +var _ provider.ProviderWithFunctions = &TursoProvider{} + +// TursoProvider defines the provider implementation. +type TursoProvider struct { + // version is set to the provider version on release, "dev" when the + // provider is built and ran locally, and "test" when running acceptance + // testing. + version string +} + +// TursoProviderModel describes the provider data model. +type TursoProviderModel struct { + Organization types.String `tfsdk:"organization"` + ApiToken types.String `tfsdk:"api_token"` +} + +func (p *TursoProvider) Metadata(ctx context.Context, req provider.MetadataRequest, resp *provider.MetadataResponse) { + resp.TypeName = "turso" + resp.Version = p.version +} + +func (p *TursoProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) { + resp.Schema = schema.Schema{ + Attributes: map[string]schema.Attribute{ + "organization": schema.StringAttribute{ + MarkdownDescription: "The name of the Turso organization", + Required: true, + }, + "api_token": schema.StringAttribute{ + MarkdownDescription: "The API token to authenticate with Turso API. If not provided, the TURSO_API_TOKEN environment variable will be used. Finally, `turso auth token` is used to get the token.", + Optional: true, + Sensitive: true, + }, + }, + } +} + +func (p *TursoProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { + var config TursoProviderModel + + resp.Diagnostics.Append(req.Config.Get(ctx, &config)...) + + if resp.Diagnostics.HasError() { + return + } + + var apiToken string + if !config.ApiToken.IsNull() && !config.ApiToken.IsUnknown() { + apiToken = config.ApiToken.ValueString() + } else if token, ok := os.LookupEnv("TURSO_API_TOKEN"); ok { + apiToken = token + } else { + out, err := exec.Command("turso", "auth", "token").Output() + if err == nil { + apiToken = strings.TrimSpace(string(out)) + } + } + + if apiToken == "" { + resp.Diagnostics.AddError("api_token is required", "Must be provided in the configuration, the TURSO_API_TOKEN environment variable, or by logging into the Turso CLI.") + return + } + + client, err := tursoadmin.NewClient(tursoadmin.Config{ + OrgName: config.Organization.ValueString(), + APIToken: apiToken, + }) + if err != nil { + resp.Diagnostics.AddError(err.Error(), err.Error()) + return + } + resp.DataSourceData = client + resp.ResourceData = client +} + +func (p *TursoProvider) Resources(ctx context.Context) []func() resource.Resource { + return []func() resource.Resource{ + NewDatabaseResource, + NewDatabaseTokenResource, + NewGroupResource, + NewGroupTokenResource, + } +} + +func (p *TursoProvider) DataSources(ctx context.Context) []func() datasource.DataSource { + return []func() datasource.DataSource{ + NewDatabaseDataSource, + } +} + +func (p *TursoProvider) Functions(ctx context.Context) []func() function.Function { + return []func() function.Function{} +} + +func New(version string) func() provider.Provider { + return func() provider.Provider { + return &TursoProvider{ + version: version, + } + } +} diff --git a/internal/provider/provider_test.go b/internal/provider/provider_test.go new file mode 100644 index 0000000..65b602d --- /dev/null +++ b/internal/provider/provider_test.go @@ -0,0 +1,36 @@ +package provider + +import ( + "math/rand/v2" + "strconv" + "testing" + + "github.com/hashicorp/terraform-plugin-framework/providerserver" + "github.com/hashicorp/terraform-plugin-go/tfprotov6" +) + +// testAccProtoV6ProviderFactories are used to instantiate a provider during +// acceptance testing. The factory function will be invoked for every Terraform +// CLI command executed to create a provider server to which the CLI can +// reattach. +var testAccProtoV6ProviderFactories = map[string]func() (tfprotov6.ProviderServer, error){ + "turso": providerserver.NewProtocol6WithError(New("test")()), +} + +func testAccPreCheck(t *testing.T) { + // You can add code here to run prior to any test case execution, for example assertions + // about the appropriate environment variables being set are common to see in a pre-check + // function. +} + +func testAccCreateConfig(config string) string { + return ` +provider "turso" { + organization = "celest-dev" +} + ` + config +} + +func randomName() string { + return "test-" + strconv.Itoa(rand.IntN(10000000)) +} diff --git a/internal/provider/resource_database.go b/internal/provider/resource_database.go new file mode 100644 index 0000000..236fed1 --- /dev/null +++ b/internal/provider/resource_database.go @@ -0,0 +1,476 @@ +package provider + +import ( + "context" + "fmt" + "strings" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin" + "github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/mapplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/objectplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + "github.com/hashicorp/terraform-plugin-log/tflog" +) + +// Ensure provider defined types fully satisfy framework interfaces. +var _ resource.Resource = &DatabaseResource{} +var _ resource.ResourceWithImportState = &DatabaseResource{} + +func NewDatabaseResource() resource.Resource { + return &DatabaseResource{} +} + +type DatabaseResource struct { + client *tursoadmin.Client +} + +type DatabaseResourceModel struct { + Name types.String `tfsdk:"name"` + Group types.String `tfsdk:"group"` + Seed types.Object `tfsdk:"seed"` + SizeLimit types.String `tfsdk:"size_limit"` + IsSchema types.Bool `tfsdk:"is_schema"` + Schema types.String `tfsdk:"schema"` + AllowAttach types.Bool `tfsdk:"allow_attach"` + BlockReads types.Bool `tfsdk:"block_reads"` + BlockWrites types.Bool `tfsdk:"block_writes"` + + // Computed + DbId types.String `tfsdk:"db_id"` + Hostname types.String `tfsdk:"hostname"` + Type types.String `tfsdk:"type"` + Version types.String `tfsdk:"version"` + PrimaryRegion types.String `tfsdk:"primary_region"` + Instances types.Map `tfsdk:"instances"` +} + +type DatabaseSeedModel struct { + Type types.String `tfsdk:"type"` + Name types.String `tfsdk:"name"` + URL types.String `tfsdk:"url"` + Timestamp timetypes.RFC3339 `tfsdk:"timestamp"` +} + +func (DatabaseSeedModel) AttributeTypes() map[string]attr.Type { + return map[string]attr.Type{ + "type": types.StringType, + "name": types.StringType, + "url": types.StringType, + "timestamp": timetypes.RFC3339Type{}, + } +} + +type DatabaseInstanceModel struct { + UUID types.String `tfsdk:"uuid"` + Name types.String `tfsdk:"name"` + Type types.String `tfsdk:"type"` + Region types.String `tfsdk:"region"` + Hostname types.String `tfsdk:"hostname"` +} + +func (DatabaseInstanceModel) AttributeTypes() map[string]attr.Type { + return map[string]attr.Type{ + "uuid": types.StringType, + "name": types.StringType, + "type": types.StringType, + "region": types.StringType, + "hostname": types.StringType, + } +} + +func (r *DatabaseResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_database" +} + +func (r *DatabaseResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Database resource", + Attributes: map[string]schema.Attribute{ + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the new database. Must contain only lowercase letters, numbers, dashes. No longer than 32 characters.", + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "group": schema.StringAttribute{ + MarkdownDescription: "The name of the group where the database should be created. The group must already exist.", + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "seed": schema.SingleNestedAttribute{ + MarkdownDescription: "Seed configuration for the new database.", + Optional: true, + Attributes: map[string]schema.Attribute{ + "type": schema.StringAttribute{ + MarkdownDescription: "The type of seed to be used to create a new database.", + Required: true, + Validators: []validator.String{ + stringvalidator.OneOf(string(tursoadmin.DatabaseSeedDatabase), string(tursoadmin.DatabaseSeedDump)), + }, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the existing database when `database` is used as a seed type.", + Optional: true, + Validators: []validator.String{ + stringvalidator.ConflictsWith(path.MatchRelative().AtParent().AtName("url")), + stringvalidator.AtLeastOneOf(path.MatchRelative(), path.MatchRelative().AtParent().AtName("url")), + }, + }, + "url": schema.StringAttribute{ + MarkdownDescription: "The URL returned by [upload dump](https://docs.turso.tech/api-reference/databases/upload-dump) can be used with the `dump` seed type.", + Optional: true, + Validators: []validator.String{ + stringvalidator.ConflictsWith(path.MatchRelative().AtParent().AtName("name")), + stringvalidator.AtLeastOneOf(path.MatchRelative().AtParent().AtName("name"), path.MatchRelative()), + }, + }, + "timestamp": schema.StringAttribute{ + MarkdownDescription: "A formatted ISO 8601 recovery point to create a database from. This must be within the last 24 hours, or 30 days on the scaler plan.", + Optional: true, + CustomType: timetypes.RFC3339Type{}, + }, + }, + PlanModifiers: []planmodifier.Object{ + objectplanmodifier.RequiresReplace(), + }, + }, + "size_limit": schema.StringAttribute{ + MarkdownDescription: "The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb.", + Optional: true, + }, + "is_schema": schema.BoolAttribute{ + MarkdownDescription: "Mark this database as the parent schema database that updates child databases with any schema changes.", + Optional: true, + }, + "schema": schema.StringAttribute{ + MarkdownDescription: "The name of the parent database to use as the schema.", + Optional: true, + }, + "allow_attach": schema.BoolAttribute{ + MarkdownDescription: "Allow attaching databases to this database.", + Optional: true, + Computed: true, + Default: booldefault.StaticBool(false), + }, + "block_reads": schema.BoolAttribute{ + MarkdownDescription: "Block all read queries to the database.", + Optional: true, + Computed: true, + Default: booldefault.StaticBool(false), + }, + "block_writes": schema.BoolAttribute{ + MarkdownDescription: "Block all write queries to the database.", + Optional: true, + Computed: true, + Default: booldefault.StaticBool(false), + }, + "db_id": schema.StringAttribute{ + MarkdownDescription: "The database universal unique identifier (UUID).", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "hostname": schema.StringAttribute{ + MarkdownDescription: "The DNS hostname used for client libSQL and HTTP connections.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "type": schema.StringAttribute{ + MarkdownDescription: "The string representing the object type. Default: `logical`.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "version": schema.StringAttribute{ + MarkdownDescription: "The current libSQL version the database is running.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "primary_region": schema.StringAttribute{ + MarkdownDescription: "The location code for the primary region this database is located.", + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "instances": schema.MapNestedAttribute{ + MarkdownDescription: "The instance configurations for the database.", + Computed: true, + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + "uuid": schema.StringAttribute{ + MarkdownDescription: "The instance universal unique identifier (UUID).", + Computed: true, + }, + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the instance (location code).", + Computed: true, + }, + "type": schema.StringAttribute{ + MarkdownDescription: "The type of database instance. One of: `primary` or `replica`.", + Computed: true, + }, + "region": schema.StringAttribute{ + MarkdownDescription: "The location code for the region this instance is located.", + Computed: true, + }, + "hostname": schema.StringAttribute{ + MarkdownDescription: "The DNS hostname used for client libSQL and HTTP connections (specific to this instance only).", + Computed: true, + }, + }, + }, + PlanModifiers: []planmodifier.Map{ + mapplanmodifier.UseStateForUnknown(), + }, + }, + }, + } +} + +func (r *DatabaseResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*tursoadmin.Client) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *tursoadmin.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + return + } + + r.client = client +} + +func (r *DatabaseResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan DatabaseResourceModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Trace(ctx, "create database plan", map[string]interface{}{ + "plan": plan, + }) + fmt.Printf("create database plan: %+v\n", plan) + + var dbSeed *tursoadmin.DatabaseSeed + if !plan.Seed.IsNull() && !plan.Seed.IsUnknown() { + var seedModel DatabaseSeedModel + resp.Diagnostics.Append(plan.Seed.As(ctx, &seedModel, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + if resp.Diagnostics.HasError() { + return + } + + dbSeed = &tursoadmin.DatabaseSeed{ + Type: tursoadmin.DatabaseSeedType(seedModel.Type.ValueString()), + Name: seedModel.Name.ValueString(), + URL: seedModel.URL.ValueString(), + } + + // timestamp := seedModel.Timestamp + // if !timestamp.IsNull() && !timestamp.IsUnknown() { + // ts, diags := timestamp.ValueRFC3339Time() + // resp.Diagnostics.Append(diags...) + // if resp.Diagnostics.HasError() { + // return + // } + // dbSeed.Timestamp = ts + // } + } + + createReq := tursoadmin.CreateDatabaseRequest{ + Name: plan.Name.ValueString(), + Group: plan.Group.ValueString(), + Seed: dbSeed, + SizeLimit: plan.SizeLimit.ValueString(), + IsSchema: plan.IsSchema.ValueBool(), + SchemaDatabase: plan.Schema.ValueString(), + } + tflog.Trace(ctx, "creating database", map[string]interface{}{ + "request": createReq, + }) + fmt.Printf("creating database: %+v\n", createReq) + db, err := r.client.CreateDatabase(ctx, createReq) + if err != nil { + resp.Diagnostics.AddError("error creating database", err.Error()) + return + } + resp.Diagnostics.Append(r.readDatabase(ctx, db.Name, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + tflog.Trace(ctx, "created database resource") + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) +} + +func (r *DatabaseResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data DatabaseResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(r.readDatabase(ctx, data.Name.ValueString(), &data)...) + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *DatabaseResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data DatabaseResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + fmt.Printf("update database: %+v\n", data) + config, err := r.client.UpdateDatabaseConfiguration(ctx, data.Name.ValueString(), tursoadmin.DatabaseConfig{ + SizeLimit: data.SizeLimit.ValueStringPointer(), + AllowAttach: data.AllowAttach.ValueBoolPointer(), + BlockReads: data.BlockReads.ValueBoolPointer(), + BlockWrites: data.BlockWrites.ValueBoolPointer(), + }) + if err != nil { + resp.Diagnostics.AddError("client error", err.Error()) + return + } + + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("size_limit"), config.SizeLimit)...) + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("allow_attach"), config.AllowAttach)...) + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("block_reads"), config.BlockReads)...) + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("block_writes"), config.BlockWrites)...) +} + +func (r *DatabaseResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data DatabaseResourceModel + + // Read Terraform prior state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + fmt.Printf("delete database: %+v\n", data) + err := r.client.DeleteDatabase(ctx, data.Name.ValueString()) + if err != nil { + resp.Diagnostics.AddError("client error", err.Error()) + return + } +} + +func (r *DatabaseResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + tflog.Trace(ctx, fmt.Sprintf("importing database: %s", req.ID)) + + idParts := strings.Split(req.ID, "/") + if len(idParts) != 2 { + resp.Diagnostics.AddError("invalid import ID", fmt.Sprintf("expected format: group_name/database_name, got: %s", req.ID)) + return + } + + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("group"), idParts[0])...) + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), idParts[1])...) +} + +func (r *DatabaseResource) readDatabase(ctx context.Context, name string, data *DatabaseResourceModel) diag.Diagnostics { + db, err := r.client.GetDatabase(ctx, name) + if err != nil { + return diag.Diagnostics{ + diag.NewErrorDiagnostic("client error", err.Error()), + } + } + fmt.Printf("read database: %+v\n", db) + + data.DbId = types.StringValue(db.ID) + data.Hostname = types.StringValue(db.Hostname) + if data.Seed.IsUnknown() { + data.Seed = types.ObjectNull(DatabaseSeedModel{}.AttributeTypes()) + } + if data.SizeLimit.IsUnknown() { + data.SizeLimit = types.StringNull() + } + if !data.IsSchema.IsNull() && !data.IsSchema.IsUnknown() { + data.IsSchema = types.BoolValue(db.IsSchema) + } else { + data.IsSchema = types.BoolNull() + } + if data.Schema.IsUnknown() { + data.Schema = types.StringNull() + } + data.PrimaryRegion = types.StringValue(db.PrimaryRegion) + data.Type = types.StringValue(db.Type) + data.Version = types.StringValue(db.Version) + data.AllowAttach = types.BoolValue(db.AllowAttach) + data.BlockReads = types.BoolValue(db.BlockReads) + data.BlockWrites = types.BoolValue(db.BlockWrites) + + instances, err := r.client.ListDatabaseInstances(ctx, db.Name) + if err != nil { + return diag.Diagnostics{ + diag.NewErrorDiagnostic("client error", err.Error()), + } + } + instanceElements := make(map[string]attr.Value) + for _, instance := range instances { + model := DatabaseInstanceModel{ + UUID: types.StringValue(instance.UUID), + Name: types.StringValue(instance.Name), + Type: types.StringValue(string(instance.Type)), + Region: types.StringValue(instance.Region), + Hostname: types.StringValue(instance.Hostname), + } + element, diags := types.ObjectValueFrom(ctx, model.AttributeTypes(), model) + if diags.HasError() { + return diags + } + instanceElements[instance.Region] = element + } + instancesValue, diags := types.MapValue( + types.ObjectType{AttrTypes: DatabaseInstanceModel{}.AttributeTypes()}, + instanceElements, + ) + if diags.HasError() { + return diags + } + data.Instances = instancesValue + + return nil +} diff --git a/internal/provider/resource_database_test.go b/internal/provider/resource_database_test.go new file mode 100644 index 0000000..e2f473b --- /dev/null +++ b/internal/provider/resource_database_test.go @@ -0,0 +1,64 @@ +package provider + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/knownvalue" + "github.com/hashicorp/terraform-plugin-testing/statecheck" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" +) + +func TestAccResourceDatabase(t *testing.T) { + name := randomName() + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + // Create and Read test + { + Config: testAccCreateConfig(` + resource "turso_database" "test" { + group = "test" + name = "` + name + `" + }`), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("instances"), knownvalue.MapSizeExact(1)), + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("allow_attach"), knownvalue.Bool(false)), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("turso_database.test", "name", name), + resource.TestCheckResourceAttr("turso_database.test", "group", "test"), + ), + }, + + // ImportState test + { + ResourceName: "turso_database.test", + ImportStateIdPrefix: "test/", // group name + ImportStateId: name, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIdentifierAttribute: "name", + }, + + // Update and Read test + { + Config: testAccCreateConfig(` + resource "turso_database" "test" { + group = "test" + name = "` + name + `" + allow_attach = true + }`), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("instances"), knownvalue.MapSizeExact(1)), + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("allow_attach"), knownvalue.Bool(true)), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("turso_database.test", "name", name), + resource.TestCheckResourceAttr("turso_database.test", "group", "test"), + ), + }, + }, + }) +} diff --git a/internal/provider/resource_database_token.go b/internal/provider/resource_database_token.go new file mode 100644 index 0000000..187e2f3 --- /dev/null +++ b/internal/provider/resource_database_token.go @@ -0,0 +1,171 @@ +package provider + +import ( + "context" + "fmt" + "time" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin" + "github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" +) + +var _ resource.Resource = &DatabaseTokenResource{} +var _ resource.ResourceWithConfigure = &DatabaseTokenResource{} + +func NewDatabaseTokenResource() resource.Resource { + return &DatabaseTokenResource{} +} + +type DatabaseTokenResource struct { + client *tursoadmin.Client +} + +type DatabaseTokenResourceModel struct { + DatabaseName types.String `tfsdk:"database"` + Expiration timetypes.GoDuration `tfsdk:"expiration"` + + // Computed + Token types.String `tfsdk:"token"` + ExpiresAt timetypes.RFC3339 `tfsdk:"expires_at"` +} + +func (r *DatabaseTokenResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_database_token" +} + +func (r *DatabaseTokenResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Database token resource", + Attributes: map[string]schema.Attribute{ + "database": schema.StringAttribute{ + MarkdownDescription: "The name of the database.", + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "expiration": schema.StringAttribute{ + MarkdownDescription: ` +Expiration time for the token. If not provided, defaults to "never". + +A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, +such as "300s", "-1.5h" or "2h45m". + +Valid time units are "s", "m", "h"."`, + Optional: true, + CustomType: timetypes.GoDurationType{}, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "token": schema.StringAttribute{ + MarkdownDescription: "The database authorization token (JWT).", + Computed: true, + Sensitive: true, + }, + "expires_at": schema.StringAttribute{ + MarkdownDescription: "The computed expiration time of the token.", + Computed: true, + CustomType: timetypes.RFC3339Type{}, + }, + }, + } +} + +func (r *DatabaseTokenResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*tursoadmin.Client) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *client.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + return + } + + r.client = client +} + +func (r *DatabaseTokenResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data DatabaseTokenResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *DatabaseTokenResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data DatabaseTokenResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + now := time.Now().UTC() + var expiration time.Duration + if !data.Expiration.IsUnknown() && !data.Expiration.IsNull() { + exp, diags := data.Expiration.ValueGoDuration() + resp.Diagnostics.Append(diags...) + if diags.HasError() { + return + } + expiration = exp + } else { + data.Expiration = timetypes.NewGoDurationNull() + } + + res, err := r.client.CreateDatabaseToken(ctx, data.DatabaseName.ValueString(), expiration) + if err != nil { + resp.Diagnostics.AddError("client error", err.Error()) + return + } + data.Token = types.StringValue(res) + if expiration != time.Duration(0) { + data.ExpiresAt = timetypes.NewRFC3339TimeValue(now.Add(expiration)) + } else { + data.ExpiresAt = timetypes.NewRFC3339Null() + } + + tflog.Trace(ctx, "created database token") + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *DatabaseTokenResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + panic("should have forced replacement") +} + +func (r *DatabaseTokenResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data DatabaseTokenResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + // Technically we can only invalidate ALL database tokens, but because we expect only one token to exist per database at a time + // with no expiration, this is acceptable. + fmt.Printf("Invalidating all database tokens for %s\n", data.DatabaseName.ValueString()) + err := r.client.InvalidateDatabaseTokens(ctx, data.DatabaseName.ValueString()) + if err != nil { + // TODO: Invalidating the db token is not allowed when the DB is in a group ?? + resp.Diagnostics.AddWarning("client error", err.Error()) + return + } + + tflog.Trace(ctx, "deleted group token") +} diff --git a/internal/provider/resource_database_token_test.go b/internal/provider/resource_database_token_test.go new file mode 100644 index 0000000..e850cf2 --- /dev/null +++ b/internal/provider/resource_database_token_test.go @@ -0,0 +1,69 @@ +package provider + +import ( + "database/sql" + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/knownvalue" + "github.com/hashicorp/terraform-plugin-testing/statecheck" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" + "github.com/tursodatabase/libsql-client-go/libsql" +) + +func TestAccResourceDatabaseToken_E2E(t *testing.T) { + name := randomName() + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccCreateConfig(` + resource "turso_database" "test" { + group = "test" + name = "` + name + `" + } + resource "turso_database_token" "test" { + database = turso_database.test.name + }`), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("instances"), knownvalue.MapSizeExact(1)), + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("hostname"), knownvalue.NotNull()), + + statecheck.ExpectSensitiveValue("turso_database_token.test", tfjsonpath.New("token")), + statecheck.ExpectKnownValue("turso_database_token.test", tfjsonpath.New("token"), knownvalue.NotNull()), + statecheck.ExpectKnownValue("turso_database_token.test", tfjsonpath.New("expires_at"), knownvalue.Null()), // no expiration + }, + Check: func(s *terraform.State) error { + dbHostname, ok := s.RootModule().Resources["turso_database.test"].Primary.Attributes["hostname"] + if !ok { + return fmt.Errorf("missing hostname") + } + token, ok := s.RootModule().Resources["turso_database_token.test"].Primary.Attributes["token"] + if !ok { + return fmt.Errorf("missing token") + } + + connector, err := libsql.NewConnector("libsql://"+dbHostname, libsql.WithAuthToken(token)) + if err != nil { + return fmt.Errorf("error creating database connector: %v", err) + } + db := sql.OpenDB(connector) + defer db.Close() + + // Test connection + if err := db.Ping(); err != nil { + return fmt.Errorf("error pinging database: %v", err) + } + if _, err := db.Query("select 1"); err != nil { + return fmt.Errorf("error querying database: %v", err) + } + + return nil + }, + }, + }, + }) +} diff --git a/internal/provider/resource_group.go b/internal/provider/resource_group.go new file mode 100644 index 0000000..b573664 --- /dev/null +++ b/internal/provider/resource_group.go @@ -0,0 +1,309 @@ +package provider + +import ( + "context" + "fmt" + "slices" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + "github.com/hashicorp/terraform-plugin-log/tflog" +) + +// Ensure provider defined types fully satisfy framework interfaces. +var _ resource.Resource = &GroupResource{} +var _ resource.ResourceWithImportState = &GroupResource{} +var _ resource.ResourceWithConfigValidators = &GroupResource{} + +func NewGroupResource() resource.Resource { + return &GroupResource{} +} + +type GroupResource struct { + client *tursoadmin.Client +} + +type GroupResourceModel struct { + // The group name, unique across your organization. + Name types.String `tfsdk:"name"` + + // The primary location key. + Primary types.String `tfsdk:"primary"` + + // The locations where the databases in the group are running. + Locations []types.String `tfsdk:"locations"` + + // Computed + + // The current libSQL server version the databases in that group are running. + Version types.String `tfsdk:"version"` + + // The group universal unique identifier (UUID). + UUID types.String `tfsdk:"uuid"` + + // Groups on the free tier go to sleep after some inactivity. + Archived types.Bool `tfsdk:"archived"` +} + +func (r *GroupResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_group" +} + +func (r *GroupResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Turso group resource", + + Attributes: map[string]schema.Attribute{ + "name": schema.StringAttribute{ + MarkdownDescription: "The name of the group.", + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "primary": schema.StringAttribute{ + MarkdownDescription: "The primary location of the group. Required if multiple `locations` are specified.", + Optional: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "locations": schema.SetAttribute{ + MarkdownDescription: "The locations of the group.", + Required: true, + ElementType: basetypes.StringType{}, + }, + "version": schema.StringAttribute{ + MarkdownDescription: "The current libSQL server version the databases in that group are running.", + Computed: true, + }, + "uuid": schema.StringAttribute{ + MarkdownDescription: "The group universal unique identifier (UUID).", + Computed: true, + }, + "archived": schema.BoolAttribute{ + MarkdownDescription: "Groups on the free tier go to sleep after some inactivity.", + Computed: true, + }, + }, + } +} + +type groupConfigValidator struct{} + +var _ resource.ConfigValidator = &groupConfigValidator{} + +// Description implements resource.ConfigValidator. +func (p *groupConfigValidator) Description(context.Context) string { + return "Validate the group configuration." +} + +// MarkdownDescription implements resource.ConfigValidator. +func (p *groupConfigValidator) MarkdownDescription(context.Context) string { + return "Validate the group configuration." +} + +// ValidateResource implements resource.ConfigValidator. +func (p *groupConfigValidator) ValidateResource(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) { + var locations types.Set + resp.Diagnostics.Append(req.Config.GetAttribute(ctx, path.Root("locations"), &locations)...) + + var primary types.String + resp.Diagnostics.Append(req.Config.GetAttribute(ctx, path.Root("primary"), &primary)...) + + if resp.Diagnostics.HasError() { + return + } + + if len(locations.Elements()) == 0 { + resp.Diagnostics.AddAttributeError(path.Root("locations"), "Invalid locations", "At least one location must be specified.") + return + } + + if len(locations.Elements()) == 1 { + // OK, will use the only location as primary + return + } + + if primary.IsNull() { + resp.Diagnostics.AddAttributeError(path.Root("primary"), "Invalid primary location", "Primary location must be specified if multiple locations are specified.") + return + } +} + +func (r *GroupResource) ConfigValidators(ctx context.Context) []resource.ConfigValidator { + return []resource.ConfigValidator{ + &groupConfigValidator{}, + } +} + +func (r *GroupResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*tursoadmin.Client) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *client.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + return + } + + r.client = client +} + +func (r *GroupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data GroupResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + locations := make([]string, len(data.Locations)) + for i, location := range data.Locations { + locations[i] = location.ValueString() + } + + var primaryLocation string + if !data.Primary.IsNull() && !data.Primary.IsUnknown() { + primaryLocation = data.Primary.ValueString() + } else { + + primaryLocation = locations[0] + } + + group, err := r.client.CreateGroup(ctx, tursoadmin.CreateGroupRequest{ + Name: data.Name.ValueString(), + Location: primaryLocation, + Extensions: tursoadmin.ExtensionsAll, + }) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create group, got error: %s", err.Error())) + return + } + + for _, location := range locations { + if location == primaryLocation { + continue + } + group, err = r.client.AddGroupLocation(ctx, data.Name.ValueString(), location) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to add location to group, got error: %s", err.Error())) + return + } + } + + data.Name = types.StringValue(group.Name) + data.Primary = types.StringValue(group.PrimaryLocation) + data.Locations = make([]basetypes.StringValue, len(group.Locations)) + for i, location := range group.Locations { + data.Locations[i] = types.StringValue(location) + } + data.Version = types.StringValue(group.Version) + data.UUID = types.StringValue(group.UUID) + data.Archived = types.BoolValue(group.Archived) + + tflog.Trace(ctx, "created group resource") + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *GroupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data GroupResourceModel + + // Read Terraform prior state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + group, err := r.client.GetGroup(ctx, data.Name.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read group, got error: %s", err.Error())) + return + } + + data.Name = types.StringValue(group.Name) + data.Primary = types.StringValue(group.PrimaryLocation) + data.Locations = make([]basetypes.StringValue, len(group.Locations)) + for i, location := range group.Locations { + data.Locations[i] = types.StringValue(location) + } + data.Version = types.StringValue(group.Version) + data.UUID = types.StringValue(group.UUID) + data.Archived = types.BoolValue(group.Archived) + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *GroupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data GroupResourceModel + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + group, err := r.client.GetGroup(ctx, data.Name.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read group, got error: %s", err.Error())) + return + } + + currentLocations := group.Locations + requestedLocations := make([]string, len(data.Locations)) + for i, location := range data.Locations { + requestedLocations[i] = location.ValueString() + } + + missingLocations := make([]string, 0, len(requestedLocations)) + for _, location := range requestedLocations { + if !slices.Contains(currentLocations, location) { + missingLocations = append(missingLocations, location) + } + } + + for _, location := range missingLocations { + group, err = r.client.AddGroupLocation(ctx, data.Name.ValueString(), location) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to add location to group, got error: %s", err.Error())) + return + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *GroupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data GroupResourceModel + + // Read Terraform prior state data into the model + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + err := r.client.DeleteGroup(ctx, data.Name.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete group, got error: %s", err.Error())) + return + } +} + +func (r *GroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), req.ID)...) +} diff --git a/internal/provider/resource_group_token.go b/internal/provider/resource_group_token.go new file mode 100644 index 0000000..c6d2ab3 --- /dev/null +++ b/internal/provider/resource_group_token.go @@ -0,0 +1,169 @@ +package provider + +import ( + "context" + "fmt" + "time" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin" + "github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" +) + +var _ resource.Resource = &GroupTokenResource{} +var _ resource.ResourceWithConfigure = &GroupTokenResource{} + +func NewGroupTokenResource() resource.Resource { + return &GroupTokenResource{} +} + +type GroupTokenResource struct { + client *tursoadmin.Client +} + +type GroupTokenResourceModel struct { + GroupName types.String `tfsdk:"group"` + Expiration timetypes.GoDuration `tfsdk:"expiration"` + + // Computed + Token types.String `tfsdk:"token"` + ExpiresAt timetypes.RFC3339 `tfsdk:"expires_at"` +} + +func (r *GroupTokenResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_group_token" +} + +func (r *GroupTokenResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "Group token resource", + Attributes: map[string]schema.Attribute{ + "group": schema.StringAttribute{ + MarkdownDescription: "The name of the group.", + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "expiration": schema.StringAttribute{ + MarkdownDescription: ` +Expiration time for the token. If not provided, defaults to "never". + +A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, +such as "300s", "-1.5h" or "2h45m". + +Valid time units are "s", "m", "h"."`, + Optional: true, + CustomType: timetypes.GoDurationType{}, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "token": schema.StringAttribute{ + MarkdownDescription: "The group authorization token (JWT).", + Computed: true, + Sensitive: true, + }, + "expires_at": schema.StringAttribute{ + MarkdownDescription: "The computed expiration time of the token.", + Computed: true, + CustomType: timetypes.RFC3339Type{}, + }, + }, + } +} + +func (r *GroupTokenResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(*tursoadmin.Client) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *client.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + return + } + + r.client = client +} + +func (r *GroupTokenResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data GroupTokenResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *GroupTokenResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data GroupTokenResourceModel + + // Read Terraform plan data into the model + resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + now := time.Now().UTC() + var expiration time.Duration + if !data.Expiration.IsUnknown() && !data.Expiration.IsNull() { + exp, diags := data.Expiration.ValueGoDuration() + resp.Diagnostics.Append(diags...) + if diags.HasError() { + return + } + expiration = exp + } else { + data.Expiration = timetypes.NewGoDurationNull() + } + + res, err := r.client.CreateGroupToken(ctx, data.GroupName.ValueString(), expiration) + if err != nil { + resp.Diagnostics.AddError("client error", err.Error()) + return + } + data.Token = types.StringValue(res) + if expiration != time.Duration(0) { + data.ExpiresAt = timetypes.NewRFC3339TimeValue(now.Add(expiration)) + } else { + data.ExpiresAt = timetypes.NewRFC3339Null() + } + + tflog.Trace(ctx, "created group token") + + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *GroupTokenResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + panic("should have forced replacement") +} + +func (r *GroupTokenResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data GroupTokenResourceModel + resp.Diagnostics.Append(req.State.Get(ctx, &data)...) + if resp.Diagnostics.HasError() { + return + } + + // Technically we can only invalidate ALL group tokens, but because we expect only one token to exist per group at a time + // with no expiration, this is acceptable. + err := r.client.InvalidateGroupTokens(ctx, data.GroupName.ValueString()) + if err != nil { + resp.Diagnostics.AddWarning("client error", err.Error()) + return + } + + tflog.Trace(ctx, "deleted group token") +} diff --git a/internal/provider/resource_group_token_test.go b/internal/provider/resource_group_token_test.go new file mode 100644 index 0000000..9a3b0cf --- /dev/null +++ b/internal/provider/resource_group_token_test.go @@ -0,0 +1,137 @@ +package provider + +import ( + "database/sql" + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/knownvalue" + "github.com/hashicorp/terraform-plugin-testing/plancheck" + "github.com/hashicorp/terraform-plugin-testing/statecheck" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" + "github.com/tursodatabase/libsql-client-go/libsql" +) + +func TestAccResourceGroupToken_NoExpiration(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccCreateConfig(` + resource "turso_group_token" "test" { + group = "test" + }`), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectSensitiveValue("turso_group_token.test", tfjsonpath.New("token")), + statecheck.ExpectKnownValue("turso_group_token.test", tfjsonpath.New("token"), knownvalue.NotNull()), + statecheck.ExpectKnownValue("turso_group_token.test", tfjsonpath.New("expires_at"), knownvalue.Null()), // no expiration + }, + }, + + // Should not refresh token + { + Config: testAccCreateConfig(` + resource "turso_group_token" "test" { + group = "test" + }`), + ConfigPlanChecks: resource.ConfigPlanChecks{ + PreApply: []plancheck.PlanCheck{ + plancheck.ExpectEmptyPlan(), + }, + }, + }, + }, + }) +} + +func TestAccResourceGroupToken_WithExpiration(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccCreateConfig(` + resource "turso_group_token" "test" { + group = "test" + expiration = "1h" + }`), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectSensitiveValue("turso_group_token.test", tfjsonpath.New("token")), + statecheck.ExpectKnownValue("turso_group_token.test", tfjsonpath.New("token"), knownvalue.NotNull()), + statecheck.ExpectKnownValue("turso_group_token.test", tfjsonpath.New("expires_at"), knownvalue.NotNull()), // no expiration + }, + }, + + // Must refresh token when expiration changes + { + Config: testAccCreateConfig(` + resource "turso_group_token" "test" { + group = "test" + }`), + ConfigPlanChecks: resource.ConfigPlanChecks{ + PreApply: []plancheck.PlanCheck{ + plancheck.ExpectNonEmptyPlan(), + }, + }, + }, + }, + }) +} + +func TestAccResourceGroupToken_E2E(t *testing.T) { + name := randomName() + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProtoV6ProviderFactories: testAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testAccCreateConfig(` + resource "turso_database" "test" { + group = "test" + name = "` + name + `" + } + resource "turso_group_token" "test" { + group = "test" + }`), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("instances"), knownvalue.MapSizeExact(1)), + statecheck.ExpectKnownValue("turso_database.test", tfjsonpath.New("hostname"), knownvalue.NotNull()), + + statecheck.ExpectSensitiveValue("turso_group_token.test", tfjsonpath.New("token")), + statecheck.ExpectKnownValue("turso_group_token.test", tfjsonpath.New("token"), knownvalue.NotNull()), + statecheck.ExpectKnownValue("turso_group_token.test", tfjsonpath.New("expires_at"), knownvalue.Null()), // no expiration + }, + Check: func(s *terraform.State) error { + dbHostname, ok := s.RootModule().Resources["turso_database.test"].Primary.Attributes["hostname"] + if !ok { + return fmt.Errorf("missing hostname") + } + token, ok := s.RootModule().Resources["turso_group_token.test"].Primary.Attributes["token"] + if !ok { + return fmt.Errorf("missing token") + } + + connector, err := libsql.NewConnector("libsql://"+dbHostname, libsql.WithAuthToken(token)) + if err != nil { + return fmt.Errorf("error creating database connector: %v", err) + } + db := sql.OpenDB(connector) + defer db.Close() + + // Test connection + if err := db.Ping(); err != nil { + return fmt.Errorf("error pinging database: %v", err) + } + if _, err := db.Query("select 1"); err != nil { + return fmt.Errorf("error querying database: %v", err) + } + + return nil + }, + }, + }, + }) +} diff --git a/internal/tursoadmin/internal/httpmodel/httpmodel.go b/internal/tursoadmin/internal/httpmodel/httpmodel.go new file mode 100644 index 0000000..822b763 --- /dev/null +++ b/internal/tursoadmin/internal/httpmodel/httpmodel.go @@ -0,0 +1,78 @@ +package httpmodel + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "reflect" + "testing/iotest" +) + +type JSONClient struct { + *http.Client + baseURL string + headers map[string]string +} + +func NewJSONClient(client *http.Client, baseURL string, headers map[string]string) *JSONClient { + return &JSONClient{Client: client, baseURL: baseURL, headers: headers} +} + +type JSON[R any] struct { + method string + url string + request io.Reader + response R +} + +func NewJSON[R any](method string, url string, request interface{}) *JSON[R] { + model := JSON[R]{ + method: method, + url: url, + } + body, err := json.Marshal(request) + if err != nil { + model.request = iotest.ErrReader( + fmt.Errorf("error marshalling body (%T): %v", request, err)) + } else { + model.request = bytes.NewReader(body) + } + return &model +} + +func (m *JSON[R]) Send(ctx context.Context, client *JSONClient) (R, error) { + req, err := http.NewRequestWithContext(ctx, m.method, client.baseURL+m.url, m.request) + if err != nil { + return m.response, fmt.Errorf("error creating request: %v", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + for key, value := range client.headers { + req.Header.Set(key, value) + } + resp, err := client.Do(req) + if err != nil { + return m.response, fmt.Errorf("error sending request: %v", err) + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return m.response, fmt.Errorf("unexpected status code: %v", resp.Status) + } + defer resp.Body.Close() + decoder := json.NewDecoder(resp.Body) + err = decoder.Decode(&m.response) + if err != nil { + if err == io.EOF { + v := reflect.ValueOf(m.response) + if v.Kind() == reflect.Struct && v.NumField() == 0 { + return m.response, nil + } + return m.response, errors.New("empty response") + } + return m.response, fmt.Errorf("error reading response: %v", err) + } + return m.response, nil +} diff --git a/internal/tursoadmin/tursoadmin.go b/internal/tursoadmin/tursoadmin.go new file mode 100644 index 0000000..cbf0128 --- /dev/null +++ b/internal/tursoadmin/tursoadmin.go @@ -0,0 +1,66 @@ +package tursoadmin + +import ( + "errors" + "net/http" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin/internal/httpmodel" +) + +// Config is the configuration for a Turso admin client. +type Config struct { + // Required. The name of the organization. + OrgName string + + // Required. The API token for the organization. + APIToken string + + // Optional. The HTTP client to use for API requests. + // + // Default: `http.DefaultClient` + HTTPClient *http.Client + + // Optional. The base URL for API requests. + // + // Default: `https://api.turso.tech/v1` + BaseURL string +} + +// Client is a Turso admin client. +type Client struct { + http *httpmodel.JSONClient + baseURL string + orgName string +} + +// NewClient creates a new Turso admin client. +func NewClient(config Config) (*Client, error) { + if config.OrgName == "" { + return nil, errors.New("missing organization name") + } + if config.APIToken == "" { + return nil, errors.New("missing API token") + } + baseURL := coalesce(config.BaseURL, "https://api.turso.tech/v1") + return &Client{ + http: httpmodel.NewJSONClient( + coalesce(config.HTTPClient, http.DefaultClient), + baseURL, + map[string]string{ + "Authorization": "Bearer " + config.APIToken, + }, + ), + baseURL: baseURL, + orgName: config.OrgName, + }, nil +} + +func coalesce[T comparable](values ...T) T { + var zero T + for _, value := range values { + if value != zero { + return value + } + } + return zero +} diff --git a/internal/tursoadmin/tursoadmin_database.go b/internal/tursoadmin/tursoadmin_database.go new file mode 100644 index 0000000..78c7cb2 --- /dev/null +++ b/internal/tursoadmin/tursoadmin_database.go @@ -0,0 +1,270 @@ +package tursoadmin + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin/internal/httpmodel" +) + +// CreateDatabaseRequest is the configuration for creating a new Turso database. +type CreateDatabaseRequest struct { + Name string `json:"name"` + + // The name of the group where the database should be created. The group must already exist. + Group string `json:"group,omitempty"` + + Seed *DatabaseSeed `json:"seed,omitempty"` + + // The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb. + SizeLimit string `json:"size_limit,omitempty"` + + // Mark this database as the parent schema database that updates child databases with any schema changes. + // + // See [Multi-DB Schemas](https://docs.turso.tech/features/multi-db-schemas). + IsSchema bool `json:"is_schema,omitempty"` + + // The name of the parent database to use as the schema. + // + // See [Multi-DB Schemas](https://docs.turso.tech/features/multi-db-schemas). + SchemaDatabase string `json:"schema,omitempty"` +} + +type DatabaseSeedType string + +const ( + DatabaseSeedDatabase DatabaseSeedType = "database" + DatabaseSeedDump DatabaseSeedType = "dump" +) + +type DatabaseSeed struct { + // The type of seed to be used to create a new database. + Type DatabaseSeedType `json:"type"` + + // The name of the existing database when `database` is used as a seed type. + Name string `json:"name,omitempty"` + + // The URL returned by [upload dump](https://docs.turso.tech/api-reference/databases/upload-dump) + // can be used with the `dump` seed type. + URL string `json:"url,omitempty"` + + // A formatted ISO 8601 recovery point to create a database from. This must be within the + // last 24 hours, or 30 days on the scaler plan. + Timestamp *time.Time `json:"timestamp,omitempty"` +} + +// Database represents a Turso database's metadata. +type Database struct { + // The database universal unique identifier (UUID). + ID string `json:"DbId"` + + // The DNS hostname used for client libSQL and HTTP connections. + Hostname string `json:"Hostname"` + + // The database name, unique across your organization. + Name string `json:"Name"` +} + +type DatabaseConfig struct { + // The maximum size of the database in bytes. Values with units are also accepted, e.g. 1mb, 256mb, 1gb. + SizeLimit *string `json:"size_limit,omitempty"` + + // Allow or disallow attaching databases to the current database. + AllowAttach *bool `json:"allow_attach,omitempty"` + + // Block all database reads. + BlockReads *bool `json:"block_reads,omitempty"` + + // Block all database writes. + BlockWrites *bool `json:"block_writes,omitempty"` +} + +// A Database with its configuration, returned from GetDatabase. +type DatabaseWithConfig struct { + // The database universal unique identifier (UUID). + ID string `json:"DbId"` + + // The DNS hostname used for client libSQL and HTTP connections. + Hostname string `json:"Hostname"` + + // The database name, unique across your organization. + Name string `json:"Name"` + + // The name of the group the database belongs to. + Group string `json:"group"` + + // Allow or disallow attaching databases to the current database. + AllowAttach bool `json:"allow_attach"` + + // Block all database reads. + BlockReads bool `json:"block_reads"` + + // Block all database writes. + BlockWrites bool `json:"block_writes"` + + // A list of regions for the group the database belongs to. + Regions []string `json:"regions"` + + // The primary region location code the group the database belongs to. + PrimaryRegion string `json:"primaryRegion"` + + // The string representing the object type. + Type string `json:"type"` + + // The current libSQL version the database is running. + Version string `json:"version"` + + // If this database controls other child databases then this will be true. + // + // See [Multi-DB Schemas](https://docs.turso.tech/features/multi-db-schemas). + IsSchema bool `json:"is_schema"` + + // The name of the parent database that owns the schema for this database. + // + // See [Multi-DB Schemas](https://docs.turso.tech/features/multi-db-schemas). + Schema string `json:"schema,omitempty"` +} + +type DatabaseInstanceType string + +const ( + DatabaseInstanceTypePrimary DatabaseInstanceType = "primary" + DatabaseInstanceTypeReplica DatabaseInstanceType = "replica" +) + +// An instance of a Database. +type DatabaseInstance struct { + // The instance universal unique identifier (UUID). + UUID string `json:"uuid"` + + // The name of the instance (location code). + Name string `json:"name"` + + // The type of database instance. One of: `primary` or `replica`. + Type DatabaseInstanceType `json:"type"` + + // The location code for the region this instance is located. + Region string `json:"region"` + + // The DNS hostname used for client libSQL and HTTP connections (specific to this instance only). + Hostname string `json:"hostname"` +} + +// CreateDatabase creates a new database in a group for the organization or user. +// +// https://docs.turso.tech/api-reference/databases/create +func (c *Client) CreateDatabase(ctx context.Context, request CreateDatabaseRequest) (Database, error) { + type response struct { + Database Database `json:"database"` + } + model := httpmodel.NewJSON[response](http.MethodPost, "/organizations/"+c.orgName+"/databases", request) + resp, err := model.Send(ctx, c.http) + if err != nil { + return Database{}, fmt.Errorf("failed to create database: %v", err) + } + return resp.Database, nil +} + +// ListDatabaseInstances returns a list of instances of a database. Instances are the individual primary or replica databases in each region defined by the group. +// +// https://docs.turso.tech/api-reference/databases/list-instances +func (c *Client) ListDatabaseInstances(ctx context.Context, dbName string) ([]DatabaseInstance, error) { + type response struct { + Instances []DatabaseInstance `json:"instances"` + } + model := httpmodel.NewJSON[response](http.MethodGet, "/organizations/"+c.orgName+"/databases/"+dbName+"/instances", nil) + resp, err := model.Send(ctx, c.http) + if err != nil { + return nil, fmt.Errorf("failed to read database instances: %v", err) + } + return resp.Instances, nil +} + +// GetDatabase retrieves a database by name. +// +// https://docs.turso.tech/api-reference/databases/retrieve +func (c *Client) GetDatabase(ctx context.Context, dbName string) (DatabaseWithConfig, error) { + type response struct { + Database DatabaseWithConfig `json:"database"` + } + model := httpmodel.NewJSON[response](http.MethodGet, "/organizations/"+c.orgName+"/databases/"+dbName, struct{}{}) + resp, err := model.Send(ctx, c.http) + if err != nil { + return DatabaseWithConfig{}, fmt.Errorf("failed to get database: %v", err) + } + return resp.Database, nil +} + +// GetDatabaseConfiguration gets a database's configuration. +// +// https://docs.turso.tech/api-reference/databases/configuration +func (c *Client) GetDatabaseConfiguration(ctx context.Context, dbName string) (DatabaseConfig, error) { + model := httpmodel.NewJSON[DatabaseConfig](http.MethodGet, "/organizations/"+c.orgName+"/databases/"+dbName+"/configuration", nil) + config, err := model.Send(ctx, c.http) + if err != nil { + return DatabaseConfig{}, fmt.Errorf("failed to get database config: %v", err) + } + return config, nil +} + +// UpdateDatabaseConfiguration updates a database's configuration. +// +// https://docs.turso.tech/api-reference/databases/update-configuration +func (c *Client) UpdateDatabaseConfiguration(ctx context.Context, dbName string, config DatabaseConfig) (DatabaseConfig, error) { + model := httpmodel.NewJSON[DatabaseConfig](http.MethodPatch, "/organizations/"+c.orgName+"/databases/"+dbName+"/configuration", config) + updatedConfig, err := model.Send(ctx, c.http) + if err != nil { + return DatabaseConfig{}, fmt.Errorf("failed to update database config: %v", err) + } + return updatedConfig, nil +} + +// DeleteDatabase deletes a database by name. +// +// https://docs.turso.tech/api-reference/databases/delete +func (c *Client) DeleteDatabase(ctx context.Context, dbName string) error { + model := httpmodel.NewJSON[struct{}](http.MethodDelete, "/organizations/"+c.orgName+"/databases/"+dbName, nil) + _, err := model.Send(ctx, c.http) + if err != nil { + return fmt.Errorf("failed to delete database: %v", err) + } + return nil +} + +// CreateDatabaseToken generates an authorization token for the specified database. +// +// https://docs.turso.tech/api-reference/databases/create-token +func (c *Client) CreateDatabaseToken(ctx context.Context, dbName string, expiration time.Duration) (string, error) { + type response struct { + JWT string `json:"jwt"` // jwt is the JSON Web Token. + } + var expParam string + if expiration == time.Duration(0) { + expParam = "never" + } else { + expParam = fmt.Sprintf("%ds", int(expiration.Seconds())) + } + route := fmt.Sprintf("/organizations/%s/databases/%s/auth/tokens?expiration=%s&authorization=full-access", c.orgName, dbName, expParam) + model := httpmodel.NewJSON[response](http.MethodPost, route, struct{}{}) + resp, err := model.Send(ctx, c.http) + if err != nil { + return "", fmt.Errorf("failed to create database token: %v", err) + } + return resp.JWT, nil +} + +// InvalidateDatabaseTokens invalidates all authorization tokens for the specified database. +// +// https://docs.turso.tech/api-reference/databases/invalidate-tokens +func (c *Client) InvalidateDatabaseTokens(ctx context.Context, dbName string) error { + route := fmt.Sprintf("/organizations/%s/databases/%s/auth/rotate", c.orgName, dbName) + fmt.Printf("Invalidating all database tokens for: %s", route) + model := httpmodel.NewJSON[struct{}](http.MethodPost, route, nil) + _, err := model.Send(ctx, c.http) + if err != nil { + return fmt.Errorf("failed to invalidate database token: %v", err) + } + return nil +} diff --git a/internal/tursoadmin/tursoadmin_group.go b/internal/tursoadmin/tursoadmin_group.go new file mode 100644 index 0000000..9744d5d --- /dev/null +++ b/internal/tursoadmin/tursoadmin_group.go @@ -0,0 +1,154 @@ +package tursoadmin + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/celest-dev/terraform-provider-turso/internal/tursoadmin/internal/httpmodel" +) + +// Group represents a Turso group's metadata. +type Group struct { + Name string `json:"name"` + Version string `json:"version"` + UUID string `json:"uuid"` + Locations []string `json:"locations"` + PrimaryLocation string `json:"primary"` + Archived bool `json:"archived"` +} + +type Extensions string + +const ( + ExtensionsAll Extensions = "all" +) + +type CreateGroupRequest struct { + Name string `json:"name"` + Location string `json:"location"` + Extensions Extensions `json:"extensions,omitempty"` +} + +// GetGroup retrieves a group by name. +// +// https://docs.turso.tech/api-reference/groups/retrieve +func (c *Client) GetGroup(ctx context.Context, groupName string) (Group, error) { + type response struct { + Group Group `json:"group"` + } + model := httpmodel.NewJSON[response](http.MethodGet, "/organizations/"+c.orgName+"/groups/"+groupName, struct{}{}) + resp, err := model.Send(ctx, c.http) + if err != nil { + return Group{}, fmt.Errorf("failed to get group: %v", err) + } + return resp.Group, nil +} + +// CreateGroup creates a new group in the organization. +// +// https://docs.turso.tech/api-reference/groups/create +func (c *Client) CreateGroup(ctx context.Context, request CreateGroupRequest) (Group, error) { + type response struct { + Group Group `json:"group"` + } + model := httpmodel.NewJSON[response](http.MethodPost, "/organizations/"+c.orgName+"/groups", request) + resp, err := model.Send(ctx, c.http) + if err != nil { + return Group{}, fmt.Errorf("failed to create group: %v", err) + } + return resp.Group, nil +} + +// AddGroupLocation adds a location to a group. +// +// https://docs.turso.tech/api-reference/groups/add-location +func (c *Client) AddGroupLocation(ctx context.Context, groupName, location string) (Group, error) { + type response struct { + Group Group `json:"group"` + } + model := httpmodel.NewJSON[response](http.MethodPost, "/organizations/"+c.orgName+"/groups/"+groupName+"/locations/"+location, nil) + resp, err := model.Send(ctx, c.http) + if err != nil { + return Group{}, fmt.Errorf("failed to add location to group: %v", err) + } + return resp.Group, nil +} + +// RemoveGroupLocation removes a location from a group. +// +// https://docs.turso.tech/api-reference/groups/remove-location +func (c *Client) RemoveGroupLocation(ctx context.Context, groupName, location string) (Group, error) { + type response struct { + Group Group `json:"group"` + } + model := httpmodel.NewJSON[response](http.MethodDelete, "/organizations/"+c.orgName+"/groups/"+groupName+"/locations/"+location, nil) + resp, err := model.Send(ctx, c.http) + if err != nil { + return Group{}, fmt.Errorf("failed to remove location from group: %v", err) + } + return resp.Group, nil +} + +// CreateGroupToken generates an authorization token for the specified group. +// +// https://docs.turso.tech/api-reference/groups/create-token +func (c *Client) CreateGroupToken(ctx context.Context, groupName string, expiration time.Duration) (string, error) { + type response struct { + JWT string `json:"jwt"` + } + var expParam string + if expiration == time.Duration(0) { + expParam = "never" + } else { + expParam = fmt.Sprintf("%ds", int(expiration.Seconds())) + } + route := fmt.Sprintf("/organizations/%s/groups/%s/auth/tokens?expiration=%s&authorization=full-access", c.orgName, groupName, expParam) + model := httpmodel.NewJSON[response](http.MethodPost, route, struct{}{}) + resp, err := model.Send(ctx, c.http) + if err != nil { + return "", fmt.Errorf("failed to create group token: %v", err) + } + return resp.JWT, nil +} + +// InvalidateGroupTokens invalidates all authorization tokens for the specified group. +// +// https://docs.turso.tech/api-reference/groups/invalidate-tokens +func (c *Client) InvalidateGroupTokens(ctx context.Context, groupName string) error { + route := fmt.Sprintf("/organizations/%s/groups/%s/auth/rotate", c.orgName, groupName) + model := httpmodel.NewJSON[struct{}](http.MethodPost, route, nil) + _, err := model.Send(ctx, c.http) + if err != nil { + return fmt.Errorf("failed to invalidate group token: %v", err) + } + return nil +} + +// DeleteGroup deletes a group by name. +// +// https://docs.turso.tech/api-reference/groups/delete +func (c *Client) DeleteGroup(ctx context.Context, groupName string) error { + model := httpmodel.NewJSON[struct{}](http.MethodDelete, "/organizations/"+c.orgName+"/groups/"+groupName, nil) + _, err := model.Send(ctx, c.http) + if err != nil { + return fmt.Errorf("failed to delete group: %v", err) + } + return nil +} + +// ListGroups retrieves all groups in the organization. +// +// https://docs.turso.tech/api-reference/groups/list +func (c *Client) ListGroups(ctx context.Context) ([]Group, error) { + type response struct { + Groups []Group `json:"groups"` + } + model := httpmodel.NewJSON[response]("GET", "/organizations/"+c.orgName+"/groups", struct{}{}) + resp, err := model.Send(ctx, c.http) + if err != nil { + return nil, fmt.Errorf("failed to list groups: %v", err) + } + return resp.Groups, nil +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..ff0ea02 --- /dev/null +++ b/main.go @@ -0,0 +1,49 @@ +package main + +import ( + "context" + "flag" + "log" + + "github.com/celest-dev/terraform-provider-turso/internal/provider" + + "github.com/hashicorp/terraform-plugin-framework/providerserver" +) + +// Run "go generate" to format example terraform files and generate the docs for the registry/website + +// If you do not have terraform installed, you can remove the formatting command, but its suggested to +// ensure the documentation is formatted properly. +//go:generate terraform fmt -recursive ./examples/ + +// Run the docs generation tool, check its repository for more information on how it works and how docs +// can be customized. +//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs generate -provider-name turso + +var ( + // these will be set by the goreleaser configuration + // to appropriate values for the compiled binary. + version string = "dev" + + // goreleaser can pass other information to the main package, such as the specific commit + // https://goreleaser.com/cookbooks/using-main.version/ +) + +func main() { + var debug bool + + flag.BoolVar(&debug, "debug", false, "set to true to run the provider with support for debuggers like delve") + flag.Parse() + + opts := providerserver.ServeOpts{ + Address: "registry.terraform.io/celest-dev/turso", + ProtocolVersion: 6, + Debug: debug, + } + + err := providerserver.Serve(context.Background(), provider.New(version), opts) + + if err != nil { + log.Fatal(err.Error()) + } +} diff --git a/terraform-registry-manifest.json b/terraform-registry-manifest.json new file mode 100644 index 0000000..fec2a56 --- /dev/null +++ b/terraform-registry-manifest.json @@ -0,0 +1,6 @@ +{ + "version": 1, + "metadata": { + "protocol_versions": ["6.0"] + } +} diff --git a/tools/tools.go b/tools/tools.go new file mode 100644 index 0000000..2c4f8fb --- /dev/null +++ b/tools/tools.go @@ -0,0 +1,8 @@ +//go:build tools + +package tools + +import ( + // Documentation generation + _ "github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs" +)