Simplify TableRowsCount func logic

This commit is contained in:
Dan Sosedoff 2018-12-12 13:56:08 -06:00
parent 2db5ce544f
commit 7917c2ad35
2 changed files with 13 additions and 10 deletions

View File

@ -237,20 +237,23 @@ func (client *Client) EstimatedTableRowsCount(table string, opts RowsOptions) (*
} }
func (client *Client) TableRowsCount(table string, opts RowsOptions) (*Result, error) { func (client *Client) TableRowsCount(table string, opts RowsOptions) (*Result, error) {
// 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
}
n := res.Rows[0][0].(int64)
if n >= 100000 {
return res, nil
}
}
schema, tableName := getSchemaAndTable(table) schema, tableName := getSchemaAndTable(table)
sql := fmt.Sprintf(`SELECT COUNT(1) FROM "%s"."%s"`, schema, tableName) sql := fmt.Sprintf(`SELECT COUNT(1) FROM "%s"."%s"`, schema, tableName)
if opts.Where != "" { if opts.Where != "" {
sql += fmt.Sprintf(" WHERE %s", opts.Where) sql += fmt.Sprintf(" WHERE %s", opts.Where)
} else if client.serverType == postgresType {
tableInfo, err := client.TableInfo(table)
if err != nil {
return nil, err
}
estimatedRowsCount := tableInfo.Rows[0][3].(float64)
if estimatedRowsCount > 100000 {
return client.EstimatedTableRowsCount(table, opts)
}
} }
return client.query(sql) return client.query(sql)

View File

@ -301,7 +301,7 @@ func testTableRowsCount(t *testing.T) {
func testTableRowsCountWithLargeTable(t *testing.T) { func testTableRowsCountWithLargeTable(t *testing.T) {
var count int64 = 100010 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;`) testClient.db.MustExec(`VACUUM large_table;`)
res, err := testClient.TableRowsCount("large_table", RowsOptions{}) res, err := testClient.TableRowsCount("large_table", RowsOptions{})