Fix the type of the 'masterid' case statement

It seems that newish versions of pg8000 complain (probably correctly)
that a case statement is of text type, but the masterid column should be
an integer.  This adds an explicit cast, which works fine across all
three database engines.

This is related to the pg8000 upgrade in bug 2933.