Ceng301 Dbms Session 11
Ceng301 Dbms Session 11
Session-11
Asst. Prof. Mustafa YENIAD
[email protected]
PostgreSQL Schemas
• In PostgreSQL, a schema is a namespace that contains named database objects
such as:
tables, views, indexes, data types, functions, stored procedures and operators.
• A schema is a named collection of tables (as well as functions, data types, and
operators).
• The schema name must be unique within a database.
• A database can contain one or multiple schemas and each schema belongs to only one
database. Two schemas can have different objects that share the same name.
• To access an object in a schema, you need to qualify the object by using the following
DBMS
syntax:
schema_name.object_name
• There are some scenarios that you want to use schemas:
• Schemas allow you to organize database objects e.g., tables into logical groups to make them more manageable.
• Schemas enable multiple users to use one database without interfering with each other.
• PostgreSQL automatically creates a schema called public for every new database. Whatever object you create without specifying
the schema name, PostgreSQL will place it into this public schema. Therefore, the following statements are equivalent:
CREATE TABLE table_name( CREATE TABLE public.table_name(
... ...
); );
connection to the database cluster is determined by the role one authenticates to.
• It is important to get a good handle on role management because of its importance within core operations!
• PostgreSQL doesn’t use the user concept like other database systems:
• It uses roles to represent user accounts (roles are equivalent to users).
• A role is a grouping of a specific set of capabilities, permissions, and "owned" entities.
• Instead of having distinct concepts of "users" and "groups",
PostgreSQL uses roles to represent both of these ideas.
• A role can correspond to an individual person in the real world,
or it can operate as a group with certain access that
other roles can become members of.
PostgreSQL Roles
• With PostgreSQL, you can create users and roles with granular access permissions.
• The new user or role must be selectively granted the required permissions for each
database object. This gives a lot of power to the end user, but at the same time, it makes the process of
creating users and roles with the correct permissions potentially complicated.
• PostgreSQL lets you grant permissions directly to the database users. However, as a good
practice, it is recommended that you create multiple roles with specific sets of permissions based on
DBMS
application and access requirements. Then assign the appropriate role to each user.
• The roles should be used to enforce a least privilege model for accessing database objects.
• Always keep in mind: The master user should never be used by the application!
• Instead, most of the time, users should use accounts dedicated to the specific functions or data objects they are
working with, only using the superuser accounts when more powerful access is required.
• The master user that is created during PostgreSQL installation (postgres) should be used
only for database administration tasks like creating other users, roles, and databases.
PostgreSQL Roles
• The recommended approach for setting up fine-grained access control in PostgreSQL is as follows:
• Use the master user to create roles per application or use case, like readonly and readwrite.
• Add permissions to allow these roles to access various database objects. For example, the readonly role can only run
SELECT queries.
• Grant the roles the least possible permissions required for the functionality.
• Create new users for each application or distinct functionality, like app_user and reporting_user.
• Assign the applicable roles to these users to quickly grant them the same permissions as the role. For example, grant
the readwrite role to app_user and grant the readonly role to reporting_user.
DBMS
• At any time, you can remove the role from the user in order to revoke the permissions.
• The following diagram summarizes these recommendations:
PostgreSQL Roles
Role attributes:
• Role attributes are flags on the role itself that determine some of the core privileges it has on the database cluster level.
These can be set when the role is initially created, or changed at any time by any role with the appropriate attributes
(SUPERUSER or CREATEROLE in this case). Attributes that can be applied to a role include:
Role Explanation
LOGIN Allows users to initially connect to the database cluster using this role.
The CREATE USER command automatically adds this attribute, while CREATE ROLE command does not!
DBMS
SUPERUSER Allows the role to bypass all permission checks except the right to log in.
Only other SUPERUSER roles can create roles with this attribute.
CREATEDB Allows the role to create new databases.
CREATEROLE Allows the role to create, alter, and delete other roles.
This attribute also allows the role to assign or alter role membership. An exception is that a role with the CREATEROLE
attribute cannot alter SUPERUSER roles without also having the SUPERUSER attribute.
REPLICATION Allows the role to initiate streaming replication. Roles with this attribute must also have the LOGIN attribute.
PASSWORD Assigns a password to the role that will be used with password or md5 authentication mechanisms.
This attribute takes a password in quotations as an argument directly after the attribute keyword.
INHERIT Determines whether the role inherits the privileges of roles it is a member of.
Without the INHERIT, members must use SET ROLE to change into the other role in order to access those exclusive privileges.
This attribute is set for new roles by default.
• Remember:
• PostgreSQL's authentication system has a number of different components, each of which are tied to roles. In order
to be used for the initial connection to the database, roles must first have the LOGIN attribute set. The
authentication rules are defined in the host-based configuration file called pg_hba.conf. Each rule defines methods
of authentication that may be scoped to the individual role. Upon installation, PostgreSQL is set up to use peer
authentication, meaning that it associates PostgreSQL roles with a matching Unix/Linux system account. It means
that, if a role exists within PostgreSQL, a Unix/Linux username with the same name is able to sign in as that role (in
this case, the postgres role is the default role with superuser privileges):
$ sudo --login -u postgres # switch to the postgres account
postgres@[hostname]:~ $ psql # then access the PostgreSQL prompt immediately
postgres=# \du # this meta-command lists the roles attributes in your Postgres instance
PostgreSQL Roles
r.rolconnlimit, r.rolvaliduntil,
ARRAY(SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
WHERE m.member = r.oid) AS memberof
, r.rolreplication
, r.rolbypassrls
FROM pg_catalog.pg_roles r
WHERE r.rolname !~ '^pg_'
ORDER BY 1;
The "ORDER BY 1" statement above sorts the results based on the first column in the SELECT list.
PostgreSQL Roles
• If you are only interested in seeing which roles have the superuser attribute, you can ask for a list explicitly:
postgres=# SELECT rolname FROM pg_roles WHERE rolsuper;
DBMS
• Alternatively, you can list all users and their superuser status for a more complete picture (if multiple users created):
postgres=# SELECT usename, usesuper FROM pg_user;
• If you want to find the attributes of the role you are currently using:
postgres=# \du :USER
PostgreSQL Roles
Users, groups and roles:
• Users, groups, and roles are the same thing in PostgreSQL, with the only difference being that users have permission to
log in by default.
• The CREATE USER and CREATE GROUP statements are actually aliases for the CREATE ROLE statement.
LOGIN
CREATE USER = CREATE ROLE + PERMISSION
DBMS
• Additional info: In other relational database management systems (RDBMS) like Oracle, users and roles are two different entities.
In Oracle, a role cannot be used to log in to the database. The roles are used only to group grants and other roles. This role can then be
assigned to one or more users to grant them all the permissions.
(Noice that the roles that start with with pg_ are system roles)
postgres=# SELECT rolname FROM pg_roles;
postgres=# \du # to list all existing roles
• As you can see clearly from the output, the role user1 cannot login. To allow to log in to the PostgreSQL database server, you need to
ALTER the LOGIN attribute to it (this enables the ability to login, the authentication methods are still controlled by the pg_hba.conf file).
• If you want user2 to be able to create roles, and create databases, you can specify those two attributes, separated
by spaces:
postgres=# ALTER ROLE user2 WITH CREATEROLE CREATEDB;
postgres=# du\
All new users and roles inherit permissions from the public role.
The following section provides more details about the public role.
Public schema and public role:
• When a new database is created, PostgreSQL by default creates a schema named public and grants access on this
schema to a backend role named public. All new users and roles are by default granted this public role, and therefore can
create objects in the public schema.
• PostgreSQL uses a concept of a search_path.
The search_path is a list of schema names that PostgreSQL checks when you don’t use a qualified name of the database object.
For example, when you select from a table named “mytable”, PostgreSQL looks for this table in the schemas listed in the search path. It
chooses the first match it finds.
• The first name "$user" resolves to the name of the currently logged in user.
• By default, no schema with the same name as the user name exists. So the public schema becomes the default schema whenever
an unqualified object name is used. Because of this, when a user tries to create a new table without specifying the schema name,
the table gets created in the public schema.
DBMS
• As mentioned earlier, by default, all users have access to create objects in the public schema, and therefore the table is created
successfully. This becomes a problem if you are trying to create a read-only user. Even if you restrict all privileges, the permissions
inherited via the public role allow the user to create objects in the public schema. To fix this, you should revoke the default create
permission on the public schema from the public role using the following SQL statement (make sure that you are the owner of the
public schema or are part of a role that allows you to run this SQL statement):
• Read-only Role:
The first step is to create a new role named readonly using the following
SQL statement:
postgres=# CREATE ROLE readonly;
• This is a base role with no permissions and no password. It cannot be used to log in to the database.
Grant this role permission to connect to your target created previously database named "mydatabase":
postgres=# GRANT CONNECT ON DATABASE mydatabase TO readonly;
• The next step is to grant this role usage access to your schema. Let’s assume the schema is named "myschema":
postgres=# GRANT CONNECT ON SCHEMA myschema TO readonly;
• This step grants the readonly role permission to perform some activity inside the schema. Without this step, the readonly
role cannot perform any action on the objects in this schema, even if the permissions were granted for those objects!
PostgreSQL Roles - Public Schema and Public Role
• The next step is to grant the readonly role access to run select on the required tables.
postgres=# GRANT SELECT TABLE mytable1, mytable2 TO readonly;
• If the requirement is to grant access on all the tables and views in the schema, then you can use the following SQL:
postgres=# GRANT SELECT ALL TABLES IN SCHEMA myschema TO readonly;
• The preceding SQL statement grants SELECT access to the readonly role on all the existing tables and views in the schema
myschema. Note that any new tables that get added in the future will not be accessible by the readonly user. To help
DBMS
ensure that new tables and views are also accessible, run the following statement to grant permissions automatically:
postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT ON TABLES TO readonly;
• With the roles in place, the process of creating users is simplified. Just create the user and grant it one of the existing
roles. Here are the SQL statements for this process:
postgres=# CREATE USER user4 WITH PASSWORD 'secret';
postgres=# GRANT readonly TO user4;
• Using the method documented previously, it becomes very easy to revoke privileges from a user. For example, you can
remove the readonly permission from user4 using the following SQL statement:
postgres=# REVOKE readonly FROM user4;