forked from cyrilgdn/terraform-provider-postgresql
-
Notifications
You must be signed in to change notification settings - Fork 1
add postgresql_script resource #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
a35a285
add postgresql_script resource
antoineverin 48ac715
fix typo in the postgresql_script description
antoineverin aafff3b
add reference to postgresql_script in documentation
antoineverin 255d84e
improve definition of postgresql_script resource in documentation
antoineverin 2e843f4
update retry logic to retry all instead of the failing one in postgre…
antoineverin e1a4937
add test case for multiple failing command
antoineverin 3f3e83f
rename timeout to backoffDelay
antoineverin fc353f8
rename timeout to backoffdelay in documentation
antoineverin faa3740
fix backoffdelay name to backoff_delay
antoineverin 0ece4b4
Update postgresql/resource_postgresql_script.go
antoineverin b46675b
rename timeout to backoff_delay in tests
antoineverin 0d873a3
refactor resource logic
antoineverin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
package postgresql | ||
|
||
import ( | ||
"crypto/sha1" | ||
"encoding/hex" | ||
"log" | ||
"time" | ||
|
||
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" | ||
) | ||
|
||
const ( | ||
scriptCommandsAttr = "commands" | ||
scriptTriesAttr = "tries" | ||
scriptBackoffDelayAttr = "backoff_delay" | ||
scriptShasumAttr = "shasum" | ||
) | ||
|
||
func resourcePostgreSQLScript() *schema.Resource { | ||
return &schema.Resource{ | ||
Create: PGResourceFunc(resourcePostgreSQLScriptCreateOrUpdate), | ||
Read: PGResourceFunc(resourcePostgreSQLScriptRead), | ||
Update: PGResourceFunc(resourcePostgreSQLScriptCreateOrUpdate), | ||
Delete: PGResourceFunc(resourcePostgreSQLScriptDelete), | ||
|
||
Schema: map[string]*schema.Schema{ | ||
scriptCommandsAttr: { | ||
Type: schema.TypeList, | ||
Required: true, | ||
Description: "List of SQL commands to execute", | ||
Elem: &schema.Schema{ | ||
Type: schema.TypeString, | ||
}, | ||
}, | ||
scriptTriesAttr: { | ||
Type: schema.TypeInt, | ||
Optional: true, | ||
Default: 1, | ||
Description: "Number of tries for a failing command", | ||
}, | ||
scriptBackoffDelayAttr: { | ||
Type: schema.TypeInt, | ||
Optional: true, | ||
Default: 1, | ||
Description: "Number of seconds between two tries of the batch of commands", | ||
}, | ||
scriptShasumAttr: { | ||
Type: schema.TypeString, | ||
Computed: true, | ||
Description: "Shasum of commands", | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
func resourcePostgreSQLScriptCreateOrUpdate(db *DBConnection, d *schema.ResourceData) error { | ||
commands := d.Get(scriptCommandsAttr).([]any) | ||
tries := d.Get(scriptTriesAttr).(int) | ||
backoffDelay := d.Get(scriptBackoffDelayAttr).(int) | ||
|
||
sum := shasumCommands(commands) | ||
|
||
if err := executeCommands(db, commands, tries, backoffDelay); err != nil { | ||
return err | ||
} | ||
|
||
d.Set(scriptShasumAttr, sum) | ||
d.SetId(sum) | ||
return nil | ||
} | ||
|
||
func resourcePostgreSQLScriptRead(db *DBConnection, d *schema.ResourceData) error { | ||
commands := d.Get(scriptCommandsAttr).([]any) | ||
newSum := shasumCommands(commands) | ||
d.Set(scriptShasumAttr, newSum) | ||
|
||
return nil | ||
} | ||
|
||
func resourcePostgreSQLScriptDelete(db *DBConnection, d *schema.ResourceData) error { | ||
return nil | ||
} | ||
|
||
func executeCommands(db *DBConnection, commands []any, tries int, backoffDelay int) error { | ||
for try := 1; ; try++ { | ||
err := executeBatch(db, commands) | ||
if err == nil { | ||
return nil | ||
} else { | ||
if try >= tries { | ||
return err | ||
} | ||
time.Sleep(time.Duration(backoffDelay) * time.Second) | ||
} | ||
} | ||
} | ||
|
||
func executeBatch(db *DBConnection, commands []any) error { | ||
for _, command := range commands { | ||
log.Printf("[ERROR] Executing %s", command.(string)) | ||
_, err := db.Query(command.(string)) | ||
|
||
if err != nil { | ||
log.Println("[ERROR] Error catched:", err) | ||
if _, rollbackError := db.Query("ROLLBACK"); rollbackError != nil { | ||
log.Println("[ERROR] Rollback raised an error:", rollbackError) | ||
} | ||
return err | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
func shasumCommands(commands []any) string { | ||
sha := sha1.New() | ||
for _, command := range commands { | ||
sha.Write([]byte(command.(string))) | ||
} | ||
return hex.EncodeToString(sha.Sum(nil)) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
package postgresql | ||
|
||
import ( | ||
"regexp" | ||
"testing" | ||
|
||
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" | ||
) | ||
|
||
func TestAccPostgresqlScript_basic(t *testing.T) { | ||
config := ` | ||
resource "postgresql_script" "test" { | ||
commands = [ | ||
"SELECT 1;" | ||
] | ||
tries = 2 | ||
backoff_delay = 4 | ||
} | ||
` | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { testAccPreCheck(t) }, | ||
Providers: testAccProviders, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: config, | ||
Check: resource.ComposeTestCheckFunc( | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.0", "SELECT 1;"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "tries", "2"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "backoff_delay", "4"), | ||
), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func TestAccPostgresqlScript_multiple(t *testing.T) { | ||
config := ` | ||
resource "postgresql_script" "test" { | ||
commands = [ | ||
"SELECT 1;", | ||
"SELECT 2;", | ||
"SELECT 3;" | ||
] | ||
tries = 2 | ||
backoff_delay = 4 | ||
} | ||
` | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { testAccPreCheck(t) }, | ||
Providers: testAccProviders, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: config, | ||
Check: resource.ComposeTestCheckFunc( | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.0", "SELECT 1;"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.1", "SELECT 2;"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.2", "SELECT 3;"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "tries", "2"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "backoff_delay", "4"), | ||
), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func TestAccPostgresqlScript_default(t *testing.T) { | ||
config := ` | ||
resource "postgresql_script" "test" { | ||
commands = [ | ||
"SELECT 1;" | ||
] | ||
} | ||
` | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { testAccPreCheck(t) }, | ||
Providers: testAccProviders, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: config, | ||
Check: resource.ComposeTestCheckFunc( | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.0", "SELECT 1;"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "tries", "1"), | ||
resource.TestCheckResourceAttr("postgresql_script.test", "backoff_delay", "1"), | ||
), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func TestAccPostgresqlScript_reapply(t *testing.T) { | ||
config := ` | ||
resource "postgresql_script" "test" { | ||
commands = [ | ||
"SELECT 1;" | ||
] | ||
} | ||
` | ||
|
||
configChange := ` | ||
resource "postgresql_script" "test" { | ||
commands = [ | ||
"SELECT 2;" | ||
] | ||
} | ||
` | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { testAccPreCheck(t) }, | ||
Providers: testAccProviders, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: config, | ||
Check: resource.ComposeTestCheckFunc( | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.0", "SELECT 1;"), | ||
), | ||
}, | ||
{ | ||
Config: config, | ||
Check: resource.ComposeTestCheckFunc( | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.0", "SELECT 1;"), | ||
), | ||
}, | ||
{ | ||
Config: configChange, | ||
Check: resource.ComposeTestCheckFunc( | ||
resource.TestCheckResourceAttr("postgresql_script.test", "commands.0", "SELECT 2;"), | ||
), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func TestAccPostgresqlScript_fail(t *testing.T) { | ||
config := ` | ||
resource "postgresql_script" "invalid" { | ||
commands = [ | ||
"SLC FROM nowhere;" | ||
] | ||
tries = 2 | ||
backoff_delay = 2 | ||
} | ||
` | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { testAccPreCheck(t) }, | ||
Providers: testAccProviders, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: config, | ||
ExpectError: regexp.MustCompile("syntax error"), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
||
func TestAccPostgresqlScript_failMultiple(t *testing.T) { | ||
config := ` | ||
resource "postgresql_script" "invalid" { | ||
commands = [ | ||
"BEGIN", | ||
"SLC FROM nowhere;", | ||
"COMMIT" | ||
] | ||
tries = 2 | ||
backoff_delay = 2 | ||
} | ||
` | ||
|
||
resource.Test(t, resource.TestCase{ | ||
PreCheck: func() { testAccPreCheck(t) }, | ||
Providers: testAccProviders, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: config, | ||
ExpectError: regexp.MustCompile("syntax error"), | ||
}, | ||
}, | ||
}) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
--- | ||
layout: "postgresql" | ||
page_title: "PostgreSQL: postgresql_script" | ||
sidebar_current: "docs-postgresql-resource-postgresql_script" | ||
description: |- | ||
Execute a SQL script | ||
--- | ||
|
||
# postgresql\_script | ||
|
||
The ``postgresql_script`` execute a script given as parameter. This script will be executed each time it changes. | ||
antoineverin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
If one command of the batch fails, the provider will send a `ROLLBACK` command to the database, and retry, according to the tries / backoff_delay configuration. | ||
|
||
## Usage | ||
|
||
```hcl | ||
resource "postgresql_script" "foo" { | ||
commands = [ | ||
"command 1", | ||
"command 2" | ||
] | ||
tries = 1 | ||
backoff_delay = 1 | ||
} | ||
``` | ||
|
||
## Argument Reference | ||
|
||
* `commands` - (Required) An array of commands to execute, one by one. | ||
* `tries` - (Optional) Number of tries of a command before raising an error. | ||
* `backoff_delay` - (Optional) In case of failure, time in second to wait before a retry. | ||
|
||
## Examples | ||
|
||
Revoke default accesses for public schema: | ||
|
||
```hcl | ||
resource "postgresql_script" "foo" { | ||
commands = [ | ||
"BEBIN", | ||
"SELECT * FROM table", | ||
"COMMIT" | ||
] | ||
tries = 3 | ||
backoff_delay = 1 | ||
} | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.