Skip to content
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

mysql_databases Data source #160

Merged
merged 1 commit into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions mysql/data_source_databases.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package mysql

import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"log"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func dataSourceDatabases() *schema.Resource {
return &schema.Resource{
ReadContext: ShowDatabases,
Schema: map[string]*schema.Schema{
"pattern": {
Type: schema.TypeString,
Optional: true,
},
"databases": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}

func ShowDatabases(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
db, err := getDatabaseFromMeta(ctx, meta)
if err != nil {
return diag.FromErr(err)
}

pattern := d.Get("pattern").(string)

sql := fmt.Sprint("SHOW DATABASES")

if pattern != "" {
sql += fmt.Sprintf(" LIKE '%s'", pattern)
}

log.Printf("[DEBUG] SQL: %s", sql)

rows, err := db.QueryContext(ctx, sql)
if err != nil {
return diag.Errorf("failed querying for databases: %v", err)
}
defer rows.Close()

var databases []string
for rows.Next() {
var database string

if err := rows.Scan(&database); err != nil {
return diag.Errorf("failed scanning MySQL rows: %v", err)
}

databases = append(databases, database)
}

if err := d.Set("databases", databases); err != nil {
return diag.Errorf("failed setting databases field: %v", err)
}

d.SetId(id.UniqueId())

return nil
}
76 changes: 76 additions & 0 deletions mysql/data_source_databases_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package mysql

import (
"fmt"
"strconv"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccDataSourceDatabases(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: testAccProviderFactories,
Steps: []resource.TestStep{
{
Config: testAccDatabasesConfigBasic("%"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.mysql_databases.test", "pattern", "%"),
testAccDatabasesCount("data.mysql_databases.test", "databases.#", func(rn string, databaseCount int) error {
if databaseCount < 1 {
return fmt.Errorf("%s: databases not found", rn)
}

return nil
}),
),
},
{
Config: testAccDatabasesConfigBasic("__database_does_not_exist__"),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.mysql_databases.test", "pattern", "__database_does_not_exist__"),
testAccDatabasesCount("data.mysql_databases.test", "databases.#", func(rn string, databaseCount int) error {
if databaseCount > 0 {
return fmt.Errorf("%s: unexpected database found", rn)
}

return nil
}),
),
},
},
})
}

func testAccDatabasesCount(rn string, key string, check func(string, int) error) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[rn]

if !ok {
return fmt.Errorf("resource not found: %s", rn)
}

value, ok := rs.Primary.Attributes[key]

if !ok {
return fmt.Errorf("%s: attribute '%s' not found", rn, key)
}

databaseCount, err := strconv.Atoi(value)

if err != nil {
return err
}

return check(rn, databaseCount)
}
}

func testAccDatabasesConfigBasic(pattern string) string {
return fmt.Sprintf(`
data "mysql_databases" "test" {
pattern = "%s"
}`, pattern)
}
3 changes: 2 additions & 1 deletion mysql/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,8 @@ func Provider() *schema.Provider {
},

DataSourcesMap: map[string]*schema.Resource{
"mysql_tables": dataSourceTables(),
"mysql_databases": dataSourceDatabases(),
"mysql_tables": dataSourceTables(),
},

ResourcesMap: map[string]*schema.Resource{
Expand Down
32 changes: 32 additions & 0 deletions website/docs/d/databases.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
layout: "mysql"
page_title: "MySQL: mysql_databases"
sidebar_current: "docs-mysql-datasource-databases"
description: |-
Gets databases on a MySQL server.
---

# Data Source: mysql\_databases

The ``mysql_databases`` gets databases on a MySQL
server.

## Example Usage

```hcl
data "mysql_databases" "app" {
pattern = "test_%"
}
```

## Argument Reference

The following arguments are supported:

* `pattern` - (Optional) Patterns for searching databases.

## Attributes Reference

The following attributes are exported:

* `databases` - The list of the database names.
4 changes: 4 additions & 0 deletions website/mysql.erb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@
<a href="#">Data Sources</a>
<ul class="nav nav-visible">

<li<%= sidebar_current("docs-mysql-datasource-databases") %>>
<a href="/docs/providers/mysql/d/databases.html">mysql_databases</a>
</li>

<li<%= sidebar_current("docs-mysql-datasource-tables") %>>
<a href="/docs/providers/mysql/d/tables.html">mysql_tables</a>
</li>
Expand Down
Loading