Documentationcurrent version
Help us improve the docs by fixing typos and proposing enhancements.


Action "db.schema"

Create or modify a schema for the destination database.

A PostgreSQL database contains one or multiple schemas which in turns contains table, data types, functions, and operators.

Note, PostgreSQL default to the default root database while Nikita enforce the presence of the targeted database.

Create Schema example

const {$status} = await nikita.db.schema({
  admin_username: 'test',
  admin_password: 'test',
  database: 'my_database'
  schema: 'my_schema'
})`Schema created or modified: ${$status}`)

Schema definitions

definitions =
    type: 'object'
        $ref: 'module://@nikitajs/db/src/query#/definitions/config/properties/admin_username'
        $ref: 'module://@nikitajs/db/src/query#/definitions/config/properties/admin_password'
        type: 'string'
        description: '''
        The database name where the schema is created.
        $ref: 'module://@nikitajs/db/src/query#/definitions/config/properties/engine'
        $ref: 'module://@nikitajs/db/src/query#/definitions/config/properties/host'
        $ref: 'module://@nikitajs/db/src/query#/definitions/config/properties/port'
        type: 'string'
        description: '''
        The Schema owner. Alter Schema if schema already exists.
        type: 'string'
        description: '''
        New schema name.
    required: ['admin_username', 'admin_password', 'database', 'engine', 'host', 'schema']


handler = ({config}) ->
  {$status} = await @execute
    $shy: true
    code_skipped: 2
    command: command config, '\\dt'
  throw Error "Database does not exist #{config.database}" if !$status
  await @db.query config,
    command: "CREATE SCHEMA #{config.schema};"
    $unless_execute: command(config, "SELECT 1 FROM pg_namespace WHERE nspname = '#{config.schema}';") + " | grep 1"
  # Check if owner is the good one
  {stderr} = await @execute
    $if: config.owner?
    $unless_execute: command(config, '\\dn') + " | grep '#{config.schema}|#{config.owner}'"
    command: command config, "ALTER SCHEMA #{config.schema} OWNER TO #{config.owner};"
    code_skipped: 1
  throw Error "Owner #{config.owner} does not exists" if /^ERROR:\s\srole.*does\snot\sexist/.test stderr


module.exports =
  handler: handler
    global: 'db'
    definitions: definitions


{command} = require '../query'
Edit on GitHub

Nikita is an open source project hosted on GitHub and developed by Adaltas.