Merge pull request #394 from sosedoff/fix-row-estimation

Fix row estimation bug
This commit is contained in:
Dan Sosedoff 2018-12-12 14:33:06 -06:00 committed by GitHub
commit c9d94b54d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 11 deletions

View File

@ -238,22 +238,25 @@ func (client *Client) EstimatedTableRowsCount(table string, opts RowsOptions) (*
}
func (client *Client) TableRowsCount(table string, opts RowsOptions) (*Result, error) {
schema, table := getSchemaAndTable(table)
sql := fmt.Sprintf(`SELECT COUNT(1) FROM "%s"."%s"`, schema, table)
if opts.Where != "" {
sql += fmt.Sprintf(" WHERE %s", opts.Where)
} else if client.serverType == postgresType {
tableInfo, err := client.TableInfo(table)
// Return postgres estimated rows count on empty filter
if opts.Where == "" && client.serverType == postgresType {
res, err := client.EstimatedTableRowsCount(table, opts)
if err != nil {
return nil, err
}
estimatedRowsCount := tableInfo.Rows[0][3].(float64)
if estimatedRowsCount > 100000 {
return client.EstimatedTableRowsCount(table, opts)
n := res.Rows[0][0].(int64)
if n >= 100000 {
return res, nil
}
}
schema, tableName := getSchemaAndTable(table)
sql := fmt.Sprintf(`SELECT COUNT(1) FROM "%s"."%s"`, schema, tableName)
if opts.Where != "" {
sql += fmt.Sprintf(" WHERE %s", opts.Where)
}
return client.query(sql)
}

View File

@ -301,7 +301,7 @@ func testTableRowsCount(t *testing.T) {
func testTableRowsCountWithLargeTable(t *testing.T) {
var count int64 = 100010
testClient.db.MustExec(`create table large_table as select s from generate_Series(1,100010) s;`)
testClient.db.MustExec(`CREATE TABLE large_table AS SELECT s FROM generate_Series(1,100010) s;`)
testClient.db.MustExec(`VACUUM large_table;`)
res, err := testClient.TableRowsCount("large_table", RowsOptions{})