Вы находитесь на странице: 1из 130

Table of Contents

Azure DB for PostgreSQL Docs


Overview
Azure DB for PostgreSQL
Quickstarts
Create DB - Portal
Create DB - Azure CLI
Connect & query
Python
Node.js
Java
Ruby
PHP
.NET
Go
Tutorials
1 - Design a Database
Azure portal
Azure CLI
2 - Design Web App - Python
Samples
Azure CLI
Concepts
DB & Servers
Servers
Supported versions
PostgreSQL extensions
Server logs
High availability
Resources
Pricing tiers
Compute Units
Limits
Data access & security
Firewall rules
Configure SSL
Monitor
Development
Connection libraries
How-to guides
Firewall rules
Azure portal
Azure CLI
Restore a server
Azure portal
Azure CLI
Migrate your database
Dump & restore
Import & export
Configure server parameters
Azure portal
Azure CLI
Access server logs
Azure portal
Azure CLI
Monitor
Create alerts on metrics
Reference
Azure CLI
REST API
Resources
Deployment templates
Azure Roadmap
Pricing
MSDN forum
Stack Overflow
Videos
Feedback forum
Region availability
Support options
Customer stories
Database Migration Guide
What is Azure Database for PostgreSQL?
11/7/2017 • 3 min to read • Edit Online

Azure Database for PostgreSQL is a relational database service in the Microsoft cloud built for developers based on
the community version of open source PostgreSQL database engine. This service is in public preview. Azure
Database for PostgreSQL delivers:
Built-in high availability with no additional cost.
Predictable performance, using inclusive pay-as-you-go pricing.
Scale on the fly within seconds.
Secured to protect sensitive data at-rest and in-motion.
Automatic backups and point-in-time-restore for up to 35 days.
Enterprise-grade security and compliance.
All those capabilities require almost no administration, and all are provided at no additional cost. These capabilities
allow you to focus on rapid application development and accelerating your time to market, rather than allocating
precious time and resources to managing virtual machines and infrastructure. In addition, you can continue to
develop your application with the open source tools and platform of your choice, and deliver with the speed and
efficiency your business demands without having to learn new skills.
This article is an introduction to Azure Database for PostgreSQL core concepts and features related to
performance, scalability, and manageability. See these quickstarts to get you started:
Create an Azure Database for PostgreSQL using Azure portal
Create an Azure Database for PostgreSQL using the Azure CLI
For a set of Azure CLI samples, see:
Azure CLI samples for Azure Database for PostgreSQL

Adjust performance and scale within seconds


In preview, the Azure Database for PostgreSQL service offers two service tiers: Basic and Standard. Each tier offers
different performance and capabilities to support lightweight to heavyweight database workloads. You can build
your first app on a small database for a few dollars a month, and then adjust the scale to meet the needs of your
solution. Dynamic scalability enables your database to transparently respond to rapidly changing resource
requirements. You only pay for the resources you need, and only when you need them. See Pricing tiers for details.

Monitoring and alerting


How do you decide when to dial up and down? You use the built-in performance monitoring and alerting features,
combined with the performance ratings based on Compute Units. Using these tools, you can quickly assess the
impact of scaling Compute Units up or down based on your current or projected performance needs. See Alerts for
details.

Keep your app and business running


Azure's industry leading 99.99% availability (not available in preview) service level agreement (SLA), powered by a
global network of Microsoft-managed datacenters, helps keep your app running 24/7. With every Azure Database
for PostgreSQL server, you take advantage of built-in security, fault tolerance, and data protection that you would
otherwise have to buy or design, build, and manage. With Azure Database for PostgreSQL, each service tier offers a
comprehensive set of business continuity features and options that you can use to get up and running and stay
that way. You can use point-in-time restore to return a database to an earlier state, as far back as 35 days. In
addition, if the datacenter hosting your databases experiences an outage, you can restore databases from geo-
redundant copies of recent backups.

Secure your data


Azure database services have a tradition of data security that Azure Database for PostgreSQL upholds with
features that limit access, protect data at-rest and in-motion, and help you monitor activity. Visit the Azure Trust
Center for information about Azure's platform security.
The Azure Database for PostgreSQL service uses storage encryption for data at-rest. Data including backups are
encrypted on disk (with the exception of temporary files created by the engine while running queries). The service
uses AES 256-bit cipher that is included in Azure storage encryption, and the keys are system managed. Storage
encryption is always on and cannot be disabled.
By default, the Azure Database for PostgreSQL service is configured to require SSL connection security for data in-
motion across the network. Enforcing SSL connections between your database server and your client applications
helps protect against "man in the middle" attacks by encrypting the data stream between the server and your
application. Optionally, you can disable requiring SSL for connecting to your database service if your client
application does not support SSL connectivity.

Next steps
See the pricing page for cost comparisons and calculators.
Get started by creating your first Azure Database for PostgreSQL.
Build your first app in Python, PHP, Ruby, C#, Java, Node.js: Connection libraries
Create an Azure Database for PostgreSQL server in
the Azure portal
11/6/2017 • 11 min to read • Edit Online

Azure Database for PostgreSQL is a managed service that you use to run, manage, and scale highly available
PostgreSQL databases in the cloud. This Quickstart shows you how to create an Azure Database for PostgreSQL
server in about five minutes by using the Azure portal.
If you don't have an Azure subscription, create a free Azure account before you begin.

Sign in to the Azure portal


Open your web browser and go to the portal. Enter your credentials to sign in to the portal. The default view is
your service dashboard.

Create an Azure Database for PostgreSQL server


An Azure Database for PostgreSQL server is created with a defined set of compute and storage resources. The
server is created within an Azure resource group.
To create an Azure Database for PostgreSQL server, take the following steps:
1. Select the New button (+) in the upper-left corner of the portal.
2. Select Databases > Azure Database for PostgreSQL.

3. Fill out the new server details form with the following information, as shown in the preceding image:

SETTING SUGGESTED VALUE DESCRIPTION


SETTING SUGGESTED VALUE DESCRIPTION

Server name mypgserver-20170401 A unique name that identifies your


Azure Database for PostgreSQL
server. The domain name
postgres.database.azure.com is
appended to the server name you
provide. The server can contain only
lowercase letters, numbers, and the
hyphen (-) character. It must contain
at least 3 through 63 characters.

Subscription Your subscription The Azure subscription that you


want to use for your server. If you
have multiple subscriptions, choose
the subscription in which you're
billed for the resource.

Resource group myresourcegroup A new resource group name or an


existing one from your subscription.

Server admin login mylogin Your own login account to use when
you connect to the server. The
admin login name can't be
azure_superuser,
azure_pg_admin, admin,
administrator, root, guest, or
public. It can't start with pg_.

Password Your choice A new password for the server


admin account. It must contain from
8 to 128 characters. Your password
must contain characters from three
of the following categories: English
uppercase letters, English lowercase
letters, numbers (0 through 9), and
nonalphanumeric characters (!, $, #,
%, etc.).

Location The region closest to your users The location that's closest to your
users.

PostgreSQL version The latest version The latest version, unless you have
specific requirements.

Pricing tier Basic, 50 Compute Units, 50 GB The service tier and performance
level for your new database. Select
Pricing tier. Next, select the Basic
tab. Then select the left end of the
Compute Units slider to adjust the
value to the least amount available
for this Quickstart. To save the
pricing tier selection, select OK. For
more information, see the following
screenshot.

Pin to dashboard Check Enables easy tracking of your server


on the front dashboard page of your
portal.
IMPORTANT
The server admin login and password that you specify here are required to sign in to the server and its databases
later in this Quickstart. Remember or record this information for later use.

4. Select Create to provision the server. Provisioning can take up to 20 minutes.


5. On the toolbar, select the Notifications symbol to monitor the deployment process.

By default, a postgres database is created under your server. The postgres database is a default database
that's meant for use by users, utilities, and third-party applications.

Configure a server-level firewall rule


Azure Database for PostgreSQL creates a firewall at the server level. It prevents external applications and tools
from connecting to the server and any databases on the server, unless you create a rule to open the firewall for
specific IP addresses.
1. After the deployment finishes, locate your server. If needed, you can search for it. For example, on the
menu on the left, select All resources. Type your server name, such as the example, mypgserver-
20170401, to search for your newly created server. Select your server name from the search result list. The
Overview page for your server opens and provides options for further configuration.

2. On the server page, select Connection security.

3. Under the Firewall rules heading, in the Rule Name column, select the blank text box to begin creating
the firewall rule.
For this Quickstart, let's allow all IP addresses into the server. Fill in the text box in each column with the
following values:

RULE NAME START IP END IP

AllowAllIps 0.0.0.0 255.255.255.255

4. On the upper toolbar of the Connection security page, select Save. Wait until the notification appears
stating that the connection security update has finished successfully before you continue.

NOTE
Connections to your Azure Database for PostgreSQL server communicate over port 5432. If you try to connect
from within a corporate network, outbound traffic over port 5432 might not be allowed by your network's firewall.
If so, you can't connect to your server unless your IT department opens port 5432.

Get the connection information


When you create your Azure Database for PostgreSQL server, a default database named postgres is created. To
connect to your database server, you need your full server name and admin login credentials. You might have
noted those values earlier in the Quickstart article. If you didn't, you can easily find the server name and login
information on the server Overview page in the portal.
Open your server's Overview page. Make a note of the Server name and the Server admin login name. Hover
your cursor over each field, and the copy symbol appears to the right of the text. Select the copy symbol as
needed to copy the values.

Connect to the PostgreSQL Database by using psql in Cloud Shell


There are a number of applications you can use to connect to your Azure Database for PostgreSQL server. Let's
first use the psql command-line utility to illustrate how to connect to the server. You can use a web browser and
Azure Cloud Shell as described here without the need to install any additional software. If you have the psql
utility installed locally on your own machine, you can connect from there as well.
1. In the top navigation pane, select the terminal symbol to open Cloud Shell.

2. Cloud Shell opens in your browser, where you can type Bash shell commands.

3. At the Cloud Shell prompt, connect to a database in your Azure Database for PostgreSQL server by typing
the psql command line.
To connect to an Azure Database for PostgreSQL server with the psql utility, use the following format:

psql --host=<yourserver> --port=<port> --username=<server admin login> --dbname=<database name>

For example, the following command connects to an example server:

psql --host=mypgserver-20170401.postgres.database.azure.com --port=5432 --username=mylogin@mypgserver-


20170401 --dbname=postgres
PSQL PARAMETER SUGGESTED VALUE DESCRIPTION

--host Server name The server name value that you used
when you created the Azure
Database for PostgreSQL server
earlier. The example server shown is
mypgserver-
20170401.postgres.database.azur
e.com. Use the fully qualified
domain name
(*.postgres.database.azure.com)
as shown in the example. If you
don't remember your server name,
follow the steps in the previous
section to get the connection
information.

--port 5432 The port to use when you connect


to the Azure Database for
PostgreSQL server.

--username Server admin login name The server admin login username
that you supplied when you created
the Azure Database for PostgreSQL
server earlier. If you don't remember
your username, follow the steps in
the previous section to get the
connection information. The format
is username@servername.

--dbname postgres The default, system-generated


database name that was created for
the first connection. Later, you
create your own database.

After you run the psql command with your own parameter values, you're prompted to enter the server
admin password. This password is the same one that you provided when you created the server.

PSQL PARAMETER SUGGESTED VALUE DESCRIPTION

password Your admin password The typed password characters


aren't shown on the bash prompt.
After you type all the characters,
select the Enter key to authenticate
and connect.

After you connect, the psql utility displays a postgres prompt where you type sql commands. In the initial
connection output, a warning might appear because the psql in Cloud Shell might be a different version
than the Azure Database for PostgreSQL server version.
Example psql output:

psql (9.5.7, server 9.6.2)


WARNING: psql major version 9.5, server major version 9.6.
Some psql features might not work.
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=>
TIP
If the firewall is not configured to allow the IP address of Cloud Shell, the following error occurs:
"psql: FATAL: no pg_hba.conf entry for host "138.91.195.82", user "mylogin", database "postgres", SSL on FATAL:
SSL connection is required. Specify SSL options and retry.
To resolve the error, make sure the server configuration matches the steps in the "Configure a server-level firewall
rule" section of this article.

4. Create a blank database at the prompt by typing the following command:

CREATE DATABASE mypgsqldb;

The command might take a few minutes to finish.


5. At the prompt, execute the following command to switch connections to the newly created database
mypgsqldb:

\c mypgsqldb

6. Type \q , and then select the Enter key to quit psql. You can close Cloud Shell after you're finished.

Now you're connected to the Azure Database for PostgreSQL server, and you created a blank user database.
Continue to the next section to connect by using another common tool, pgAdmin.

Connect to the PostgreSQL Database by using pgAdmin


To connect to the Azure PostgreSQL server by using the GUI tool pgAdmin:
1. Open the pgAdmin application on your client computer. You can install pgAdmin from the pgAdmin
website.
2. On the dashboard page, under the Quick Links section, select the Add New Server symbol.
3. In the Create - Server dialog box, on the General tab, enter a unique friendly name for the server, such as
Azure PostgreSQL Server.
4. In the Create - Server dialog box, on the Connection tab, use the settings as specified, and then select
Save.

PGADMIN PARAMETER SUGGESTED VALUE DESCRIPTION


PGADMIN PARAMETER SUGGESTED VALUE DESCRIPTION

Host Name/Address Server name The server name value that you used
when you created the Azure
Database for PostgreSQL server
earlier. Our example server is
mypgserver-
20170401.postgres.database.azur
e.com. Use the fully qualified
domain name
(*.postgres.database.azure.com)
as shown in the example. If you
don't remember your server name,
follow the steps in the previous
section to get the connection
information.

Port 5432 The port to use when you connect


to the Azure Database for
PostgreSQL server.

Maintenance database postgres The default system-generated


database name.

Username Server admin login name The server admin login username
that you supplied when you created
the Azure Database for PostgreSQL
server earlier. If you don't remember
the username, follow the steps in the
previous section to get the
connection information. The format
is username@servername.

Password Your admin password The password you chose when you
created the server earlier in this
Quickstart.

Role Leave blank There's no need to provide a role


name at this point. Leave the field
blank.

SSL mode Required By default, all Azure PostgreSQL


servers are created with SSL
enforcing turned on. To turn off SSL
enforcing, see Enforce SSL.

5. Select Save.
6. In the Browser pane on the left, expand the Servers node. Select your server, for example, Azure
PostgreSQL Server. Click to connect to it.
7. Expand the server node, and then expand Databases under it. The list should include your existing
postgres database and any newly created user database, such as mypgsqldb, which was created in the
previous section. Notice that you can create multiple databases per server with Azure Database for
PostgreSQL.
8. Right-click Databases, choose the Create menu, and then select Database.
9. Type a database name of your choice in the Database field, such as mypgsqldb, as shown in the
example.
10. Select the Owner for the database from the list box. Choose your server admin login name, such as the
example, mylogin.
11. Select Save to create a new blank database.
12. In the Browser pane, see the database that you created in the list of databases under your server name.

Clean up resources
You can clean up the resources that you created in the Quickstart in one of two ways. You can delete the Azure
resource group, which includes all the resources in the resource group. If you want to keep the other resources
intact, delete only the single server resource.

TIP
Other Quickstarts in this collection build on this Quickstart. If you plan to continue working with Quickstarts, don't clean
up the resources that you created in this Quickstart. If you don't plan to continue, follow these steps to delete the
resources that were created by this Quickstart in the portal.

To delete the entire resource group, including the newly created server:
1. Locate your resource group in the portal. On the menu on the left, select Resource groups. Then select
the name of your resource group, such as the example, myresourcegroup.
2. On your resource group page, select Delete. Type the name of your resource group, such as the example,
myresourcegroup, in the text box to confirm deletion. Select Delete.
To delete only the newly created server:
1. Locate your server in the portal, if you don't have it open. On the menu on the left, select All resources.
Then search for the server you created.
2. On the Overview page, select Delete.
3. Confirm the server name you want to delete, and view the databases under it that are affected. Type your
server name in the text box, such as the example, mypgserver-20170401. Select Delete.

Next steps
Migrate your database using Export and Import
Create an Azure Database for PostgreSQL using the
Azure CLI
12/7/2017 • 5 min to read • Edit Online

Azure Database for PostgreSQL is a managed service that enables you to run, manage, and scale highly available
PostgreSQL databases in the cloud. The Azure CLI is used to create and manage Azure resources from the
command line or in scripts. This quickstart shows you how to create an Azure Database for PostgreSQL server in
an Azure resource group using the Azure CLI.
If you don't have an Azure subscription, create a free account before you begin.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account. Just click the Copy to copy the code, paste it
into the Cloud Shell, and then press enter to run it. There are two ways to launch the Cloud Shell:

Click Try It in the upper right corner of a code block.

Click the Cloud Shell button on the menu in the upper right
of the Azure portal.

If you choose to install and use the CLI locally, this article requires that you are running the Azure CLI version 2.0
or later. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI 2.0.
If you are running the CLI locally, you need to log in to your account using the az login command.

az login

If you have multiple subscriptions, choose the appropriate subscription in which the resource should be billed.
Select a specific subscription ID under your account using az account set command.

az account set --subscription 00000000-0000-0000-0000-000000000000

Create a resource group


Create an Azure resource group using the az group create command. A resource group is a logical container into
which Azure resources are deployed and managed as a group. The following example creates a resource group
named myresourcegroup in the westus location.

az group create --name myresourcegroup --location westus

Create an Azure Database for PostgreSQL server


Create an Azure Database for PostgreSQL server using the az postgres server create command. A server contains
a group of databases managed as a group.
The following example creates a server named mypgserver-20170401 in your resource group myresourcegroup
with server admin login mylogin . The name of a server maps to DNS name and is thus required to be globally
unique in Azure. Substitute the <server_admin_password> with your own value.

az postgres server create --resource-group myresourcegroup --name mypgserver-20170401 --location westus --


admin-user mylogin --admin-password <server_admin_password> --performance-tier Basic --compute-units 50 --
version 9.6

IMPORTANT
The server admin login and password that you specify here are required to log in to the server and its databases later in
this quick start. Remember or record this information for later use.

By default, postgres database gets created under your server. The postgres database is a default database meant
for use by users, utilities, and third-party applications.

Configure a server-level firewall rule


Create an Azure PostgreSQL server-level firewall rule with the az postgres server firewall-rule create command. A
server-level firewall rule allows an external application, such as psql or PgAdmin to connect to your server
through the Azure PostgreSQL service firewall.
You can set a firewall rule that covers an IP range to be able to connect from your network. The following example
uses az postgres server firewall-rule create to create a firewall rule AllowAllIps for an IP address range. To open
all IP addresses, use 0.0.0.0 as the starting IP address and 255.255.255.255 as the ending address.

az postgres server firewall-rule create --resource-group myresourcegroup --server mypgserver-20170401 --name


AllowAllIps --start-ip-address 0.0.0.0 --end-ip-address 255.255.255.255

NOTE
Azure PostgreSQL server communicates over port 5432. When connecting from within a corporate network, outbound
traffic over port 5432 may not be allowed by your network's firewall. Have your IT department open port 5432 to connect
to your Azure SQL Database server.

Get the connection information


To connect to your server, you need to provide host information and access credentials.

az postgres server show --resource-group myresourcegroup --name mypgserver-20170401

The result is in JSON format. Make a note of the administratorLogin and fullyQualifiedDomainName.
{
"administratorLogin": "mylogin",
"fullyQualifiedDomainName": "mypgserver-20170401.postgres.database.azure.com",
"id": "/subscriptions/00000000-0000-0000-0000-
000000000000/resourceGroups/myresourcegroup/providers/Microsoft.DBforPostgreSQL/servers/mypgserver-20170401",
"location": "westus",
"name": "mypgserver-20170401",
"resourceGroup": "myresourcegroup",
"sku": {
"capacity": 50,
"family": null,
"name": "PGSQLS2M50",
"size": null,
"tier": "Basic"
},
"sslEnforcement": null,
"storageMb": 51200,
"tags": null,
"type": "Microsoft.DBforPostgreSQL/servers",
"userVisibleState": "Ready",
"version": "9.6"
}

Connect to PostgreSQL database using psql


If your client computer has PostgreSQL installed, you can use a local instance of psql to connect to an Azure
PostgreSQL server. Let's now use the psql command-line utility to connect to the Azure PostgreSQL server.
1. Run the following psql command to connect to an Azure Database for PostgreSQL server

psql --host=<servername> --port=<port> --username=<user@servername> --dbname=<dbname>

For example, the following command connects to the default database called postgres on your
PostgreSQL server mypgserver-20170401.postgres.database.azure.com using access credentials. Enter
the <server_admin_password> you chose when prompted for password.

psql --host=mypgserver-20170401.postgres.database.azure.com --port=5432 --username=mylogin@mypgserver-


20170401 --dbname=postgres

2. Once you are connected to the server, create a blank database at the prompt.

CREATE DATABASE mypgsqldb;

3. At the prompt, execute the following command to switch connection to the newly created database
mypgsqldb:

\c mypgsqldb

Connect to PostgreSQL database using pgAdmin


To connect to Azure PostgreSQL server using the GUI tool pgAdmin
1. Launch the pgAdmin application on your client computer. You can install pgAdmin from
http://www.pgadmin.org/.
2. Choose Add New Server from the Quick Links menu.
3. In the Create - Server dialog box General tab, enter a unique friendly Name for the server. Say Azure
PostgreSQL Server.

4. In the Create - Server dialog box, Connection tab:


Enter the fully qualified server name (for example, mypgserver-
20170401.postgres.database.azure.com) in the Host Name/ Address box.
Enter port 5432 into the Port box.
Enter the Server admin login (user@mypgserver) obtained earlier in this quickstart and password
you entered when you created the server into the Username and Password boxes, respectively.
Select SSL Mode as Require. By default, all Azure PostgreSQL servers are created with SSL enforcing
turned ON. To turn OFF SSL enforcing, see details in Enforcing SSL.
5. Click Save.
6. In the Browser left pane, expand the Server Groups. Choose your server Azure PostgreSQL Server.
7. Choose the Server you connected to, and then choose Databases under it.
8. Right-click on Databases to Create a Database.
9. Choose a database name mypgsqldb and the owner for it as server admin login mylogin.
10. Click Save to create a blank database.
11. In the Browser, expand the Servers group. Expand the server you created, and see the database mypgsqldb
under it.

Clean up resources
Clean up all resources you created in the quickstart by deleting the Azure resource group.
TIP
Other quickstarts in this collection build upon this quickstart. If you plan to continue to work with subsequent quickstarts,
do not clean up the resources created in this quickstart. If you do not plan to continue, use the following steps to delete all
resources created by this quickstart in the Azure CLI.

az group delete --name myresourcegroup

If you would just like to delete the one newly created server, you can run az postgres server delete command.

az postgres server delete --resource-group myresourcegroup --name mypgserver-20170401

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Python to
connect and query data
11/6/2017 • 5 min to read • Edit Online

This quickstart demonstrates how to use Python to connect to an Azure Database for PostgreSQL. It also
demonstrates how to use SQL statements to query, insert, update, and delete data in the database from macOS,
Ubuntu Linux, and Windows platforms. The steps in this article assume that you are familiar with developing using
Python and are new to working with Azure Database for PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - CLI
You also need:
python installed
pip package installed (pip is already installed if you're working with Python 2 >=2.7.9 or Python 3 >=3.4
binaries downloaded from python.org.

Install the Python connection libraries for PostgreSQL


Install the psycopg2 package, which enables you to connect and query the database. psycopg2 is available on PyPI
in the form of wheel packages for the most common platforms (Linux, OSX, Windows). Use pip install to get the
binary version of the module including all the dependencies.
1. On your own computer, launch a command-line interface:
On Linux, launch the Bash shell.
On macOS, launch the Terminal.
On Windows, launch the Command Prompt from the Start Menu.
2. Ensure that you are using the most current version of pip by running a command such as:

pip install -U pip

3. Run the following command to install the psycopg2 package:

pip install psycopg2

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources and search for mypgserver-20170401 (the server
you created).
3. Click the server name mypgserver-20170401.
4. Select the server's Overview page, and then make a note of the Server name and Server admin login name.

5. If you forget your server login information, navigate to the Overview page to view the Server admin login
name and, if necessary, reset the password.

How to run Python code


This article contains a total of four code samples, each of which performs a specific function. The following
instructions indicate how to create a text file, insert a code block, and then save the file so that you can run it later.
Be sure to create four separate files, one for each code block.
Using your favorite text editor, create a new file.
Copy and paste one of the code samples in the following sections into the text file. Replace the host, dbname,
user, and password parameters with the values that you specified when you created the server and database.
Save the file with the .py extension (for example postgres.py) into your project folder. If you are running on
Windows, be sure to select UTF-8 encoding when saving the file.
Launch the Command Prompt, Terminal, or Bash shell and then change the directory to your project folder, for
example cd postgres .
To run the code, type the Python command followed by the file name, for example Python postgres.py .

NOTE
Starting in Python version 3, you may see the error SyntaxError: Missing parentheses in call to 'print' when
running the following code blocks: If that happens, replace each call to the command print "string" with a function call
using parenthesis, such as print("string") .

Connect, create table, and insert data


Use the following code to connect and load the data using psycopg2.connect function with INSERT SQL statement.
The cursor.execute function is used to execute the SQL query against PostgreSQL database. Replace the host,
dbname, user, and password parameters with the values that you specified when you created the server and
database.
import psycopg2

# Update connection string information obtained from the portal


host = "mypgserver-20170401.postgres.database.azure.com"
user = "mylogin@mypgserver-20170401"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Drop previous table of same name if one exists


cursor.execute("DROP TABLE IF EXISTS inventory;")
print "Finished dropping table (if existed)"

# Create table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print "Finished creating table"

# Insert some data into table


cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
print "Inserted 3 rows of data"

# Cleanup
conn.commit()
cursor.close()
conn.close()

After the code runs successfully, the output appears as follows:

Read data
Use the following code to read the data inserted using cursor.execute function with SELECT SQL statement. This
function accepts a query and returns a result set that can be iterated over with the use of cursor.fetchall(). Replace
the host, dbname, user, and password parameters with the values that you specified when you created the server
and database.
import psycopg2

# Update connection string information obtained from the portal


host = "mypgserver-20170401.postgres.database.azure.com"
user = "mylogin@mypgserver-20170401"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Fetch all rows from table


cursor.execute("SELECT * FROM inventory;")
rows = cursor.fetchall()

# Print all rows


for row in rows:
print "Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2]))

# Cleanup
conn.commit()
cursor.close()
conn.close()

Update data
Use the following code to update the inventory row that you previously inserted using cursor.execute function with
UPDATE SQL statement. Replace the host, dbname, user, and password parameters with the values that you
specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal


host = "mypgserver-20170401.postgres.database.azure.com"
user = "mylogin@mypgserver-20170401"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Update a data row in the table


cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
print "Updated 1 row of data"

# Cleanup
conn.commit()
cursor.close()
conn.close()
Delete data
Use the following code to delete an inventory item that you previously inserted using cursor.execute function with
DELETE SQL statement. Replace the host, dbname, user, and password parameters with the values that you
specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal


host = "mypgserver-20170401.postgres.database.azure.com"
user = "mylogin@mypgserver-20170401"
dbname = "mypgsqldb"
password = "<server_admin_password>"
sslmode = "require"

# Construct connection string


conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password,
sslmode)
conn = psycopg2.connect(conn_string)
print "Connection established"

cursor = conn.cursor()

# Delete data row from table


cursor.execute("DELETE FROM inventory WHERE name = %s;", ("orange",))
print "Deleted 1 row of data"

# Cleanup
conn.commit()
cursor.close()
conn.close()

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Node.js to
connect and query data
11/6/2017 • 4 min to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Node.js application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using Node.js, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - CLI
You also need to:
Install Node.js

Install pg client
Install pg, which is a PostgreSQL client for Node.js.
To do so, run the node package manager (npm) for JavaScript from your command line to install the pg client.

npm install pg

Verify the installation by listing the packages installed.

npm list

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources and search for the server you created.
3. Click the server name.
4. Select the server's Overview page. Make a note of the Server name and Server admin login name.
5. If you forget your server login information, navigate to the Overview page to view the Server admin login
name and, if necessary, reset the password.

Running the JavaScript code in Node.js


You may launch Node.js from the Bash shell, Terminal, or Windows Command Prompt by typing node , then run
the example JavaScript code interactively by copy and pasting it onto the prompt. Alternatively, you may save the
JavaScript code into a text file and launch node filename.js with the file name as a parameter to run it.

Connect, create table, and insert data


Use the following code to connect and load the data using CREATE TABLE and INSERT INTO SQL statements. The
pg.Client object is used to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish
the connection to the server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL
database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.

const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) throw err;
else {
queryDatabase();
}
});

function queryDatabase() {
const query = `
DROP TABLE IF EXISTS inventory;
CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);
INSERT INTO inventory (name, quantity) VALUES ('banana', 150);
INSERT INTO inventory (name, quantity) VALUES ('orange', 154);
INSERT INTO inventory (name, quantity) VALUES ('apple', 100);
`;

client
.query(query)
.then(() => {
console.log('Table created successfully!');
client.end(console.log('Closed client connection'));
})
.catch(err => console.log(err))
.then(() => {
console.log('Finished execution, exiting now');
process.exit();
});
}
Read data
Use the following code to connect and read the data using a SELECT SQL statement. The pg.Client object is used to
interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the
server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.

const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) throw err;
else { queryDatabase(); }
});

function queryDatabase() {

console.log(`Running query to PostgreSQL server: ${config.host}`);

const query = 'SELECT * FROM inventory;';

client.query(query)
.then(res => {
const rows = res.rows;

rows.map(row => {
console.log(`Read: ${JSON.stringify(row)}`);
});

process.exit();
})
.catch(err => {
console.log(err);
});
}

Update data
Use the following code to connect and read the data using a UPDATE SQL statement. The pg.Client object is used
to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the
server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.
const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) throw err;
else {
queryDatabase();
}
});

function queryDatabase() {
const query = `
UPDATE inventory
SET quantity= 1000 WHERE name='banana';
`;

client
.query(query)
.then(result => {
console.log('Update completed');
console.log(`Rows affected: ${result.rowCount}`);
})
.catch(err => {
console.log(err);
throw err;
});
}

Delete data
Use the following code to connect and read the data using a DELETE SQL statement. The pg.Client object is used to
interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the
server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.
Replace the host, dbname, user, and password parameters with the values that you specified when you created the
server and database.
const pg = require('pg');

const config = {
host: '<your-db-server-name>.postgres.database.azure.com',
// Do not hard code your username and password.
// Consider using Node environment variables.
user: '<your-db-username>',
password: '<your-password>',
database: '<name-of-database>',
port: 5432,
ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
if (err) {
throw err;
} else {
queryDatabase();
}
});

function queryDatabase() {
const query = `
DELETE FROM inventory
WHERE name = 'apple';
`;

client
.query(query)
.then(result => {
console.log('Delete completed');
console.log(`Rows affected: ${result.rowCount}`);
})
.catch(err => {
console.log(err);
throw err;
});
}

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Java to connect
and query data
11/6/2017 • 7 min to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Java application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using Java, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI
You also need to:
Download the PostgreSQL JDBC Driver matching your version of Java and the Java Development Kit.
Include the PostgreSQL JDBC jar file (for example postgresql-42.1.1.jar) in your application classpath. For more
information, see classpath details.

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources and search for the server you have created, such as
mypgserver-20170401.
3. Click the server name mypgserver-20170401.
4. Select the server's Overview page. Make a note of the Server name and Server admin login name.

5. If you forget your server login information, navigate to the Overview page to view the Server admin login
name and, if necessary, reset the password.

Connect, create table, and insert data


Use the following code to connect and load the data into the database using the function with an INSERT SQL
statement. The methods getConnection(), createStatement(), and executeQuery() are used to connect to the
database, drop, and create the table. The prepareStatement object is used to build the insert commands, with
setString() and setInt() to bind the parameter values. Method executeUpdate() runs the command for each set of
parameters.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.util.Properties;

public class CreateTableInsertRows {

public static void main (String[] args) throws Exception


{

// Initialize connection variables.


String host = "mypgserver-20170401.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mypgserver-20170401";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
{
// Drop previous table of same name if one exists.
Statement statement = connection.createStatement();
statement.execute("DROP TABLE IF EXISTS inventory;");
System.out.println("Finished dropping table (if existed).");

// Create table.
statement.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity
INTEGER);");
System.out.println("Created table.");
// Insert some data into table.
int nRowsInserted = 0;
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO inventory (name,
quantity) VALUES (?, ?);");
preparedStatement.setString(1, "banana");
preparedStatement.setInt(2, 150);
nRowsInserted += preparedStatement.executeUpdate();

preparedStatement.setString(1, "orange");
preparedStatement.setInt(2, 154);
nRowsInserted += preparedStatement.executeUpdate();

preparedStatement.setString(1, "apple");
preparedStatement.setInt(2, 100);
nRowsInserted += preparedStatement.executeUpdate();
System.out.println(String.format("Inserted %d row(s) of data.", nRowsInserted));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.

}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}

Read data
Use the following code to read the data with a SELECT SQL statement. The methods getConnection(),
createStatement(), and executeQuery() are used to connect to the database, create, and run the select statement.
The results are processed using a ResultSet object.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.util.Properties;

public class ReadTable {

public static void main (String[] args) throws Exception


{

// Initialize connection variables.


String host = "mypgserver-20170401.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mypgserver-20170401";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}
System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
{

Statement statement = connection.createStatement();


ResultSet results = statement.executeQuery("SELECT * from inventory;");
while (results.next())
{
String outputString =
String.format(
"Data row = (%s, %s, %s)",
results.getString(1),
results.getString(2),
results.getString(3));
System.out.println(outputString);
}
}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}

Update data
Use the following code to change the data with an UPDATE SQL statement. The methods getConnection(),
prepareStatement(), and executeUpdate() are used to connect to the database, prepare, and run the update
statement.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.sql.*;
import java.util.Properties;

public class UpdateTable {


public static void main (String[] args) throws Exception
{

// Initialize connection variables.


String host = "mypgserver-20170401.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mypgserver-20170401";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
{
// Modify some data in table.
int nRowsUpdated = 0;
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE inventory SET
quantity = ? WHERE name = ?;");
preparedStatement.setInt(1, 200);
preparedStatement.setString(2, "banana");
nRowsUpdated += preparedStatement.executeUpdate();
System.out.println(String.format("Updated %d row(s) of data.", nRowsUpdated));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.


}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}

Delete data
Use the following code to remove data with a DELETE SQL statement. The methods getConnection(),
prepareStatement(), and executeUpdate() are used to connect to the database, prepare, and run the delete
statement.
Replace the host, database, user, and password parameters with the values that you specified when you created
your own server and database.

import java.sql.*;
import java.util.Properties;

public class DeleteTable {


public static void main (String[] args) throws Exception
{

// Initialize connection variables.


String host = "mypgserver-20170401.postgres.database.azure.com";
String database = "mypgsqldb";
String user = "mylogin@mypgserver-20170401";
String password = "<server_admin_password>";

// check that the driver is installed


try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);
}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object


try
{
String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties


Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("ssl", "true");

// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection.


try
try
{
// Delete some data from table.
int nRowsDeleted = 0;
PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM inventory WHERE
name = ?;");
preparedStatement.setString(1, "orange");
nRowsDeleted += preparedStatement.executeUpdate();
System.out.println(String.format("Deleted %d row(s) of data.", nRowsDeleted));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.


}
catch (SQLException e)
{
throw new SQLException("Encountered an error when executing given sql statement.", e);
}
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
}

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Ruby to connect
and query data
11/6/2017 • 6 min to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Ruby application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using Ruby, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI

Install Ruby
Install Ruby on your own machine.
Windows
Download and Install the latest version of Ruby.
On the finish screen of the MSI installer, check the box that says "Run 'ridk install' to install MSYS2 and
development toolchain." Then click Finish to launch the next installer.
The RubyInstaller2 for Windows installer launches. Type 2 to install the MSYS2 repository update. After it
finishes and returns to the installation prompt, close the command window.
Launch a new command prompt (cmd) from the Start menu.
Test the Ruby installation ruby -v to see the version installed.
Test the Gem installation gem -v to see the version installed.
Build the PostgreSQL module for Ruby using Gem by running the command gem install pg .
MacOS
Install Ruby using Homebrew by running the command brew install ruby . For more installation options, see
the Ruby installation documentation
Test the Ruby installation ruby -v to see the version installed.
Test the Gem installation gem -v to see the version installed.
Build the PostgreSQL module for Ruby using Gem by running the command gem install pg .
Linux (Ubuntu)
Install Ruby by running the command sudo apt-get install ruby-full . For more installation options, see the
Ruby installation documentation.
Test the Ruby installation ruby -v to see the version installed.
Install the latest updates for Gem by running the command sudo gem update --system .
Test the Gem installation gem -v to see the version installed.
Install the gcc, make, and other build tools by running the command sudo apt-get install build-essential .
Install the PostgreSQL libraries by running the command sudo apt-get install libpq-dev .
Build the Ruby pg module using Gem by running the command sudo gem install pg .
Run Ruby code
Save the code into a text file with file extension .rb, and save the file into a project folder, such as
C:\rubypostgres\read.rb or /home/username/rubypostgres/read.rb
To run the code, launch the command prompt or bash shell. Change directory into your project folder
cd rubypostgres , then type the command ruby read.rb to run the application.

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources and search for the server you have created, such as
mypgserver-20170401.
3. Click the server name mypgserver-20170401.
4. Select the server's Overview page. Make a note of the Server name and Server admin login name.

5. If you forget your server login information, navigate to the Overview page to view the Server admin login
name. If necessary, reset the password.

Connect and create a table


Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT
INTO SQL statements to add rows into the table.
The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it
calls method exec() to run the DROP, CREATE TABLE, and INSERT INTO commands. The code checks for errors
using the PG::Error class. Then it calls method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.
require 'pg'

begin
# Initialize connection variables.
host = String('mypgserver-20170401.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mypgserver-20170401')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432',
:password => password)
puts 'Successfully created connection to database'

# Drop previous table of same name if one exists


connection.exec('DROP TABLE IF EXISTS inventory;')
puts 'Finished dropping table (if existed).'

# Drop previous table of same name if one exists.


connection.exec('CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);')
puts 'Finished creating table.'

# Insert some data into table.


connection.exec("INSERT INTO inventory VALUES(1, 'banana', 150)")
connection.exec("INSERT INTO inventory VALUES(2, 'orange', 154)")
connection.exec("INSERT INTO inventory VALUES(3, 'apple', 100)")
puts 'Inserted 3 rows of data.'

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end

Read data
Use the following code to connect and read the data using a SELECT SQL statement.
The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it
calls method exec() to run the SELECT command, keeping the results in a result set. The result set collection is
iterated over using the resultSet.each do loop, keeping the current row values in the row variable. The code
checks for errors using the PG::Error class. Then it calls method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.
require 'pg'

begin
# Initialize connection variables.
host = String('mypgserver-20170401.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mypgserver-20170401')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :database => dbname, :port => '5432',
:password => password)
puts 'Successfully created connection to database.'

resultSet = connection.exec('SELECT * from inventory;')


resultSet.each do |row|
puts 'Data row = (%s, %s, %s)' % [row['id'], row['name'], row['quantity']]
end

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end

Update data
Use the following code to connect and update the data using a UPDATE SQL statement.
The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it
calls method exec() to run the UPDATE command. The code checks for errors using the PG::Error class. Then it calls
method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.

require 'pg'

begin
# Initialize connection variables.
host = String('mypgserver-20170401.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mypgserver-20170401')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432',
:password => password)
puts 'Successfully created connection to database.'

# Modify some data in table.


connection.exec('UPDATE inventory SET quantity = %d WHERE name = %s;' % [200, '\'banana\''])
puts 'Updated 1 row of data.'

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end
Delete data
Use the following code to connect and read the data using a DELETE SQL statement.
The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it
calls method exec() to run the UPDATE command. The code checks for errors using the PG::Error class. Then it calls
method close() to close the connection before terminating.
Replace the host , database , user , and password strings with your own values.

require 'pg'

begin
# Initialize connection variables.
host = String('mypgserver-20170401.postgres.database.azure.com')
database = String('postgres')
user = String('mylogin@mypgserver-20170401')
password = String('<server_admin_password>')

# Initialize connection object.


connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432',
:password => password)
puts 'Successfully created connection to database.'

# Modify some data in table.


connection.exec('DELETE FROM inventory WHERE name = %s;' % ['\'orange\''])
puts 'Deleted 1 row of data.'

rescue PG::Error => e


puts e.message

ensure
connection.close if connection
end

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use PHP to connect
and query data
11/6/2017 • 6 min to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a PHP application. It
shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article
assume that you are familiar with developing using PHP, and are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI

Install PHP
Install PHP on your own server, or create an Azure web app that includes PHP.
Windows
Download PHP 7.1.4 non-thread safe (x64) version
Install PHP and refer to the PHP manual for further configuration
The code uses the pgsql class (ext/php_pgsql.dll) that is included in the PHP installation.
Enabled the pgsql extension by editing the php.ini configuration file, typically located at
C:\Program Files\PHP\v7.1\php.ini . The configuration file should contain a line with the text
extension=php_pgsql.so . If it is not shown, add the text and save the file. If the text is present, but commented
with a semicolon prefix, uncomment the text by removing the semicolon.
Linux (Ubuntu)
Download PHP 7.1.4 non-thread safe (x64) version
Install PHP and refer to the PHP manual for further configuration
The code uses the pgsql class (php_pgsql.so). Install it by running sudo apt-get install php-pgsql .
Enabled the pgsql extension by editing the /etc/php/7.0/mods-available/pgsql.ini configuration file. The
configuration file should contain a line with the text extension=php_pgsql.so . If it is not shown, add the text and
save the file. If the text is present, but commented with a semicolon prefix, uncomment the text by removing the
semicolon.
MacOS
Download PHP 7.1.4 version
Install PHP and refer to the PHP manual for further configuration

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources and search for the server you have created, such as
mypgserver-20170401.
3. Click the server name mypgserver-20170401.
4. Select the server's Overview page. Make a note of the Server name and Server admin login name.

5. If you forget your server login information, navigate to the Overview page to view the Server admin login
name and, if necessary, reset the password.

Connect and create a table


Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT
INTO SQL statements to add rows into the table.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
several times to run several commands, and pg_last_error() to check the details if an error occurred each time. Then
it calls method pg_close() to close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.
<?php
// Initialize connection variables.
$host = "mypgserver-20170401.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mypgserver-20170401";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). "<br/>");
print "Successfully created connection to database.<br/>";

// Drop previous table of same name if one exists.


$query = "DROP TABLE IF EXISTS inventory;";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");
print "Finished dropping table (if existed).<br/>";

// Create table.
$query = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");
print "Finished creating table.<br/>";

// Insert some data into table.


$name = '\'banana\'';
$quantity = 150;
$query = "INSERT INTO inventory (name, quantity) VALUES ($1, $2);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");

$name = '\'orange\'';
$quantity = 154;
$query = "INSERT INTO inventory (name, quantity) VALUES ($name, $quantity);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");

$name = '\'apple\'';
$quantity = 100;
$query = "INSERT INTO inventory (name, quantity) VALUES ($name, $quantity);";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error()). "<br/>";

print "Inserted 3 rows of data.<br/>";

// Closing connection
pg_close($connection);
?>

Read data
Use the following code to connect and read the data using a SELECT SQL statement.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
to run the SELECT command, keeping the results in a result set, and pg_last_error() to check the details if an error
occurred. To read the result set, method pg_fetch_row() is called in a loop, once per row, and the row data is
retrieved in an array $row , with one data value per column in each array position. To free the result set, method
pg_free_result() is called. Then it calls method pg_close() to close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.
<?php
// Initialize connection variables.
$host = "mypgserver-20170401.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mypgserver-20170401";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). "<br/>");

print "Successfully created connection to database. <br/>";

// Perform some SQL queries over the connection.


$query = "SELECT * from inventory";
$result_set = pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");
while ($row = pg_fetch_row($result_set))
{
print "Data row = ($row[0], $row[1], $row[2]). <br/>";
}

// Free result_set
pg_free_result($result_set);

// Closing connection
pg_close($connection);
?>

Update data
Use the following code to connect and update the data using a UPDATE SQL statement.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
to run a command, and pg_last_error() to check the details if an error occurred. Then it calls method pg_close() to
close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.

<?php
// Initialize connection variables.
$host = "mypgserver-20170401.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mypgserver-20170401";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). ".<br/>");

print "Successfully created connection to database. <br/>";

// Modify some data in table.


$new_quantity = 200;
$name = '\'banana\'';
$query = "UPDATE inventory SET quantity = $new_quantity WHERE name = $name;";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). ".<br/>");
print "Updated 1 row of data. </br>";

// Closing connection
pg_close($connection);
?>
Delete data
Use the following code to connect and read the data using a DELETE SQL statement.
The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query()
to run a command, and pg_last_error() to check the details if an error occurred. Then it calls method pg_close() to
close the connection.
Replace the $host , $database , $user , and $password parameters with your own values.

<?php
// Initialize connection variables.
$host = "mypgserver-20170401.postgres.database.azure.com";
$database = "mypgsqldb";
$user = "mylogin@mypgserver-20170401";
$password = "<server_admin_password>";

// Initialize connection object.


$connection = pg_connect("host=$host dbname=$database user=$user password=$password")
or die("Failed to create connection to database: ". pg_last_error(). ". </br>");

print "Successfully created connection to database. <br/>";

// Delete some data from table.


$name = '\'orange\'';
$query = "DELETE FROM inventory WHERE name = $name;";
pg_query($connection, $query)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). ". <br/>");
print "Deleted 1 row of data. <br/>";

// Closing connection
pg_close($connection);
?>

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use .NET (C#) to
connect and query data
11/15/2017 • 5 min to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a C# application. It shows
how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article assume
that you are familiar with developing using C#, and that you are new to working with Azure Database for
PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - CLI
You also need to:
Install the .NET Framework. Follow the steps in the linked article to install .NET specifically for your platform
(Windows, Ubuntu Linux, or macOS).
Install Visual Studio or Visual Studio Code to type and edit code.
Add a reference to the Npgsql Nuget package.

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources and search for the server you have created, such as
mypgserver-20170401.
3. Click the server name mypgserver-20170401.
4. Select the server's Overview page. Make a note of the Server name and Server admin login name.

5. If you forget your server login information, navigate to the Overview page to view the Server admin login
name and, if necessary, reset the password.

Connect, create table, and insert data


Use the following code to connect and load the data using CREATE TABLE and INSERT INTO SQL statements. The
code uses NpgsqlCommand class with method Open() to establish a connection to the PostgreSQL database. Then
the code uses method CreateCommand(), sets the CommandText property, and calls the ExecuteNonQuery()
method to run the database commands.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresCreate
{
// Obtain connection string information from the portal
//
private static string Host = "mypgserver-20170401.postgres.database.azure.com";
private static string User = "mylogin@mypgserver-20170401";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4}; SSL Mode=Prefer; Trust
Server Certificate=true",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText = "DROP TABLE IF EXISTS inventory;";
command.ExecuteNonQuery();
Console.Out.WriteLine("Finished dropping table (if existed)");

command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity
INTEGER);";
command.ExecuteNonQuery();
Console.Out.WriteLine("Finished creating table");

command.CommandText =
String.Format(
@"
INSERT INTO inventory (name, quantity) VALUES ({0}, {1});
INSERT INTO inventory (name, quantity) VALUES ({2}, {3});
INSERT INTO inventory (name, quantity) VALUES ({4}, {5});
",
"\'banana\'", 150,
"\'orange\'", 154,
"\'apple\'", 100
);

int nRows = command.ExecuteNonQuery();


Console.Out.WriteLine(String.Format("Number of rows inserted={0}", nRows));
Console.Out.WriteLine("Closing connection");
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Read data
Use the following code to connect and read the data using a SELECT SQL statement. The code uses
NpgsqlCommand class with method Open() to establish a connection to PostgreSQL. Then the code uses the
methods CreateCommand() and ExecuteReader() to run the database commands. Next, the code uses Read() to
advance to the record in the results. Finally, the code uses GetInt32() and GetString() to parse the values in the
record.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresRead
{
// Obtain connection string information from the portal
//
private static string Host = "mypgserver-20170401.postgres.database.azure.com";
private static string User = "mylogin@mypgserver-20170401";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText = "SELECT * FROM inventory;";

var reader = command.ExecuteReader();


while (reader.Read())
{
Console.WriteLine(
string.Format(
"Reading from table=({0}, {1}, {2})",
reader.GetInt32(0).ToString(),
reader.GetString(1),
reader.GetInt32(2).ToString()
)
);
}

Console.Out.WriteLine("Closing connection");
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Update data
Use the following code to connect and update the data using an UPDATE SQL statement. The code uses
NpgsqlCommand class with method Open() to establish a connection to PostgreSQL. Then, the code uses method
CreateCommand(), sets the CommandText property, and calls the ExecuteNonQuery() method to run the database
commands.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresUpdate
{
// Obtain connection string information from the portal
//
private static string Host = "mypgserver-20170401.postgres.database.azure.com";
private static string User = "mylogin@mypgserver-20170401";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText =
String.Format("UPDATE inventory SET quantity = {0} WHERE name = {1};",
200,
"\'banana\'"
);

int nRows = command.ExecuteNonQuery();


Console.Out.WriteLine(String.Format("Number of rows updated={0}", nRows));

Console.Out.WriteLine("Closing connection");
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Delete data
Use the following code to connect and delete data using a DELETE SQL statement.
The code uses NpgsqlCommand class with method Open() to establish a connection to the PostgreSQL database.
Then, the code uses the CreateCommand() method, sets the CommandText property, and calls the method
ExecuteNonQuery() to run the database commands.
Replace the Host, DBName, User, and Password parameters with the values that you specified when you created
the server and database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;

namespace Driver
{
public class AzurePostgresDelete
{
// Obtain connection string information from the portal
//
private static string Host = "mypgserver-20170401.postgres.database.azure.com";
private static string User = "mylogin@mypgserver-20170401";
private static string DBname = "mypgsqldb";
private static string Password = "<server_admin_password>";
private static string Port = "5432";

static void Main(string[] args)


{
// Build connection string using parameters from portal
//
string connString =
String.Format(
"Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};",
Host,
User,
DBname,
Port,
Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection");
conn.Open();

var command = conn.CreateCommand();


command.CommandText =
String.Format("DELETE FROM inventory WHERE name = {0};",
"\'orange\'");
int nRows = command.ExecuteNonQuery();
Console.Out.WriteLine(String.Format("Number of rows deleted={0}", nRows));

Console.Out.WriteLine("Closing connection");
conn.Close();

Console.WriteLine("Press RETURN to exit");


Console.ReadLine();
}
}
}

Next steps
Migrate your database using Export and Import
Azure Database for PostgreSQL: Use Go language to
connect and query data
11/6/2017 • 9 min to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using code written in the Go
language (golang). It shows how to use SQL statements to query, insert, update, and delete data in the database.
This article assumes you are familiar with development using Go, but that you are new to working with Azure
Database for PostgreSQL.

Prerequisites
This quickstart uses the resources created in either of these guides as a starting point:
Create DB - Portal
Create DB - Azure CLI

Install Go and pq connector


Install Go and the Pure Go Postgres driver (pq) on your own machine. Depending on your platform, follow the
appropriate steps:
Windows
1. Download and install Go for Microsoft Windows according to the installation instructions.
2. Launch the command prompt from the start menu.
3. Make a folder for your project, such as mkdir %USERPROFILE%\go\src\postgresqlgo .
4. Change directory into the project folder, such as cd %USERPROFILE%\go\src\postgresqlgo .
5. Set the environment variable for GOPATH to point to the source code directory. set GOPATH=%USERPROFILE%\go .
6. Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
In summary, install Go, then run these commands in the command prompt:

mkdir %USERPROFILE%\go\src\postgresqlgo
cd %USERPROFILE%\go\src\postgresqlgo
set GOPATH=%USERPROFILE%\go
go get github.com/lib/pq

Linux (Ubuntu)
1. Launch the Bash shell.
2. Install Go by running sudo apt-get install golang-go .
3. Make a folder for your project in your home directory, such as mkdir -p ~/go/src/postgresqlgo/ .
4. Change directory into the folder, such as cd ~/go/src/postgresqlgo/ .
5. Set the GOPATH environment variable to point to a valid source directory, such as your current home
directory's go folder. At the bash shell, run export GOPATH=~/go to add the go directory as the GOPATH for the
current shell session.
6. Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
In summary, run these bash commands:
sudo apt-get install golang-go
mkdir -p ~/go/src/postgresqlgo/
cd ~/go/src/postgresqlgo/
export GOPATH=~/go/
go get github.com/lib/pq

Apple macOS
1. Download and install Go according to the installation instructions matching your platform.
2. Launch the Bash shell.
3. Make a folder for your project in your home directory, such as mkdir -p ~/go/src/postgresqlgo/ .
4. Change directory into the folder, such as cd ~/go/src/postgresqlgo/ .
5. Set the GOPATH environment variable to point to a valid source directory, such as your current home
directory's go folder. At the bash shell, run export GOPATH=~/go to add the go directory as the GOPATH for the
current shell session.
6. Install the Pure Go Postgres driver (pq) by running the go get github.com/lib/pq command.
In summary, install Go, then run these bash commands:

mkdir -p ~/go/src/postgresqlgo/
cd ~/go/src/postgresqlgo/
export GOPATH=~/go/
go get github.com/lib/pq

Get connection information


Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully
qualified server name and login credentials.
1. Log in to the Azure portal.
2. From the left-hand menu in Azure portal, click All resources and search for the server you have created, such as
mypgserver-20170401.
3. Click the server name mypgserver-20170401.
4. Select the server's Overview page. Make a note of the Server name and Server admin login name.

5. If you forget your server login information, navigate to the Overview page, and view the Server admin login
name. If necessary, reset the password.

Build and run Go code


1. To write Golang code, you can use a plain text editor, such as Notepad in Microsoft Windows, vi or Nano in
Ubuntu, or TextEdit in macOS. If you prefer a richer Interactive Development Environment (IDE) try Gogland by
Jetbrains, Visual Studio Code by Microsoft, or Atom.
2. Paste the Golang code from the following sections into text files, and save into your project folder with file
extension *.go, such as Windows path %USERPROFILE%\go\src\postgresqlgo\createtable.go or Linux path
~/go/src/postgresqlgo/createtable.go .
3. Locate the HOST , DATABASE , USER , and PASSWORD constants in the code, and replace the example values with
your own values.
4. Launch the command prompt or bash shell. Change directory into your project folder. For example, on Windows
cd %USERPROFILE%\go\src\postgresqlgo\ . On Linux cd ~/go/src/postgresqlgo/ . Some of the IDE environments
mentioned offer debug and runtime capabilities without requiring shell commands.
5. Run the code by typing the command go run createtable.go to compile the application and run it.
6. Alternatively, to build the code into a native application, go build createtable.go , then launch createtable.exe
to run the application.

Connect and create a table


Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT
INTO SQL statements to add rows into the table.
The code imports three packages: the sql package, the pq package as a driver to communicate with the PostgreSQL
server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The code calls the Exec() method several times to run several SQL commands. Each time a custom
checkError() method checks if an error occurred and panic to exit if an error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.
package main

import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)

const (
// Initialize connection constants.
HOST = "mypgserver-20170401.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mypgserver-20170401"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {
// Initialize connection string.
var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST,
USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Drop previous table of same name if one exists.


_, err = db.Exec("DROP TABLE IF EXISTS inventory;")
checkError(err)
fmt.Println("Finished dropping table (if existed)")

// Create table.
_, err = db.Exec("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
checkError(err)
fmt.Println("Finished creating table")

// Insert some data into table.


sql_statement := "INSERT INTO inventory (name, quantity) VALUES ($1, $2);"
_, err = db.Exec(sql_statement, "banana", 150)
checkError(err)
_, err = db.Exec(sql_statement, "orange", 154)
checkError(err)
_, err = db.Exec(sql_statement, "apple", 100)
checkError(err)
fmt.Println("Inserted 3 rows of data")
}

Read data
Use the following code to connect and read the data using a SELECT SQL statement.
The code imports three packages: the sql package, the pq package as a driver to communicate with the PostgreSQL
server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The select query is run by calling method db.Query(), and the resulting rows are kept in a variable
of type rows. The code reads the column data values in the current row using method rows.Scan() and loops over
the rows using the iterator rows.Next() until no more rows exist. Each row's column values are printed to the
console out. Each time a custom checkError() method is used to check if an error occurred and panic to exit if an
error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.

package main

import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)

const (
// Initialize connection constants.
HOST = "mypgserver-20170401.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mypgserver-20170401"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {

// Initialize connection string.


var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST,
USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Read rows from table.


var id int
var name string
var quantity int

sql_statement := "SELECT * from inventory;"


rows, err := db.Query(sql_statement)
checkError(err)

for rows.Next() {
switch err := rows.Scan(&id, &name, &quantity); err {
case sql.ErrNoRows:
fmt.Println("No rows were returned")
case nil:
fmt.Printf("Data row = (%d, %s, %d)\n", id, name, quantity)
default:
checkError(err)
}
}
}
Update data
Use the following code to connect and update the data using an UPDATE SQL statement.
The code imports three packages: the sql package, the pq package as a driver to communicate with the Postgres
server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The code calls the Exec() method to run the SQL statement that updates the table. A custom
checkError() method is used to check if an error occurred and panic to exit if an error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.

package main

import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
)

const (
// Initialize connection constants.
HOST = "mypgserver-20170401.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mypgserver-20170401"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {

// Initialize connection string.


var connectionString string =
fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST, USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Modify some data in table.


sql_statement := "UPDATE inventory SET quantity = $2 WHERE name = $1;"
_, err = db.Exec(sql_statement, "banana", 200)
checkError(err)
fmt.Println("Updated 1 row of data")
}

Delete data
Use the following code to connect and delete the data using a DELETE SQL statement.
The code imports three packages: the sql package, the pq package as a driver to communicate with the Postgres
server, and the fmt package for printed input and output on the command line.
The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the
connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the
database server. The code calls the Exec() method to run the SQL statement that deletes a row from the table. A
custom checkError() method is used to check if an error occurred and panic to exit if an error does occur.
Replace the HOST , DATABASE , USER , and PASSWORD parameters with your own values.

package main

import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
)

const (
// Initialize connection constants.
HOST = "mypgserver-20170401.postgres.database.azure.com"
DATABASE = "mypgsqldb"
USER = "mylogin@mypgserver-20170401"
PASSWORD = "<server_admin_password>"
)

func checkError(err error) {


if err != nil {
panic(err)
}
}

func main() {

// Initialize connection string.


var connectionString string =
fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST, USER, PASSWORD, DATABASE)

// Initialize connection object.


db, err := sql.Open("postgres", connectionString)
checkError(err)

err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")

// Delete some data from table.


sql_statement := "DELETE FROM inventory WHERE name = $1;"
_, err = db.Exec(sql_statement, "orange")
checkError(err)
fmt.Println("Deleted 1 row of data")
}

Next steps
Migrate your database using Export and Import
Design your first Azure Database for PostgreSQL
using the Azure portal
11/6/2017 • 6 min to read • Edit Online

Azure Database for PostgreSQL is a managed service that enables you to run, manage, and scale highly available
PostgreSQL databases in the cloud. Using the Azure portal, you can easily manage your server and design a
database.
In this tutorial, you use the Azure portal to learn how to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data

Prerequisites
If you don't have an Azure subscription, create a free account before you begin.

Log in to the Azure portal


Log in to the Azure portal.

Create an Azure Database for PostgreSQL


An Azure Database for PostgreSQL server is created with a defined set of compute and storage resources. The
server is created within an Azure resource group.
Follow these steps to create an Azure Database for PostgreSQL server:
1. Click the + New button found on the upper left-hand corner of the Azure portal.
2. Select Databases from the New page, and select Azure Database for PostgreSQL from the Databases
page.
3. Fill out the new server details form with the following information, as shown on the preceding image:
Server name: mypgserver-20170401 (name of a server maps to DNS name and is thus required to be
globally unique)
Subscription: If you have multiple subscriptions, choose the appropriate subscription in which the
resource exists or is billed for.
Resource group: myresourcegroup
Server admin login and password of your choice
Location
PostgreSQL Version

IMPORTANT
The server admin login and password that you specify here are required to log in to the server and its databases later
in this quickstart. Remember or record this information for later use.

4. Click Pricing tier to specify the service tier and performance level for your new database. For this quickstart,
select Basic Tier, 50 Compute Units and 50 GB of included storage.
5. Click Ok.
6. Click Create to provision the server. Provisioning takes a few minutes.

TIP
Check the Pin to dashboard option to allow easy tracking of your deployments.

7. On the toolbar, click Notifications to monitor the deployment process.

By default, postgres database gets created under your server. The postgres database is a default database
meant for use by users, utilities, and third-party applications.

Configure a server-level firewall rule


The Azure Database for PostgreSQL service uses a firewall at the server-level. By default, this firewall prevents all
external applications and tools from connecting to the server and any databases on the server unless a firewall rule
is created to open the firewall for a specific IP address range.
1. After the deployment completes, click All Resources from the left-hand menu and type in the name
mypgserver-20170401 to search for your newly created server. Click the server name listed in the search
result. The Overview page for your server opens and provides options for further configuration.

2. In the server page, select Connection security.


3. Click in the text box under Rule Name, and add a new firewall rule to whitelist the IP range for connectivity.
For this tutorial, let's allow all IPs by typing in Rule Name = AllowAllIps, Start IP = 0.0.0.0 and End IP =
255.255.255.255 and then click Save. You can set a specific firewall rule that covers a smaller IP range to be
able to connect from your network.

4. Click Save and then click the X to close the Connections security page.

NOTE
Azure PostgreSQL server communicates over port 5432. If you are trying to connect from within a corporate
network, outbound traffic over port 5432 may not be allowed by your network's firewall. If so, you cannot connect to
your Azure SQL Database server unless your IT department opens port 5432.

Get the connection information


When you created the Azure Database for PostgreSQL server, the default postgres database was also created. To
connect to your database server, you need to provide host information and access credentials.
1. From the left-hand menu in the Azure portal, click All resources and search for the server you just created
mypgserver-20170401.
2. Click the server name mypgserver-20170401.
3. Select the server's Overview page. Make a note of the Server name and Server admin login name.

Connect to PostgreSQL database using psql in Cloud Shell


Let's now use the psql command-line utility to connect to the Azure Database for PostgreSQL server.
1. Launch the Azure Cloud Shell via the terminal icon on the top navigation pane.

2. The Azure Cloud Shell opens in your browser, enabling you to type bash commands.

3. At the Cloud Shell prompt, connect to your Azure Database for PostgreSQL server using the psql commands.
The following format is used to connect to an Azure Database for PostgreSQL server with the psql utility:

psql --host=<myserver> --port=<port> --username=<server admin login> --dbname=<database name>


For example, the following command connects to the default database called postgres on your PostgreSQL
server mypgserver-20170401.postgres.database.azure.com using access credentials. Enter your server
admin password when prompted.

psql --host=mypgserver-20170401.postgres.database.azure.com --port=5432 --username=mylogin@mypgserver-


20170401 --dbname=postgres

Create a new database


Once you're connected to the server, create a blank database at the prompt.

CREATE DATABASE mypgsqldb;

At the prompt, execute the following command to switch connection to the newly created database mypgsqldb.

\c mypgsqldb

Create tables in the database


Now that you know how to connect to the Azure Database for PostgreSQL, you can complete some basic tasks:
First, create a table and load it with some data. Let's create a table that tracks inventory information using this SQL
code:

CREATE TABLE inventory (


id serial PRIMARY KEY,
name VARCHAR(50),
quantity INTEGER
);

You can see the newly created table in the list of tables now by typing:

\dt

Load data into the tables


Now that you have a table, insert some data into it. At the open command prompt window, run the following query
to insert some rows of data.

INSERT INTO inventory (id, name, quantity) VALUES (1, 'banana', 150);
INSERT INTO inventory (id, name, quantity) VALUES (2, 'orange', 154);

You have now two rows of sample data into the inventory table you created earlier.

Query and update the data in the tables


Execute the following query to retrieve information from the inventory database table.

SELECT * FROM inventory;


You can also update the data in the table.

UPDATE inventory SET quantity = 200 WHERE name = 'banana';

You can see the updated values when you retrieve the data.

SELECT * FROM inventory;

Restore data to a previous point in time


Imagine you have accidentally deleted this table. This situation is something you cannot easily recover from. Azure
Database for PostgreSQL allows you to go back to any point-in-time (in the last up to 7 days (Basic) and 35 days
(Standard)) and restore this point-in-time to a new server. You can use this new server to recover your deleted
data. The following steps restore the mypgserver-20170401 server to a point before the inventory table was
added.
1. On the Azure Database for PostgreSQL Overview page for your server, click Restore on the toolbar. The
Restore page opens.

2. Fill out the Restore form with the required information:

Restore point: Select a point-in-time that occurs before the server was changed
Target server: Provide a new server name you want to restore to
Location: You cannot select the region, by default it is same as the source server
Pricing tier: You cannot change this value when restoring a server. It is same as the source server.
3. Click OK restore the server to a point-in-time before the table was deleted. Restoring a server to a different
point in time creates a duplicate new server as the original server as of the point in time you specify, provided
that it is within the retention period for your service tier.

Next steps
In this tutorial, you learned how to use the Azure portal and other utilities to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data
Next, to learn how to use the Azure CLI to do similar tasks, review this tutorial: Design your first Azure Database for
PostgreSQL using Azure CLI
Design your first Azure Database for PostgreSQL
using Azure CLI
11/28/2017 • 6 min to read • Edit Online

In this tutorial, you use Azure CLI (command-line interface) and other utilities to learn how to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data
You may use the Azure Cloud Shell in the browser, or install Azure CLI 2.0 on your own computer to run the
commands in this tutorial.

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common
Azure tools preinstalled and configured to use with your account. Just click the Copy to copy the code, paste it into
the Cloud Shell, and then press enter to run it. There are two ways to launch the Cloud Shell:

Click Try It in the upper right corner of a code block.

Click the Cloud Shell button on the menu in the upper right
of the Azure portal.

If you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.0 or
later. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI 2.0.
If you have multiple subscriptions, choose the appropriate subscription in which the resource exists or is billed for.
Select a specific subscription ID under your account using az account set command.

az account set --subscription 00000000-0000-0000-0000-000000000000

Create a resource group


Create an Azure resource group using the az group create command. A resource group is a logical container into
which Azure resources are deployed and managed as a group. The following example creates a resource group
named myresourcegroup in the westus location.

az group create --name myresourcegroup --location westus


Create an Azure Database for PostgreSQL server
Create an Azure Database for PostgreSQL server using the az postgres server create command. A server contains a
group of databases managed as a group.
The following example creates a server called mypgserver-20170401 in your resource group myresourcegroup with
server admin login mylogin . The name of a server maps to DNS name and is thus required to be globally unique in
Azure. Substitute the <server_admin_password> with your own value.

az postgres server create --resource-group myresourcegroup --name mypgserver-20170401 --location westus --


admin-user mylogin --admin-password <server_admin_password> --performance-tier Basic --compute-units 50 --
version 9.6

IMPORTANT
The server admin login and password that you specify here are required to log in to the server and its databases later in this
quick start. Remember or record this information for later use.

By default, postgres database gets created under your server. The postgres database is a default database meant
for use by users, utilities, and third-party applications.

Configure a server-level firewall rule


Create an Azure PostgreSQL server-level firewall rule with the az postgres server firewall-rule create command. A
server-level firewall rule allows an external application, such as psql or PgAdmin to connect to your server through
the Azure PostgreSQL service firewall.
You can set a firewall rule that covers an IP range to be able to connect from your network. The following example
uses az postgres server firewall-rule create to create a firewall rule AllowAllIps that allows connection from any IP
address. To open all IP addresses, use 0.0.0.0 as the starting IP address and 255.255.255.255 as the ending address.
To restrict access to your Azure PostgreSQL server to only your network, you can set the firewall rule to only cover
your corporate network IP address range.

az postgres server firewall-rule create --resource-group myresourcegroup --server mypgserver-20170401 --name


AllowAllIps --start-ip-address 0.0.0.0 --end-ip-address 255.255.255.255

NOTE
Azure PostgreSQL server communicates over port 5432. When connecting from within a corporate network, outbound traffic
over port 5432 may not be allowed by your network's firewall. Have your IT department open port 5432 to connect to your
Azure SQL Database server.

Get the connection information


To connect to your server, you need to provide host information and access credentials.

az postgres server show --resource-group myresourcegroup --name mypgserver-20170401

The result is in JSON format. Make a note of the administratorLogin and fullyQualifiedDomainName.
{
"administratorLogin": "mylogin",
"fullyQualifiedDomainName": "mypgserver-20170401.postgres.database.azure.com",
"id": "/subscriptions/00000000-0000-0000-0000-
000000000000/resourceGroups/myresourcegroup/providers/Microsoft.DBforPostgreSQL/servers/mypgserver-20170401",
"location": "westus",
"name": "mypgserver-20170401",
"resourceGroup": "myresourcegroup",
"sku": {
"capacity": 50,
"family": null,
"name": "PGSQLS2M50",
"size": null,
"tier": "Basic"
},
"sslEnforcement": null,
"storageMb": 51200,
"tags": null,
"type": "Microsoft.DBforPostgreSQL/servers",
"userVisibleState": "Ready",
"version": "9.6"
}

Connect to Azure Database for PostgreSQL database using psql


If your client computer has PostgreSQL installed, you can use a local instance of psql, or the Azure Cloud Console
to connect to an Azure PostgreSQL server. Let's now use the psql command-line utility to connect to the Azure
Database for PostgreSQL server.
1. Run the following psql command to connect to an Azure Database for PostgreSQL database:

psql --host=<servername> --port=<port> --username=<user@servername> --dbname=<dbname>

For example, the following command connects to the default database called postgres on your PostgreSQL
server mypgserver-20170401.postgres.database.azure.com using access credentials. Enter the
<server_admin_password> you chose when prompted for password.

psql --host=mypgserver-20170401.postgres.database.azure.com --port=5432 --username=mylogin@mypgserver-


20170401 ---dbname=postgres

2. Once you are connected to the server, create a blank database at the prompt:

CREATE DATABASE mypgsqldb;

3. At the prompt, execute the following command to switch connection to the newly created database
mypgsqldb:

\c mypgsqldb

Create tables in the database


Now that you know how to connect to the Azure Database for PostgreSQL, we can go over how to complete some
basic tasks.
First, we can create a table and load it with some data. Let's create a table that tracks inventory information:
CREATE TABLE inventory (
id serial PRIMARY KEY,
name VARCHAR(50),
quantity INTEGER
);

You can see the newly created table in the list of tables now by typing:

\dt

Load data into the table


Now that we have a table, we can insert some data into it. At the open command prompt window, run the following
query to insert some rows of data:

INSERT INTO inventory (id, name, quantity) VALUES (1, 'banana', 150);
INSERT INTO inventory (id, name, quantity) VALUES (2, 'orange', 154);

You have now added two rows of sample data into the table you created earlier.

Query and update the data in the tables


Execute the following query to retrieve information from the inventory table:

SELECT * FROM inventory;

You can also update the data in the inventory table:

UPDATE inventory SET quantity = 200 WHERE name = 'banana';

You can see the updated values when you retrieve the data:

SELECT * FROM inventory;

Restore a database to a previous point in time


Imagine you have accidentally deleted a table. This is something you cannot easily recover from. Azure Database
for PostgreSQL allows you to go back to any point-in-time (up to 7 days in Basic and 35 days in Standard) and
restore this point-in-time to a new server. You can use this new server to recover your deleted data.
The following command restores the sample server to a point before the table was added:

az postgres server restore --resource-group myResourceGroup --name mypgserver-restored --restore-point-in-time


2017-04-13T13:59:00Z --source-server mypgserver-20170401

The az postgres server restore command needs the following parameters:

SETTING SUGGESTED VALUE DESCRIPTION


SETTING SUGGESTED VALUE DESCRIPTION

--resource-group myResourceGroup The resource group in which the source


server exists.

--name mypgserver-restored The name of the new server that is


created by the restore command.

restore-point-in-time 2017-04-13T13:59:00Z Select a point-in-time to restore to. This


date and time must be within the
source server's backup retention period.
Use ISO8601 date and time format. For
example, you may use your own local
timezone, such as
2017-04-13T05:59:00-08:00 , or use
UTC Zulu format
2017-04-13T13:59:00Z .

--source-server mypgserver-20170401 The name or ID of the source server to


restore from.

Restoring a server to a point-in-time creates a new server, copied as the original server as of the point in time you
specify. The location and pricing tier values for the restored server are the same as the source server.
The command is synchronous, and will return after the server is restored. Once the restore finishes, locate the new
server that was created. Verify the data was restored as expected.

Next steps
In this tutorial, you learned how to use Azure CLI (command-line interface) and other utilities to:
Create an Azure Database for PostgreSQL server
Configure the server firewall
Use psql utility to create a database
Load sample data
Query data
Update data
Restore data
Next, learn how to use the Azure portal to do similar tasks, review this tutorial: Design your first Azure Database for
PostgreSQL using the Azure portal
1 min to read •
Edit O nline
Azure CLI samples for Azure Database for
PostgreSQL
11/6/2017 • 1 min to read • Edit Online

The following table includes links to sample Azure CLI scripts for Azure Database for PostgreSQL.

Create a server

Create a server and firewall rule Azure CLI script that creates a single Azure Database for
PostgreSQL server and configures a server-level firewall rule.

Scale a server

Scale a server Azure CLI script that scales a single Azure Database for
PostgreSQL server up or down to allow for changing
performance needs.
Azure Database for PostgreSQL Servers
11/28/2017 • 2 min to read • Edit Online

This article provides considerations and guidelines for working with Azure Database for PostgreSQL servers.

What is an Azure Database for PostgreSQL server?


An Azure Database for PostgreSQL server is a central administrative point for multiple databases. It is the same
PostgreSQL server construct that you may be familiar with in the on-premises world. Specifically, the PostgreSQL
service is managed, provides performance guarantees, exposes access and features at the server-level.
An Azure Database for PostgreSQL server:
Is created within an Azure subscription.
Is the parent resource for databases.
Provides a namespace for databases.
Is a container with strong lifetime semantics - delete a server and it deletes the contained databases.
Collocates resources in a region.
Provides a connection endpoint for server and database access (.postgresql.database.azure.com).
Provides the scope for management policies that apply to its databases: login, firewall, users, roles,
configurations, etc.
Is available in multiple versions. For more information, see supported PostgreSQL database versions.
Is extensible by users. For more information, see PostgreSQL extensions.
Within an Azure Database for PostgreSQL server, you can create one or multiple databases. You can opt to create a
single database per server to utilize all the resources, or create multiple databases to share the resources. The
pricing is structured per-server, based on the configuration of pricing tier, compute units, and storage (GB). For
more information, see Pricing tiers.

How do I connect and authenticate to an Azure Database for


PostgreSQL server?
The following elements help ensure safe access to your database.
| :-- | :-- | | Authentication and authorization | Azure Database for PostgreSQL server supports native
PostgreSQL authentication. You can connect and authenticate to server with the server's admin login. | | Protocol |
The service supports a message-based protocol used by PostgreSQL. | | TCP/IP | The protocol is supported over
TCP/IP, and over Unix-domain sockets. | | Firewall | To help protect your data, a firewall rule prevents all access to
your server and to its databases, until you specify which computers have permission. See Azure Database for
PostgreSQL Server firewall rules. |

How do I manage a server?


You can manage Azure Database for PostgreSQL servers by using the Azure portal or the Azure CLI.

Server parameters
The PostgreSQL server parameters determine the configuration of the server. In Azure Database for PostgreSQL
the list of parameters can be viewed and edited via the Azure portal or the Azure CLI.
As a managed service for Postgres, the configurable parameters in Azure Database for PostgreSQL are a subset of
the parameters in a local Postgres instance (For more information on Postgres parameters, see the PostgreSQL
documentation). Your Azure Database for PostgreSQL server is enabled with default values for each parameter on
creation. Parameters that would require a server restart or superuser access for changes to take effect cannot be
configured by the user.

Next steps
For an overview of the service, see Azure Database for PostgreSQL Overview.
For information about specific resource quotas and limitations based on your service tier, see Service tiers.
For information on connecting to the service, see Connection libraries for Azure Database for PostgreSQL.
View and edit server parameters through Azure portal or Azure CLI.
Supported PostgreSQL Database Versions
11/6/2017 • 1 min to read • Edit Online

Microsoft aims to support n-2 versions of the PostgreSQL engine in the Azure Database for PostgreSQL service,
meaning the currently released major version (n) and the two prior major versions (-2).
Azure Database for PostgreSQL currently supports the following versions:

PostgreSQL Version 9.6.2


Refer to the PostgreSQL documentation to learn more about improvements and fixes in PostgreSQL 9.6.2.

PostgreSQL Version 9.5.7


Refer to the PostgreSQL documentation to learn about improvements and fixes in PostgreSQL 9.5.7.

Managing updates and upgrades


Azure Database for PostgreSQL automatically manages patching for minor version updates. Currently, in public
preview, major version upgrade is not supported. For example, upgrading from PostgreSQL 9.5 to PostgreSQL 9.6
is not supported.

Next steps
For information about the support of different PostgreSQL extensions, see PostgreSQL Extensions
PostgreSQL extensions in Azure Database for
PostgreSQL
11/28/2017 • 2 min to read • Edit Online

PostgreSQL provides the ability to extend the functionality of your database using extensions. Extensions allow for
bundling multiple related SQL objects together in a single package that can be loaded or removed from your
database with a single command. After being loaded in the database, extensions can function as do built-in
features. For more information on PostgreSQL extensions, see Packaging Related Objects into an Extension.

How to use PostgreSQL extensions


PostgreSQL extensions must be installed in your database before you can use them. To install a particular
extension, run the CREATE EXTENSION command from psql tool to load the packaged objects into your database.
Azure Database for PostgreSQL currently supports a subset of key extensions as listed below. Extensions beyond
the ones listed are not supported; you cannot create your own extension with Azure Database for PostgreSQL
service.

Extensions supported by Azure Database for PostgreSQL


The following tables list the standard PostgreSQL extensions that are currently supported by Azure Database for
PostgreSQL. This information is also available by querying pg\_available\_extensions .
Data types extensions
EXTENSION DESCRIPTION

chkpass Provides a data type for auto-encrypted passwords.

citext Provides a case-insensitive character string type.

cube Provides a data type for multidimensional cubes.

hstore Provides a data type for storing sets of key/value pairs.

isn Provides data types for international product numbering


standards.

ltree Provides a data type for hierarchical tree-like structures.

Functions extensions
EXTENSION DESCRIPTION

earthdistance Provides a means to calculate great-circle distances on the


surface of the Earth.

fuzzystrmatch Provides several functions to determine similarities and


distance between strings.
EXTENSION DESCRIPTION

intarray Provides functions and operators for manipulating null-free


arrays of integers.

pgcrypto Provides cryptographic functions.

pg_partman Manages partitioned tables by time or ID.

pg_trgm Provides functions and operators for determining the


similarity of alphanumeric text based on trigram matching.

tablefunc Provides functions that manipulate whole tables, including


crosstab.

uuid-ossp Generates universally unique identifiers (UUIDs).

Full-text search extensions


EXTENSION DESCRIPTION

dict_int Provides a text search dictionary template for integers.

unaccent A text search dictionary that removes accents (diacritic signs)


from lexemes.

Index Types extensions


EXTENSION DESCRIPTION

btree_gin Provides sample GIN operator classes that implement B-tree


like behavior for certain data types.

btree_gist Provides GiST index operator classes that implement B-tree.

Language extensions
EXTENSION DESCRIPTION

plpgsql PL/pgSQL loadable procedural language.

Miscellaneous extensions
EXTENSION DESCRIPTION

pg_buffercache Provides a means for examining what's happening in the


shared buffer cache in real time.

pg_prewarm Provides a way to load relation data into the buffer cache.

pg_stat_statements Provides a means for tracking execution statistics of all SQL


statements executed by a server.

pgrowlocks Provides a means for showing row-level locking information.


EXTENSION DESCRIPTION

pgstattuple Provides a means for showing tuple-level statistics.

postgres_fdw Foreign-data wrapper used to access data stored in external


PostgreSQL servers.

PostGIS extensions
EXTENSION DESCRIPTION

PostGIS, postgis_topology, postgis_tiger_geocoder, Spatial and geographic objects for PostgreSQL.


postgis_sfcgal

address_standardizer, address_standardizer_data_us Used to parse an address into constituent elements. Used to


support geocoding address normalization step.

pgrouting Extends the PostGIS / PostgreSQL geospatial database to


provide geospatial routing functionality.

Next steps
If you don't see an extension that you'd like to use, let us know. Vote for existing requests or create new feedback
and requests in our Customer feedback forum.
Server Logs in Azure Database for PostgreSQL
10/25/2017 • 1 min to read • Edit Online

Azure Database for PostgreSQL generates query and error logs. However, access to transaction logs is not
supported. Query and error logs can be used to identify, troubleshoot, and repair configuration errors and
suboptimal performance. For more information, see Error Reporting and Logging.

Access server logs


You can list and download Azure PostgreSQL server error logs using the Azure portal, Azure CLI, and Azure REST
APIs.

Log retention
You can set the retention period for system logs using the log_retention_period parameter associated with your
server. The unit for this parameter is days. The default value is 3 days. The maximum value is 7 days. Your server
must have enough allocated storage to contain the retained log files. The log files rotate every one hour or 100 MB
size, whichever comes first.

Configure logging for Azure PostgreSQL server


You can enable query logging and error logging for your server. Error logs can contain auto-vacuum, connection,
and checkpoints information.
You can enable query logging for your PostgreSQL DB instance by setting two server parameters: log\_statement
and log\_min\_duration\_statement .
The log_statement parameter controls which SQL statements are logged. We recommend setting this parameter
to all to log all statements; the default value is none.
The log_min_duration_statement parameter sets the limit in milliseconds of a statement to be logged. All SQL
statements that run longer than the parameter setting are logged. This parameter is disabled and set to minus 1 (-
1) by default. Enabling this parameter can be helpful in tracking down unoptimized queries in your applications.
The log_min_messages allows you to control which message levels are written to the server log. The default is
WARNING.
For more information on these settings, see Error Reporting and Logging documentation. For particularly
configuring Azure Database for PostgreSQL server parameters, see Customize server configuration parameters
using Azure CLI.

Next steps
To access logs using Azure CLI command-line interface, see Configure and access server logs using Azure CLI.
For more information on server parameters, see Customize server configuration parameters using Azure CLI.
High availability concepts in Azure Database for
PostgreSQL
11/2/2017 • 1 min to read • Edit Online

The Azure Database for PostgreSQL service provides a guaranteed high level of availability. The financially backed
service level agreement (SLA) is 99.99% upon general availability. There is virtually no application down time when
using this service.

High availability
The high availability (HA) model is based on built-in fail-over mechanisms when a node-level interruption occurs. A
node-level interruption could occur because of a hardware failure or in response to a service deployment.
At all times, changes made to an Azure Database for PostgreSQL database server occur in the context of a
transaction. Changes are recorded synchronously in Azure storage when the transaction is committed. If a node-
level interruption occurs, the database server automatically creates a new node and attaches data storage to the
new node. Any active connections are dropped and any inflight transactions are not committed.

Application retry logic is essential


It is important that PostgreSQL database applications are built to detect and retry dropped connections and failed
transactions. When the application retries, the application's connection is transparently redirected to the newly
created instance, which takes over for the failed instance.
Internally in Azure, a gateway is used to redirect the connections to the new instance. Upon an interruption, the
entire fail-over process typically takes tens of seconds. Since the redirect is handled internally by the gateway, the
external connection string remains the same for the client applications.

Scaling up or down
Similar to the HA model, when an Azure Database for PostgreSQL is scaled up or down, a new server instance with
the specified size is created. The existing data storage is detached from the original instance, and attached to the
new instance.
During the scale operation, an interruption to the database connections occurs. The client applications are
disconnected, and open uncommitted transactions are canceled. Once the client application retries the connection,
or makes a new connection, the gateway directs the connection to the newly sized instance.

Next steps
For an overview of the service, see Azure Database for PostgreSQL Overview
Azure Database for PostgreSQL options and
performance: Understand what’s available in each
pricing tier
11/6/2017 • 6 min to read • Edit Online

When you create an Azure Database for PostgreSQL server, you decide upon three main choices to configure the
resources allocated for that server. These choices impact the performance and scale of the server.
Pricing tier
Compute Units
Storage (GB)
Each pricing tier has a range of performance levels (Compute Units) to choose from, depending on your
workloads requirements. Higher performance levels provide additional resources for your server designed to
deliver higher throughput. You can change the server's performance level within a pricing tier with virtually no
application downtime.

IMPORTANT
While the service is in public preview, there is not a guaranteed Service Level Agreement (SLA).

Within an Azure Database for PostgreSQL server, you can have one or multiple databases. You can opt to create a
single database per server to have the database utilize all the server resources, or create multiple databases to
share the server resources.

Choose a pricing tier


While in preview, Azure Database for PostgreSQL offers two pricing tiers: Basic and Standard. Premium tier is not
yet available, but is coming soon.
The following table provides examples of the pricing tiers best suited for different application workloads.

PRICING TIER TARGET WORKLOADS

Basic Best suited for small workloads that require scalable compute
and storage without IOPS guarantee. Examples include
servers used for development or testing, or small-scale
infrequently used applications.

Standard The go-to option for cloud applications that need IOPS
guarantee with high throughput. Examples include web or
analytical applications.

Premium Best suited for workloads that need low latency for
transactions and IO. Provides the best support for many
concurrent users. Applicable to databases that support
mission critical applications.
The Premium pricing tier is not available in preview.

To decide on a pricing tier, first start by determining if your workload needs an IOPS guarantee. If so, use
Standard pricing tier.

PRICING TIER FEATURES BASIC STANDARD

Maximum Compute Units 100 800

Maximum total storage 1 TB 1 TB

Storage IOPS guarantee N/A Yes

Maximum storage IOPS N/A 3,000

Database backup retention period 7 days 35 days

During the preview timeframe, you cannot change pricing tier once the server is created. In the future, it will be
possible to upgrade or downgrade a server from one pricing tier to another tier.

Understand the price


When you create a new Azure Database for PostgreSQL inside the Azure portal, click the Pricing tier page, and
the monthly cost is shown based on the options you have selected. If you do not have an Azure subscription, use
the Azure pricing calculator to get an estimated price. Visit the Azure pricing calculator website, then click Add
items, expand the Databases category, and choose Azure Database for PostgreSQL to customize the options.

Choose a performance level (Compute Units)


Once you have determined the pricing tier for your Azure Database for PostgreSQL server, you are ready to
determine the performance level by selecting the number of Compute Units needed. A good starting point is 200
or 400 Compute Units for applications that require higher user concurrency for their web or analytical workloads,
and adjust incrementally as needed.
Compute Units are a measure of CPU processing throughput that is guaranteed to be available to a single Azure
Database for PostgreSQL server. A Compute Unit is a blended measure of CPU and memory resources. For more
information, see Explaining Compute Units.
Basic pricing tier performance levels:
PERFORMANCE LEVEL 50 100

Max Compute Units 50 100

Included storage size 50 GB 50 GB

Max server storage size* 1 TB 1 TB

Standard pricing tier performance levels:


PERFORMANCE LEVEL 100 200 400 800

Max Compute Units 100 200 400 800

Included storage size 125 GB, 125 GB, 125 GB, 125 GB,
and provisioned IOPS 375 IOPS 375 IOPS 375 IOPS 375 IOPS
PERFORMANCE LEVEL 100 200 400 800

Max server storage 1 TB 1 TB 1 TB 1 TB


size*

Max server 3,000 IOPS 3,000 IOPS 3,000 IOPS 3,000 IOPS
provisioned IOPS

Max server Fixed 3 IOPS per GB Fixed 3 IOPS per GB Fixed 3 IOPS per GB Fixed 3 IOPS per GB
provisioned IOPS per
GB

* Max server storage size refers to the maximum provisioned storage size for your server.

Storage
The storage configuration defines the amount of storage capacity available to an Azure Database for PostgreSQL
server. The storage used by the service includes the database files, transaction logs, and the PostgreSQL server
logs. Consider the size of storage needed to host your databases and the performance requirements (IOPS) when
selecting the storage configuration.
Some storage capacity is included at a minimum with each pricing tier, noted in the preceding table as "Included
storage size." Additional storage capacity can be added when the server is created, in increments of 125 GB, up to
the maximum allowed storage. The additional storage capacity can be configured independently of the Compute
Units configuration. The price changes based on the amount of storage selected.
The IOPS configuration in each performance level relates to the pricing tier and the storage size chosen. Basic tier
does not provide an IOPS guarantee. Within the Standard pricing tier, the IOPS scale proportionally to maximum
storage size in a fixed 3:1 ratio. The included storage of 125-GB guarantees for 375 provisioned IOPS, each with
an IO size of up to 256 KB. You can choose additional storage up to 1 TB maximum, to guarantee 3,000
provisioned IOPS.
Monitor the Metrics graph in the Azure portal or write Azure CLI commands to measure the consumption of
storage and IOPS. Relevant metrics to monitor are Storage limit, Storage percentage, Storage used, and IO
percentage.

IMPORTANT
While in preview, choose the amount of storage at the time when the server is created. Changing the storage size on an
existing server is not yet supported.

Scaling a server up or down


You initially choose the pricing tier and performance level when you create your Azure Database for PostgreSQL.
Later, you can scale the Compute Units up or down dynamically, within the range of the same pricing tier. In the
Azure portal, slide the Compute Units on the server's Pricing tier page, or script it by following this example:
Monitor and scale a single PostgreSQL server using Azure CLI
Scaling the Compute Units is done independently of the maximum storage size you have chosen.
Behind the scenes, changing the performance level of a database creates a copy of the original server at the new
performance level, and then switches connections over to the copied server. No data is lost during this process.
During the brief moment when the system switches over to the new copy of the server, connections to the
database are disabled, so some transactions in flight may be rolled back. This window varies, but on average is
under 4 seconds, and in more than 99% of cases is less than 30 seconds. If there are large numbers of
transactions in flight at the moment connections are disabled, this window may be longer.
The duration of the entire scale process depends on both the size and pricing tier of the server before and after
the change. For example, a server that is changing Compute Units within the Standard pricing tier, should
complete within few minutes. The new properties for the server are not applied until the changes are complete.

Next steps
For more on Compute Units, see Explaining Compute Units
Learn how to Monitor and scale a single PostgreSQL server using Azure CLI
Explaining Compute Units in Azure Database for
PostgreSQL
10/26/2017 • 2 min to read • Edit Online

This topic explains the concept of Compute Units and what happens when your workload reaches the maximum
level of Compute Units.

What are Compute Units?


Compute Units are a measure of CPU processing throughput that is guaranteed to be available to a single Azure
Database for PostgreSQL server. A Compute Unit is a blended measure of CPU and memory resources. In general,
50 Compute Units equate to half of a core. 100 Compute Units equate to one core. 2000 Compute Units equate to
20 cores of guaranteed processing throughput available to your server.
The amount of memory per Compute Unit is optimized for the Basic and Standard pricing tiers. Doubling the
Compute Units by increasing the performance level equates to doubling the amount of CPU and memory
available to that single Azure Database for PostgreSQL.
For example, a Standard 800 Compute Units provides 8x more CPU throughput and memory than a Standard 100
Compute Units configuration. However, while Standard 100 Compute Units provide the same CPU throughput as
does Basic 100 Compute Units, the amount of memory that is pre-configured in the Standard pricing tier is double
the amount of memory configured for the Basic pricing tier. Therefore, the Standard pricing tier provides better
workload performance and lower transaction latency than does the Basic pricing tier with the same Compute
Units selected.

How can I determine the number of Compute Units needed for my


workload?
If you are looking to migrate an existing PostgreSQL server running on-premises or on a virtual machine, you can
determine the number of Compute Units by estimating how many cores of processing throughput your workload
needs.
If your existing on-premises or virtual machine server is currently utilizing 4 cores (without counting CPU
hyperthread), start by configuring 400 Compute Units for your Azure Database for PostgreSQL server. Compute
Units can be dynamically scaled up or down depending on your workload needs with virtually no application
downtime.
Monitor the Metrics graph in the Azure portal or write Azure CLI commands to measure Compute Units. Relevant
metrics to monitor are the Compute Unit percentage and Compute Unit limit.

IMPORTANT
If you find storage IOPS are not fully utilized to the maximum, consider monitoring the Compute Units utilization as well.
Raising the Compute Units may allow for higher IO throughput by lessening the performance bottleneck due to limited CPU
or memory.

What happens when I hit my maximum Compute Units?


Performance levels are calibrated and governed to provide resources to run your database workload up to the
maximum limits for the selected pricing tier and performance level.
If your workload reaches the maximum limits in either the Compute Units or provisioned IOPS, you can continue
to use the resources at the maximum allowed level, but your queries are likely to see increased latencies. These
limits do not result in any errors, but rather a slowdown in the workload, unless the slowdown becomes so severe
that queries time out.
If your workload reaches the maximum limits on number of connections, explicit errors are raised. For more
information on resources limits, see Limitations in Azure Database for PostgreSQL.

Next steps
For more information on pricing tiers, see Azure Database for PostgreSQL pricing tiers.
Limitations in Azure Database for PostgreSQL
11/28/2017 • 1 min to read • Edit Online

The Azure Database for PostgreSQL service is in public preview. The following sections describe capacity and
functional limits in the database service.

Service Tier Maximums


Azure Database for PostgreSQL has multiple service tiers you can choose from when creating a server. For more
information, see Understand what’s available in each service tier.
There is a maximum number of connections, compute units, and storage in each service tier during the service
preview, as follows:

Max connections

Basic 50 Compute Units 50 connections

Basic 100 Compute Units 100 connections

Standard 100 Compute Units 200 connections

Standard 200 Compute Units 300 connections

Standard 400 Compute Units 400 connections

Standard 800 Compute Units 500 connections

Max Compute Units

Basic service tier 100 Compute Units

Standard service tier 800 Compute Units

Max storage

Basic service tier 1 TB

Standard service tier 1 TB

When too many connections are reached, you may receive the following error:

FATAL: sorry, too many clients already

Preview functional limitations


Scale operations
1. Dynamic scaling of servers across service tiers is currently not supported. That is, switching between Basic and
Standard service tiers.
2. Dynamic on-demand increase of storage on pre-created server is currently not supported.
3. Decreasing server storage size is not supported.
Server version upgrades
Automated migration between major database engine versions is currently not supported.
Subscription management
Dynamically moving pre-created servers across subscription and resource group is currently not supported.
Point-in-time -restore
1. Restoring to different service tier and/or Compute Units and Storage size is not allowed.
2. Restoring a dropped server is not supported.

Next steps
Understand What’s available in each pricing tier
Understand Supported PostgreSQL Database Versions
Review How To Back up and Restore a server in Azure Database for PostgreSQL using the Azure portal
Azure Database for PostgreSQL Server firewall rules
11/6/2017 • 3 min to read • Edit Online

Azure Database for PostgreSQL Server firewall prevents all access to your database server until you specify which
computers have permission. The firewall grants access to the server based on the originating IP address of each
request. To configure your firewall, you create firewall rules that specify ranges of acceptable IP addresses. You can
create firewall rules at the server level.
Firewall rules: These rules enable clients to access your entire Azure Database for PostgreSQL Server, that is, all
the databases within the same logical server. Server-level firewall rules can be configured by using the Azure
portal or using Azure CLI commands. To create server-level firewall rules, you must be the subscription owner or a
subscription contributor.

Firewall overview
All database access to your Azure Database for PostgreSQL server is blocked by the firewall by default. To begin
using your server from another computer, you need to specify one or more server-level firewall rules to enable
access to your server. Use the firewall rules to specify which IP address ranges from the Internet to allow. Access to
the Azure portal website itself is not impacted by the firewall rules. Connection attempts from the Internet and
Azure must first pass through the firewall before they can reach your PostgreSQL Database, as shown in the
following diagram:

Connecting from the Internet


Server-level firewall rules apply to all databases on the same Azure Database for PostgreSQL server. If the IP
address of the request is within one of the ranges specified in the server-level firewall rules, the connection is
granted. If the IP address of the request is not within the ranges specified in any of the server-level firewall rules,
the connection request fails. For example, if your application connects with JDBC driver for PostgreSQL, you may
encounter this error attempting to connect when the firewall is blocking the connection.

java.util.concurrent.ExecutionException: java.lang.RuntimeException: org.postgresql.util.PSQLException: FATAL:


no pg_hba.conf entry for host "123.45.67.890", user "adminuser", database "postgresql", SSL

Programmatically managing firewall rules


In addition to the Azure portal, firewall rules can be managed programmatically using Azure CLI. See also Create
and manage Azure Database for PostgreSQL firewall rules using Azure CLI

Troubleshooting the database server firewall


Consider the following points when access to the Microsoft Azure Database for PostgreSQL Server service does
not behave as you expect:
Changes to the allow list have not taken effect yet: There may be as much as a five-minute delay for
changes to the Azure Database for PostgreSQL Server firewall configuration to take effect.
The login is not authorized or an incorrect password was used: If a login does not have permissions
on the Azure Database for PostgreSQL server or the password used is incorrect, the connection to the Azure
Database for PostgreSQL server is denied. Creating a firewall setting only provides clients with an
opportunity to attempt connecting to your server; each client must still provide the necessary security
credentials.
For example, using a JDBC client, the following error may appear.

java.util.concurrent.ExecutionException: java.lang.RuntimeException: org.postgresql.util.PSQLException: FATAL:


password authentication failed for user "yourusername"

Dynamic IP address: If you have an Internet connection with dynamic IP addressing and you are having
trouble getting through the firewall, you could try one of the following solutions:
Ask your Internet Service Provider (ISP) for the IP address range assigned to your client computers that
access the Azure Database for PostgreSQL Server, and then add the IP address range as a firewall rule.
Get static IP addressing instead for your client computers, and then add the static IP address as a firewall
rule.

Next steps
For articles on creating server-level firewall rules, see:
Create and manage Azure Database for PostgreSQL firewall rules using the Azure portal.
Create and manage Azure Database for PostgreSQL firewall rules using Azure CLI.
Configure SSL connectivity in Azure Database for
PostgreSQL
11/1/2017 • 5 min to read • Edit Online

Azure Database for PostgreSQL prefers connecting your client applications to the PostgreSQL service using Secure
Sockets Layer (SSL). Enforcing SSL connections between your database server and your client applications helps
protect against "man in the middle" attacks by encrypting the data stream between the server and your
application.
By default, the PostgreSQL database service is configured to require SSL connection. Optionally, you can disable
requiring SSL to connect to your database service if your client application does not support SSL connectivity.

Enforcing SSL connections


For all Azure Database for PostgreSQL servers provisioned through the Azure portal and CLI, enforcement of SSL
connections is enabled by default.
Likewise, connection strings that are pre-defined in the "Connection Strings" settings under your server in the
Azure portal include the required parameters for common languages to connect to your database server using
SSL. The SSL parameter varies based on the connector, for example "ssl=true" or "sslmode=require" or
"sslmode=required" and other variations.

Configure Enforcement of SSL


You can optionally disable enforcing SSL connectivity. Microsoft Azure recommends to always enable Enforce SSL
connection setting for enhanced security.
Using the Azure portal
Visit your Azure Database for PostgreSQL server and click Connection security. Use the toggle button to enable
or disable the Enforce SSL connection setting. Then, click Save.

You can confirm the setting by viewing the Overview page to see the SSL enforce status indicator.
Using Azure CLI
You can enable or disable the ssl-enforcement parameter using Enabled or Disabled values respectively in
Azure CLI.
az postgres server update --resource-group myresourcegroup --name mypgserver-20170401 --ssl-enforcement
Enabled

Ensure your application or framework supports SSL connections


Many common application frameworks that use PostgreSQL for their database services, such as Drupal and
Django, do not enable SSL by default during installation. Enabling SSL connectivity must be done after installation
or through CLI commands specific to the application. If your PostgreSQL server is enforcing SSL connections and
the associated application is not configured properly, the application may fail to connect to your database server.
Consult your application's documentation to learn how to enable SSL connections.

Applications that require certificate verification for SSL connectivity


In some cases, applications require a local certificate file generated from a trusted Certificate Authority (CA)
certificate file (.cer) to connect securely. See the following steps to obtain the .cer file, decode the certificate and
bind it to your application.
Download the certificate file from the Certificate Authority (CA )
The certificate needed to communicate over SSL with your Azure Database for PostgreSQL server is located here.
Download the certificate file locally.
Download and install OpenSSL on your machine
To decode the certificate file needed for your application to connect securely to your database server, you need to
install OpenSSL on your local computer.
For Linux, OS X, or Unix
The OpenSSL libraries are provided in source code directly from the OpenSSL Software Foundation. The following
instructions guide you through the steps necessary to install OpenSSL on your Linux PC. This article uses
commands known to work on Ubuntu 12.04 and higher.
Open a terminal session and download OpenSSL.

wget http://www.openssl.org/source/openssl-1.1.0e.tar.gz

Extract the files from the downloaded package.

tar -xvzf openssl-1.1.0e.tar.gz

Enter the directory where the files were extracted. By default, it should be as follows.

cd openssl-1.1.0e

Configure OpenSSL by executing the following command. If you want the files in a folder different than
/usr/local/openssl, make sure to change the following as appropriate.

./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl

Now that OpenSSL is configured properly, you need to compile it to convert your certificate. To compile, run the
following command:
make

Once compilation is complete, you're ready to install OpenSSL as an executable by running the following
command:

make install

To confirm that you've successfully installed OpenSSL on your system, run the following command and check to
make sure you get the same output.

/usr/local/openssl/bin/openssl version

If successful you should see the following message.

OpenSSL 1.1.0e 7 Apr 2014

For Windows
Installing OpenSSL on a Windows PC can be done in the following ways:
1. (Recommended) Using the built-in Bash for Windows functionality in Window 10 and above, OpenSSL is
installed by default. Instructions on how to enable Bash for Windows functionality in Windows 10 can be found
here.
2. Through downloading a Win32/64 application provided by the community. While the OpenSSL Software
Foundation does not provide or endorse any specific Windows installers, they provide a list of available
installers here.
Decode your certificate file
The downloaded Root CA file is in encrypted format. Use OpenSSL to decode the certificate file. To do so, run this
OpenSSL command:

openssl x509 -inform DER -in BaltimoreCyberTrustRoot.crt -text -out root.crt

Connecting to Azure Database for PostgreSQL with SSL certificate authentication


Now that you have successfully decoded your certificate, you can now connect to your database server securely
over SSL. To allow server certificate verification, the certificate must be placed in the file ~/.postgresql/root.crt in
the user's home directory. (On Microsoft Windows the file is named %APPDATA%\postgresql\root.crt.). The
following provides instructions for connecting to Azure Database for PostgreSQL.

NOTE
Currently, there is a known issue if you use "sslmode=verify-full" in your connection to the service, the connection will fail
with the following error: server certificate for "<region>.control.database.windows.net" (and 7 other names) does not
match host name "<servername>.postgres.database.azure.com". If "sslmode=verify-full" is required, please use the server
naming convention <servername>.database.windows.net as the host name in your connection string. We plan to
remove this limitation in the future. Connections using other SSL modes should continue to use the preferred host naming
convention <servername>.postgres.database.azure.com.

Using psql command-line utility


The following example shows how to successfully connect to your PostgreSQL server using the psql command-
line utility. Use the root.crt file created and the sslmode=verify-ca or sslmode=verify-full option.
Using the PostgreSQL command-line interface, execute the following command:

psql "sslmode=verify-ca sslrootcert=root.crt host=mypgserver-20170401.postgres.database.azure.com


dbname=postgres user=mylogin@mypgserver-20170401"

If successful, you receive the following output:

Password for user mylogin@mypgserver-20170401:


psql (9.6.2)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=>

Using pgAdmin GUI tool


Configuring pgAdmin 4 to connect securely over SSL requires you to set the SSL mode = Verify-CA or
SSL mode = Verify-Full as follows:

Next steps
Review various application connectivity options following Connection libraries for Azure Database for PostgreSQL.
Monitoring in Azure Database for PostgreSQL
10/24/2017 • 1 min to read • Edit Online

Monitoring data about your servers helps you troubleshoot and optimize for your workload. Azure Database for
PostgreSQL provides various metrics that give insight into the behavior of the resources supporting the
PostgreSQL server.

Metrics
All Azure metrics have a one-minute frequency, and each metric provides 30 days of history.
You can configure alerts on the metrics. For step by step guidance, see How to set up alerts.
Other tasks include setting up automated actions, performing advanced analytics, and archiving history. For more
information, see the Azure Metrics Overview.
List of metrics
These metrics are available for Azure Database for PostgreSQL:

METRIC METRIC DISPLAY NAME UNIT DESCRIPTION

cpu_percent CPU percent Percent The percentage of CPU in


use.

compute_limit Compute Unit limit Count This server's maximum


number of compute units

compute_consumption_perc Compute Unit percentage Percent The percentage of compute


ent units used out of the server's
maximum.

memory_percent Memory percent Percent The percentage of memory


in use.

io_consumption_percent IO percent Percent The percentage of IO in use.

storage_percent Storage percentage Percent The percentage of storage


used out of the server's
maximum.

storage_used Storage used Bytes The amount of storage in


use. The storage used by the
service includes the database
files, transaction logs, and
the server logs.

storage_limit Storage limit Bytes The maximum storage for


this server.

active_connections Total active connections Count The number of active


connections to the server.
METRIC METRIC DISPLAY NAME UNIT DESCRIPTION

connections_failed Total failed connections Count The number of failed


connections to the server.

NOTE
Compute Unit is composed of Memory and CPU. The Compute Unit percentage is max(memory%, cpu%). Examine the
memory and cpu charts to pinpoint which is contributing to Compute Unit percentage changes. For more information, see
compute units.

Next steps
For step by step guidance, see How to set up alerts.
For more information on how to access and export metrics using the Azure portal, REST API, or CLI, see the
Azure Metrics Overview.
Connection libraries for Azure Database for
PostgreSQL
11/6/2017 • 1 min to read • Edit Online

This article lists libraries and drivers that developers can use to develop applications to connect to and query
Azure Database for PostgreSQL.

Client interfaces
Most language client libraries used to connect to PostgreSQL server are external projects and are distributed
independently. The libraries listed are supported on the Windows, Linux, and Mac platforms, for connecting to
Azure Database for PostgreSQL. Several quickstart examples are listed in the Next steps section.

LANGUAGE CLIENT INTERFACE ADDITIONAL INFORMATION DOWNLOAD

Python psycopg DB API 2.0-compliant Download

PHP php-pgsql Database extension Install

Node.js Pg npm package Pure JavaScript non- Install


blocking client

Java JDBC Type 4 JDBC driver Download

Ruby Pg gem Ruby Interface Download

Go Package pq Pure Go postgres driver Install

C#/ .NET Npgsql ADO.NET Data Provider Download

ODBC psqlODBC ODBC Driver Download

C libpq Primary C language Included


interface

C++ libpqxx New-style C++ interface Download

Next steps
Read these quickstarts on how to connect to and query Azure Database for PostgreSQL by using your language of
choice:
Python | Node.JS | Java | Ruby | PHP | .NET (C#) | Go
Create and manage Azure Database for PostgreSQL
firewall rules using the Azure portal
11/28/2017 • 2 min to read • Edit Online

Server-level firewall rules enable administrators to access an Azure Database for PostgreSQL Server from a
specified IP address or range of IP addresses.

Prerequisites
To step through this how-to guide, you need:
A server Create an Azure Database for PostgreSQL

Create a server-level firewall rule in the Azure portal


1. On the PostgreSQL server page, under Settings heading, click Connection security to open the Connection
security page for the Azure Database for PostgreSQL.

2. Select Add My IP on the toolbar. This action automatically creates a firewall rule with the public IP address
of your computer, as perceived by the Azure system.
3. Verify your IP address before saving the configuration. In some situations, the IP address observed by Azure
portal differs from the IP address used when accessing the internet and Azure servers. Therefore, you may
need to change the Start IP and End IP to make the rule function as expected. Use a search engine or other
online tool to check your own IP address (for example, Bing search "what is my IP").

4. Add additional address ranges. In the firewall rules for the Azure Database for PostgreSQL, you can specify a
single IP address, or a range of addresses. If you want to limit the rule to a single IP address, type the same
address in the field for Start IP and End IP. Opening the firewall enables administrators, users, and
applications to log in to any database on the PostgreSQL server to which they have valid credentials.
5. Click Save on the toolbar to save this server-level firewall rule. Wait for the confirmation that the update to
the firewall rules was successful.

Manage existing server-level firewall rules through the Azure portal


Repeat the steps to manage the firewall rules.
To add the current computer, click the button to + Add My IP. Click Save to save the changes.
To add additional IP addresses, type in the Rule Name, Start IP Address, and End IP Address. Click Save to save
the changes.
To modify an existing rule, click any of the fields in the rule and modify. Click Save to save the changes.
To delete an existing rule, click the ellipsis […] and click Delete to remove the rule. Click Save to save the
changes.

Next steps
Similarly, you can script to Create and manage Azure Database for PostgreSQL firewall rules using Azure CLI.
For help in connecting to an Azure Database for PostgreSQL server, see Connection libraries for Azure Database
for PostgreSQL.
Create and manage Azure Database for PostgreSQL
firewall rules using Azure CLI
11/28/2017 • 2 min to read • Edit Online

Server-level firewall rules enable administrators to manage access to an Azure Database for PostgreSQL Server
from a specific IP address or range of IP addresses. Using convenient Azure CLI commands, you can create, update,
delete, list, and show firewall rules to manage your server. For an overview of Azure Database for PostgreSQL
firewall rules, see Azure Database for PostgreSQL Server firewall rules

Prerequisites
To step through this how-to guide, you need:
An Azure Database for PostgreSQL server and database.
Install Azure CLI 2.0 command-line utility or use the Azure Cloud Shell in the browser.

Configure firewall rules for Azure Database for PostgreSQL


The az postgres server firewall-rule commands are used to configure firewall rules.

List firewall rules


To list the existing server firewall rules, run the az postgres server firewall-rule list command.

az postgres server firewall-rule list --resource-group myresourcegroup --server mypgserver-20170401

The output lists the firewall rules, if any, by default in JSON format. You may use the switch --output table for a
more readable table format as the output.

az postgres server firewall-rule list --resource-group myresourcegroup --server mypgserver-20170401 --output


table

Create firewall rule


To create a new firewall rule on the server, run the az postgres server firewall-rule create command.
By specifying 0.0.0.0 as the --start-ip-address and 255.255.255.255 as the --end-ip-address range, the
following example allows all IP addresses to access the server mypgserver-
20170401.postgres.database.azure.com

az postgres server firewall-rule create --resource-group myresourcegroup --server mypgserver-20170401 --name


"AllowIpRange" --start-ip-address 0.0.0.0 --end-ip-address 255.255.255.255

To allow access to a singular IP address, provide the same address in the --start-ip-address and
--end-ip-address , as in this example.
az postgres server firewall-rule create --resource-group myresourcegroup
--server mypgserver-20170401 --name "AllowSingleIpAddress" --start-ip-address 13.83.152.1 --end-ip-address
13.83.152.1

Upon success, the command output lists the details of the firewall rule you have created, by default in JSON
format. If there is a failure, the output shows an error message instead.

Update firewall rule


Update an existing firewall rule on the server using az postgres server firewall-rule update command. Provide the
name of the existing firewall rule as input, and the start IP and end IP attributes to update.

az postgres server firewall-rule update --resource-group myresourcegroup --server mypgserver-20170401 --name


"AllowIpRange" --start-ip-address 13.83.152.0 --end-ip-address 13.83.152.255

Upon success, the command output lists the details of the firewall rule you have updated, by default in JSON
format. If there is a failure, the output shows an error message instead.

NOTE
If the firewall rule does not exist, it gets created by the update command.

Show firewall rule details


You can also show the details of an existing server-level firewall rule by running az postgres server firewall-rule
show command.

az postgres server firewall-rule show --resource-group myresourcegroup --server mypgserver-20170401 --name


"AllowIpRange"

Upon success, the command output lists the details of the firewall rule you have specified, by default in JSON
format. If there is a failure, the output shows an error message instead.

Delete firewall rule


To revoke access for an IP range to the server, delete an existing firewall rule by executing the az postgres server
firewall-rule delete command. Provide the name of the existing firewall rule.

az postgres server firewall-rule delete --resource-group myresourcegroup --server mypgserver-20170401 --name


"AllowIpRange"

Upon success, there is no output. Upon failure, the error message text is returned.

Next steps
Similarly, you can use a web browser to Create and manage Azure Database for PostgreSQL firewall rules
using the Azure portal.
Understand more about Azure Database for PostgreSQL Server firewall rules.
For help in connecting to an Azure Database for PostgreSQL server, see Connection libraries for Azure
Database for PostgreSQL.
How to backup and restore a server in Azure
Database for PostgreSQL using the Azure portal
11/6/2017 • 1 min to read • Edit Online

Backup happens automatically


When using Azure Database for PostgreSQL, the database service automatically makes a backup of the server
every 5 minutes.
The backups are available for 7 days when using Basic Tier, and 35 days when using Standard Tier. For more
information, see Azure Database for PostgreSQL service tiers
Using this automatic backup feature you may restore the server and all its databases into a new server to an
earlier point-in-time.

Restore in the Azure portal


Azure Database for PostgreSQL allows you to restore the server back to a point in time and into to a new copy of
the server. You can use this new server to recover your data.
For example, if a table was accidentally dropped at noon today, you could restore to the time just before noon and
retrieve the missing table and data from that new copy of the server.
The following steps restore the sample server to a point in time:
1. Sign into the Azure portal
2. Locate your Azure Database for PostgreSQL server. In the Azure portal, click All Resources from the left-
hand menu and type in the name of the server, such as mypgserver-20170401, to search for your existing
server. Click the server name listed in the search result. The Overview page for your server opens and
provides options for further configuration.

3. On the toolbar of the server's overview page, click Restore. The Restore page opens.
4. Fill out the Restore form with the required information:

Restore point: Select a point-in-time that occurs before the server was changed.
Target server: Provide a new server name you want to restore to.
Location: You cannot select the region. By default it is same as the source server.
Pricing tier: You cannot change this value when restoring a server. It is same as the source server.
5. Click OK to restore the server to restore to a point in time.
6. Once the restore finishes, locate the new server that is created to verify the data was restored as expected.

Next steps
Connection libraries for Azure Database for PostgreSQL
How to backup and restore a server in Azure
Database for PostgreSQL by using the Azure CLI
11/28/2017 • 2 min to read • Edit Online

Use Azure Database for PostgreSQL to restore a server database to an earlier date that spans from 7 to 35 days.

Prerequisites
To complete this how-to guide, you need:
An Azure Database for PostgreSQL server and database

Launch Azure Cloud Shell


The Azure Cloud Shell is a free interactive shell that you can use to run the steps in this article. It has common Azure
tools preinstalled and configured to use with your account. Just click the Copy to copy the code, paste it into the
Cloud Shell, and then press enter to run it. There are two ways to launch the Cloud Shell:

Click Try It in the upper right corner of a code block.

Click the Cloud Shell button on the menu in the upper right
of the Azure portal.

IMPORTANT
If you install and use the Azure CLI locally, this how-to guide requires that you use Azure CLI version 2.0 or later. To confirm
the version, at the Azure CLI command prompt, enter az --version . To install or upgrade, see Install Azure CLI 2.0.

Backup happens automatically


When you use Azure Database for PostgreSQL, the database service automatically makes a backup of the service
every 5 minutes.
For Basic Tier, the backups are available for 7 days. For Standard Tier, the backups are available for 35 days. For
more information, see Azure Database for PostgreSQL pricing tiers.
With this automatic backup feature, you can restore the server and its databases to an earlier date, or point in time.

Restore a database to a previous point in time by using the Azure CLI


Use Azure Database for PostgreSQL to restore the server to a previous point in time. The restored data is copied to
a new server, and the existing server is left as is. For example, if a table is accidentally dropped at noon today, you
can restore to the time just before noon. Then, you can retrieve the missing table and data from the restored copy
of the server.
To restore the server, use the Azure CLI az postgres server restore command.
Run the restore command
To restore the server, at the Azure CLI command prompt, enter the following command:

az postgres server restore --resource-group myResourceGroup --name mypgserver-restored --restore-point-in-time


2017-04-13T13:59:00Z --source-server mypgserver-20170401

The az postgres server restore command requires the following parameters:

SETTING SUGGESTED VALUE DESCRIPTION

resource-group myResourceGroup The resource group where the source


server exists.

name mypgserver-restored The name of the new server that is


created by the restore command.

restore-point-in-time 2017-04-13T13:59:00Z Select a point in time to restore to. This


date and time must be within the
source server's backup retention period.
Use the ISO8601 date and time format.
For example, you can use your own
local time zone, such as
2017-04-13T05:59:00-08:00 . You can
also use the UTC Zulu format, for
example, 2017-04-13T13:59:00Z .

source-server mypgserver-20170401 The name or ID of the source server to


restore from.

When you restore a server to an earlier point in time, a new server is created. The original server and its databases
from the specified point in time are copied to the new server.
The location and pricing tier values for the restored server remain the same as the original server.
The az postgres server restore command is synchronous. After the server is restored, you can use it again to
repeat the process for a different point in time.
After the restore process finishes, locate the new server and verify that the data is restored as expected.

Next steps
Connection libraries for Azure Database for PostgreSQL
Migrate your PostgreSQL database using dump and
restore
11/6/2017 • 1 min to read • Edit Online

You can use pg_dump to extract a PostgreSQL database into a dump file and pg_restore to restore the PostgreSQL
database from an archive file created by pg_dump.

Prerequisites
To step through this how-to guide, you need:
An Azure Database for PostgreSQL server with firewall rules to allow access and database under it.
pg_dump and pg_restore command-line utilities installed
Follow these steps to dump and restore your PostgreSQL database:

Create a dump file using pg_dump that contains the data to be loaded
To back up an existing PostgreSQL database on-premises or in a VM, run the following command:

pg_dump -Fc -v --host=<host> --username=<name> --dbname=<database name> > <database>.dump

For example, if you have a local server and a database called testdb in it

pg_dump -Fc -v --host=localhost --username=masterlogin --dbname=testdb > testdb.dump

Restore the data into the target Azure Database for PostrgeSQL using
pg_restore
Once you have created the target database, you can use the pg_restore command and the -d, --dbname parameter
to restore the data into the target database from the dump file.

pg_restore -v –-host=<server name> --port=<port> --username=<user@servername> --dbname=<target database name>


<database>.dump

In this example, restore the data from the dump file testdb.dump into the database mypgsqldb on target server
mypgserver-20170401.postgres.database.azure.com.

pg_restore -v --host=mypgserver-20170401.postgres.database.azure.com --port=5432 --username=mylogin@mypgserver-


20170401 --dbname=mypgsqldb testdb.dump

Next steps
To migrate a PostgreSQL database using export and import, see Migrate your PostgreSQL database using
export and import
Migrate your PostgreSQL database using export
and import
11/6/2017 • 1 min to read • Edit Online

You can use pg_dump to extract a PostgreSQL database into a script file and psql to import the data into the
target database from that file.

Prerequisites
To step through this how-to guide, you need:
An Azure Database for PostgreSQL server with firewall rules to allow access and database under it.
pg_dump command-line utility installed
psql command-line utility installed
Follow these steps to export and import your PostgreSQL database.

Create a script file using pg_dump that contains the data to be loaded
To export your existing PostgreSQL database on-premises or in a VM to a sql script file, run the following
command in your existing environment:

pg_dump –-host=<host> --username=<name> --dbname=<database name> --file=<database>.sql

For example, if you have a local server and a database called testdb in it:

pg_dump --host=localhost --username=masterlogin --dbname=testdb --file=testdb.sql

Import the data on target Azure Database for PostrgeSQL


You can use the psql command line and the --dbname parameter (-d) to import the data into the Azure Database
for PostgreSQL server and load data from the sql file.

psql --file=<database>.sql --host=<server name> --port=5432 --username=<user@servername> --dbname=<target


database name>

This example uses psql utility and a script file named testdb.sql from previous step to import data into the
database mypgsqldb on the target server mypgserver-20170401.postgres.database.azure.com.

psql --file=testdb.sql --host=mypgserver-20170401.database.windows.net --port=5432 --


username=mylogin@mypgserver-20170401 --dbname=mypgsqldb

Next steps
To migrate a PostgreSQL database using dump and restore, see Migrate your PostgreSQL database using
dump and restore
Configure server parameters in Azure portal
11/9/2017 • 1 min to read • Edit Online

You can list, show, and update configuration parameters for an Azure Database for PostgreSQL server through the
Azure portal.

Prerequisites
To step through this how-to guide you need:
Azure Database for PostgreSQL server

Viewing and editing parameters


1. Open the Azure portal.
2. Select your Azure Database for PostgreSQL server.
3. Under the SETTINGS section, select Server parameters. The page shows a list of parameters, their values,
and descriptions.

4. Select the drop down button to see the possible values for enumerated-type parameters like
client_min_messages.
5. Select or hover over the i (information) button to see the range of possible values for numeric parameters
like cpu_index_tuple_cost.

6. If needed, use the search box to narrow down to a specific parameter. The search is on the name and
description of the parameters.
7. Change the parameter values you would like to adjust. All changes you make in a session are highlighted in
purple. Once you have changed the values, you can select Save. Or you can Discard your changes.

8. If you have saved new values for the parameters, you can always revert everything back to the default
values by selecting Reset all to default.
Next steps
Learn about:
Overview of server parameters in Azure Database for PostgreSQL
Configuring parameters using the Azure CLI
Customize server configuration parameters using
Azure CLI
11/28/2017 • 1 min to read • Edit Online

You can list, show, and update configuration parameters for an Azure PostgreSQL server using the Command Line
Interface (Azure CLI). A subset of engine configurations is exposed at server-level and can be modified.

Prerequisites
To step through this how-to guide, you need:
Create an Azure Database for PostgreSQL server and database by following Create an Azure Database for
PostgreSQL
Install Azure CLI 2.0 command-line interface on your machine or use the Azure Cloud Shell in the Azure portal
using your browser.

List server configuration parameters for Azure Database for


PostgreSQL server
To list all modifiable parameters in a server and their values, run the az postgres server configuration list
command.
You can list the server configuration parameters for the server mypgserver-
20170401.postgres.database.azure.com under resource group myresourcegroup.

az postgres server configuration list --resource-group myresourcegroup --server mypgserver-20170401

Show server configuration parameter details


To show details about a particular configuration parameter for a server, run the az postgres server configuration
show command.
This example shows details of the log_min_messages server configuration parameter for server mypgserver-
20170401.postgres.database.azure.com under resource group myresourcegroup.

az postgres server configuration show --name log_min_messages --resource-group myresourcegroup --server


mypgserver-20170401

Modify server configuration parameter value


You can also modify the value of a certain server configuration parameter, which updates the underlying
configuration value for the PostgreSQL server engine. To update the configuration, use the az postgres server
configuration set command.
To update the log_min_messages server configuration parameter of server mypgserver-
20170401.postgres.database.azure.com under resource group myresourcegroup.
az postgres server configuration set --name log_min_messages --resource-group myresourcegroup --server
mypgserver-20170401 --value INFO

If you want to reset the value of a configuration parameter, you simply choose to leave out the optional --value
parameter, and the service applies the default value. In above example, it would look like:

az postgres server configuration set --name log_min_messages --resource-group myresourcegroup --server


mypgserver-20170401

This command resets the log_min_messages configuration to the default value WARNING. For more
information on server configuration and permissible values, see PostgreSQL documentation on Server
Configuration.

Next steps
To configure and access server logs, see Server Logs in Azure Database for PostgreSQL
Configure and access server logs in the Azure portal
11/7/2017 • 1 min to read • Edit Online

You can configure, list, and download the Azure Database for PostgreSQL server logs from the Azure portal.

Prerequisites
To step through this how-to guide, you need:
Azure Database for PostgreSQL server

Configure logging
Configure access to the query logs and error logs.
1. Sign in to the Azure portal.
2. Select your Azure Database for PostgreSQL server.
3. Under the Monitoring section in the sidebar, select Server Logs.

4. Select the heading Click here to enable logs and configure log parameters to see the server
parameters.
5. Select the Show more expander to see an extended list of available parameters.
For more information on the definitions of parameters, see the PostgreSQL documentation on Error
Reporting and Logging.
6. Change the parameters that you need to adjust. All changes you make in this session are highlighted in
purple.
Once you have changed the parameters, you can click Save. Or you can Discard your changes.

7. Return to the list of logs by clicking the close button (X icon) on the Server Parameters page.

View list and download logs


Once logging begins, you can view a list of available logs and download individual log files on the Server Logs
pane.
1. Open the Azure portal.
2. Select your Azure Database for PostgreSQL server.
3. Under the Monitoring section in the sidebar, select Server Logs. The page shows a list of your log files, as
shown:
TIP
The naming convention of the log is postgresql-yyyy-mm-dd_hh0000.log. The date and time used in the file name
is the time is when the log was issued. The log files rotate every one hour or 100-MB size, whichever comes first.

4. If needed, use the search box to quickly narrow down to a specific log based on date/time. The search is on
the name of the log.

5. Download individual log files using the download button (down arrow icon) next to each log file in the table
row as shown:
Next steps
See Access Server Logs in CLI to learn how to download logs programmatically.
Learn more about Server Logs in Azure DB for PostgreSQL.
For more information about the parameter definitions and PostgreSQL logging, see the PosgreSQL
documentation on Error Reporting and Logging.
Configure and access server logs using Azure CLI
11/28/2017 • 1 min to read • Edit Online

You can download the PostgreSQL server error logs using the Command Line Interface (Azure CLI). However,
access to transaction logs is not supported.

Prerequisites
To step through this how-to guide, you need:
An Azure Database for PostgreSQL server
Install Azure CLI 2.0 command-line utility or use the Azure Cloud Shell in the browser.

Configure logging for Azure Database for PostgreSQL


You can configure the server to access query logs and error logs. Error logs can contain auto-vacuum, connection,
and checkpoints information.
1. Turn on logging
2. Update log_statement and log_min_duration_statement to enable query logging
3. Update retention period
For more information, see customizing server configuration parameters.

List logs for Azure Database for PostgreSQL server


To list the available log files for your server, run the az postgres server-logs list command.
You can list the log files for server mypgserver-20170401.postgres.database.azure.com under Resource
Group myresourcegroup, and direct it to a text file called log_files_list.txt.

az postgres server-logs list --resource-group myresourcegroup --server mypgserver-20170401 >


log_files_list.txt

Download logs locally from the server


The az postgres server-logs download command allows you to download individual log files for your server.
This example downloads the specific log file for the server mypgserver-
20170401.postgres.database.azure.com under Resource Group myresourcegroup to your local environment.

az postgres server-logs download --name 20170414-mypgserver-20170401-postgresql.log --resource-group


myresourcegroup --server mypgserver-20170401

Next steps
To learn more about server logs, see Server Logs in Azure Database for PostgreSQL
For more information on server parameters, see Customize server configuration parameters using Azure CLI
Use the Azure portal to set up alerts on metrics for
Azure Database for PostgreSQL
10/24/2017 • 2 min to read • Edit Online

This article shows you how to set up Azure Database for PostgreSQL alerts using the Azure portal. You can receive
an alert based on monitoring metrics for your Azure services.
The alert triggers when the value of a specified metric crosses a threshold you assign. The alert triggers both when
the condition is first met, and then afterwards when that condition is no longer being met.
You can configure an alert to do the following actions when it triggers:
Send email notifications to the service administrator and co-administrators.
Send email to additional emails that you specify.
Call a webhook.
You can configure and get information about alert rules using:
Azure portal
PowerShell
Command-line interface (CLI)
Azure Monitor REST API

Create an alert rule on a metric from the Azure portal


1. In the Azure portal, select the Azure Database for PostgreSQL server you want to monitor.
2. Under the Monitoring section of the sidebar, select Alert rules as shown:

3. Select Add metric alert (+ icon).


4. The Add rule page opens as shown below. Fill in the required information:
SETTING DESCRIPTION

Name Provide a name for the alert rule. This value is sent in the
alert notification email.

Description Provide a short description of the alert rule. This value is


sent in the alert notification email.

Alert on Choose Metrics for this kind of alert.


SETTING DESCRIPTION

Subscription This field is prepopulated with the subscription that hosts


your Azure Database for PostgreSQL.

Resource group This field is prepopulated with the resource group of your
Azure Database for PostgreSQL.

Resource This field is prepopulated with the name of your Azure


Database for PostgreSQL.

Metric Select the metric that you want to issue an alert for. For
example, Storage percentage.

Condition Choose the condition for the metric to be compared with.


For example, Greater than.

Threshold Threshold value for the metric, for example 85 (percent).

Period The period of time that the metric rule must be satisfied
before the alert triggers. For example, Over the last 30
minutes.

Based on the example, the alert looks for Storage percentage above 85% over a 30-minute period. That
alert triggers when the average Storage percentage has been above 85% for 30 minutes. Once the first
trigger occurs, it triggers again when the average Storage percentage is below 85% over 30 minutes.
5. Choose the notification method you want for the alert rule.
Check Email owners, contributors, and readers option if you want the subscription administrators and
co-administrators to be emailed when the alert fires.
If you want additional emails to receive a notification when the alert fires, add them in the Additional
administrator email(s) field. Separate multiple emails with semi-colons -
email@contoso.com;email2@contoso.com
Optionally, provide a valid URI in the Webhook field if you want it called when the alert fires.
6. Select OK to create the alert.
Within a few minutes, the alert is active and triggers as previously described.

Manage your alerts


Once you have created an alert, you can select it and do the following actions:
View a graph showing the metric threshold and the actual values from the previous day relevant to this alert.
Edit or Delete the alert rule.
Disable or Enable the alert, if you want to temporarily stop or resume receiving notifications.

Next steps
Learn more about configuring webhooks in alerts.
Get an overview of metrics collection to make sure your service is available and responsive.
Azure Database for PostgreSQL videos
12/1/2017 • 1 min to read • Edit Online

Overview: Azure Database for PostgreSQL and MySQL

Azure Database for PostgreSQL and Azure Database for MySQL bring together community edition database
engines and capabilities of a fully managed service—so you can focus on your apps instead of having to manage a
database. Tune in to get a quick overview of the advantages of using the service, and see some of the capabilities in
action.
Deep dive on managed service capabilities for MySQL and PostgreSQL

Azure Database for PostgreSQL and Azure Database for MySQL bring together community edition database
engines and the capabilities of a fully managed service. Tune in to get a deep dive on how these services work—
how we ensure high availability and fast scaling (within seconds), so you can meet your customers’ needs. You'll
also learn about some of the underlying investments in security and worldwide availability.
Develop an intelligent analytics app with PostgreSQL

Azure Database for PostgreSQL brings together community edition database engine and capabilities of a fully
managed service—so you can focus on your apps instead of having to manage a database. Tune in to see in action
how easy it is to create new experiences like adding Cognitive Services to your apps by virtue of being on Azure.
How to get started with the new Azure Database for PostgreSQL service

In this video from the 2017 Microsoft //Build conference, learn from two early adopting customers how they've
used Azure Database for PostgreSQL service to innovate faster. Learn how they migrated to the service, and discuss
next steps in their application development. The video walks through some of the key service features and
discusses how you as a developer can migrate your existing applications or develop new applications that use this
managed PostgreSQL service in Azure.

Вам также может понравиться