Logging slow queries on Google Cloud SQL PostgreSQL instances

前端 未结 4 830
死守一世寂寞
死守一世寂寞 2021-02-13 10:40

The company I work for uses Google Cloud SQL to manage their SQL databases in production.

We\'re having performance issues and I thought it\'d be a good idea (among othe

4条回答
  •  时光取名叫无心
    2021-02-13 11:19

    There is a way to log slow queries through the pg_stat_statements extension which is supported by Cloud SQL.

    Since Cloud SQL doesn't grant superuser right to any of the users you need to use some workaround. First, you need to enable the extension with

    CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
    

    then you can check slow queries with a query like

    SELECT pd.datname,
           us.usename,
           pss.userid,
           pss.query                         AS SQLQuery,
           pss.rows                          AS TotalRowCount,
           (pss.total_time / 1000)           AS TotalSecond,
           ((pss.total_time / 1000) / calls) as TotalAverageSecond
    FROM pg_stat_statements AS pss
           INNER JOIN pg_database AS pd
                      ON pss.dbid = pd.oid
           INNER JOIN pg_user AS us
                      ON pss.userid = us.usesysid
    ORDER BY TotalAverageSecond DESC
    LIMIT 10;
    

    As postgres user you can have a look on all slow queries, but since the user is not superuser you will see on all other users' queries. To get around this limitation you can install the extension on other databases too (normally only postgres user has rigths to install extensions) and you can check the query texts with the owner of the db.

提交回复
热议问题