How to set schema in pg-promise

拟墨画扇 提交于 2019-12-12 18:44:59

问题


I was searching the documentation of pg-promise specifically in the creation of the client. But I wasn't able to find the option to set the default schema to be used in the connection, it always uses public schema. How do I set it?


回答1:


Normally, one sets the default schema(s) for the database or the role, as explained here:

  • Permanently Set Postgresql Schema Path

It is only if you want to do so without persisting the change, you might want to set the schema(s) dynamically, just for the current process.

The library supports option schema within Initialization Options:

const initOptions = {
    schema: 'my_schema' /* can also be an array of strings or a callback */
};

const pgp = require('pg-promise')(initOptions);

making it easier to set the dynamic schema(s).

Examples

  • Making your own schema visible along with the default public schema:

    const initOptions = {
        schema: ['public', 'my_schema'] /* make both schemas visible */
    };
    
    const pgp = require('pg-promise')(initOptions);
    
  • Using the callback to set schema based on the Database Context (see Database constructor):

    const initOptions = {
        schema(dc) {
            if(dc === /* whatever Database Context was used */) {
                return 'my_schema'; /* or an array of strings */
            }
            /* other provisions, if multiple databases are used. */
    
            /* can return null/undefined, if no schema change is needed. */
        }
    };
    
    const pgp = require('pg-promise')(initOptions);
    


来源:https://stackoverflow.com/questions/41730971/how-to-set-schema-in-pg-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!