Skip to content

Commit

Permalink
fix(outputs.sql): Cache the table existence result properly
Browse files Browse the repository at this point in the history
The old code will keep checking the table existence when the
table was created before, for example, after restarting telegraf.
  • Loading branch information
Wenhao Huang committed Mar 14, 2022
1 parent 4fcff21 commit 475e158
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions plugins/outputs/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,18 @@ func (p *SQL) generateInsert(tablename string, columns []string) string {
}

func (p *SQL) tableExists(tableName string) bool {
if p.tables[tableName] {
return true
}

stmt := strings.Replace(p.TableExistsTemplate, "{TABLE}", quoteIdent(tableName), -1)

_, err := p.db.Exec(stmt)
return err == nil
if err == nil {
p.tables[tableName] = true
return true
}
return false
}

func (p *SQL) Write(metrics []telegraf.Metric) error {
Expand All @@ -245,13 +253,12 @@ func (p *SQL) Write(metrics []telegraf.Metric) error {
tablename := metric.Name()

// create table if needed
if !p.tables[tablename] && !p.tableExists(tablename) {
if !p.tableExists(tablename) {
createStmt := p.generateCreateTable(metric)
_, err := p.db.Exec(createStmt)
if err != nil {
return err
}
p.tables[tablename] = true
}

var columns []string
Expand Down

0 comments on commit 475e158

Please sign in to comment.