#Requires -Version 5.1 <# .SYNOPSIS RasterizedDB Enterprise: add a customer to a server in strict tenant mode. Creates the database -Tenant with only its administrator -Owner in it, and records its limits in the tenant directory. Needs release 1.1.0 or later. .DESCRIPTION The operator's password comes from $env:PGPASSWORD and the administrator's from $env:RDB_TENANT_PASSWORD, never from the command line. .EXAMPLE $env:PGPASSWORD = ''; $env:RDB_TENANT_PASSWORD = '…' .\create-tenant.ps1 -Tenant acme -Owner acme_admin -Connections 50 -Storage 20GB -StatementTimeout 60s #> [CmdletBinding()] param( # The operator database. [string]$PgUrl = $(if ($env:RDB_PG_URL) { $env:RDB_PG_URL } else { 'postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require' }), [Parameter(Mandatory = $true)][string]$Tenant, [Parameter(Mandatory = $true)][string]$Owner, [int]$Connections = 0, # For example 20GB. [string]$Storage = '', # For example 60s. [string]$StatementTimeout = '' ) $ErrorActionPreference = 'Stop' if (-not (Get-Command psql -ErrorAction SilentlyContinue)) { throw 'psql is needed.' } if (-not $env:PGPASSWORD) { throw "Set `$env:PGPASSWORD to the operator's password." } if (-not $env:RDB_TENANT_PASSWORD) { throw "Set `$env:RDB_TENANT_PASSWORD to the administrator's password." } foreach ($v in @($Tenant, $Owner)) { if ($v -notmatch '^[A-Za-z_][A-Za-z0-9_]*$') { throw "${v}: use letters, digits and _ only." } } if (($env:RDB_TENANT_PASSWORD + $Storage + $StatementTimeout).Contains("'")) { throw 'Values may not contain a single quote.' } $limits = @() if ($Connections -gt 0) { $limits += "connections = $Connections" } if ($Storage) { $limits += "storage = '$Storage'" } if ($StatementTimeout) { $limits += "statement_timeout = '$StatementTimeout'" } $statement = "CREATE TENANT $Tenant OWNER $Owner PASSWORD '$($env:RDB_TENANT_PASSWORD)'" if ($limits) { $statement += " LIMITS ($($limits -join ', '))" } # On standard input, so the password does not appear in the process list. "$statement;" | & psql $PgUrl -v ON_ERROR_STOP=1 -X -q if ($LASTEXITCODE -ne 0) { throw 'CREATE TENANT failed; the error is above.' } & psql $PgUrl -X -c 'SHOW TENANTS' $hostPart = $PgUrl -replace '^[a-z]+://([^@/]*@)?([^/?]*).*$', '$2' Write-Host "The customer connects with: postgresql://$Owner@$hostPart/${Tenant}?sslmode=require"