Skip to content

Commit e5deeda

Browse files
authored
Support estimated count with multiple schemas (#22276)
The `EstimateCount` could be incorrect when the table lives in multiple schemas. Related to #19775.
1 parent cf07f24 commit e5deeda

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

models/db/context.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,10 @@ func EstimateCount(ctx context.Context, bean interface{}) (int64, error) {
188188
case schemas.MYSQL:
189189
_, err = e.Context(ctx).SQL("SELECT table_rows FROM information_schema.tables WHERE tables.table_name = ? AND tables.table_schema = ?;", tablename, x.Dialect().URI().DBName).Get(&rows)
190190
case schemas.POSTGRES:
191-
_, err = e.Context(ctx).SQL("SELECT reltuples AS estimate FROM pg_class WHERE relname = ?;", tablename).Get(&rows)
191+
// the table can live in multiple schemas of a postgres database
192+
// See https://wiki.postgresql.org/wiki/Count_estimate
193+
tablename = x.TableName(bean, true)
194+
_, err = e.Context(ctx).SQL("SELECT reltuples::bigint AS estimate FROM pg_class WHERE oid = ?::regclass;", tablename).Get(&rows)
192195
case schemas.MSSQL:
193196
_, err = e.Context(ctx).SQL("sp_spaceused ?;", tablename).Get(&rows)
194197
default:

0 commit comments

Comments
 (0)