Introduction to PostgreSQL Synonyms
PostgreSQL provides synonyms functionality to the user. A synonym is an identifier and it is used to reference other database objects we can also call alternate names of objects. A synonym is useful in a fully qualified schema name and referenced by PostgreSQL statement. It is not necessary a referenced object is must available at the time we create synonyms. A synonym is useful for non-existing schema or objects. When we delete a referenced object or schema that means your synonyms are not valid. If we have two synonyms with the same name that means it is unqualified so at that time the server uses a search path.
Syntax:
create [or replace] [public] synonyms [sche.]synonyms_name
for obj_sche.obj_name [#database_link_name];
Explanation:
1. synonyms_name:
It is used as the name of synonyms. A synonym must be unique within the database or schema.
2. sche:
Sche specified schema name if we don’t specify the schema name then it is automatically created in the first existing schema in the search path.
3. obj_name:
Obj_name means it specifies object name.
4. obj_sche:
Obj_sche specifies the object schema name of schema and its reference to object.
5. database_link_name:
It is a defined database link and with the help of this link, we can access objects.
How Synonyms works in PostgreSQL?
We must install PostgreSQL in your system. We required basic knowledge about PostgreSQL. We must require a database table to perform synonyms. We need basic knowledge about the synonyms syntax that means how it is used. We can perform different operations on database tables with the help of psql and pgAdmin. The advanced server supports views, tables, functions, procedures, sequences, types, and objects, etc.
Let’s see how we can implement synonyms by using the following example as follows.
Examples
First, we create table college by using the following statement as follows.
Example #1
create table college (emp_id serial PRIMARY KEY, emp_name varchar(30), emp_dept varchar[],emp_city varchar[],emp_salary text[]);
Explanation
With the help of the above statement, we created a college table with different attributes such as emp_id, emp_name, emp_dept, emp_city, and emp_salary. Illustrate the end result of the above declaration by using the following snapshot.
Example #2
Now we implement synonyms as follows.
A synonym is not to be supported in the PostgreSQL database because PostgreSQL differentiates between schema and user clearly. But oracle we need to use synonyms because of this reason. When we use syntax to create synonyms in PostgreSQL at that time it shows syntax errors. Let’s see an example of synonyms as follows.
create or replace public synonym test for public.college;
Explanation
In the above example, we try to implement synonyms in PostgreSQL but it shows error messages because PostgreSQL does not support synonyms. Illustrate the end result of the above declaration by using the following snapshot.
Example #3 – Search Path
Sometimes we create synonyms by using database links or paths. At that time we use this function as follows.
show search_path;
Explanation
In the above statement, we show the search path command to see the existing schema. Illustrate the end result of the above declaration by using the following snapshot.
Example #4 – DROP Synonyms
On the other hand, we can DROP synonyms. So let’s see how we can DROP synonyms in PostgreSQL. Suppose users need to delete synonyms at that time and users use the following syntax as follows.
Syntax:
Drop public synonym synonyms name;
Explanation
In the above syntax, we use the drop synonym command to delete synonyms. When we want to delete synonyms but two synonyms have the same name at that time we check whether the schema is qualified or not.
Example #5 – Synonym Dictionary
PostgreSQL provides a synonyms dictionary function to the user and it is used to replace words with synonyms. Synonyms dictionary is used to overcome the similar word problem. For example, suppose our schema has two similar words like Paris and Pari. So with the help of a synonyms dictionary, we solve that problem.
Example #6 – Conversion of Oracle synonyms to PostgreSQL
PostgreSQL does not support synonyms. But some users or customers need to migrate to PostgreSQL from Oracle. At that time we had a schema conversion tool. With the help of AWS tools, we can convert Oracle synonyms to PostgreSQL synonyms.
Example #7 – Synonyms package conversion of Oracle to PostgreSQL
AWS is not able to convert the oracle synonyms package to PostgreSQL. So let’s see how we can convert as follows.
CREATE OR REPLACE PACKAGE ORA_PACKAGE AS
TYPE oracle_type IS REC (
name VARCHAR2(512),
amount NUMBER);
TYPE r_ora_type IS TABLE OF oracle_type;
v_pi CONSTANT NUMBER(8) :=2.24;
mini_balance CONSTANT REAL := 1.00;
max_balance CONSTANT REAL := 9.00;
CURSOR cur IS SELECT 'Monday' AS "day" FROM dual;
END ORA_PACKAGE;
So we need to write a script to convert this above package into PostgreSQL as follows.
Script for PostgreSQL Constant
CREATE OR REPLACE FUNCTION
schema_name."s_ora_package$schema_name$ora_package$max_balance$c"()
RETURNS DOUBLE PRECISION
LANGUAGE
AS $function$
BEGIN
RETURN 9.00;
END;
$function$
;
Explanation
In the above example, we convert the Oracle synonyms package in PostgreSQL. The above example is specific for PostgreSQL constant, in the above script we create a function as shown in scripts.
Uses
- PostgreSQL synonyms are used to reference another database object, table, functions, etc.
- The synonyms we also use to hide our original content from users mean it is used for security purposes.
- The synonym is used as an alias or alternate name for a view, table, sequence, function, procedure, etc.
- It also provides backward compatibility for existing objects or schema when you rename them.
Conclusion
We hope from this article you have understood the PostgreSQL synonyms. Actually, PostgreSQL does not support PostgreSQL but it supports Oracle. From the above article, we have learned the basic syntax of synonyms. We have also learned how we can implement them in PostgreSQL with different examples of each operation. We also learned how we can convert Oracle synonyms to PostgreSQL synonyms by using a schema conversion tool. From this article, we have learned how we can handle synonyms in PostgreSQL.
Recommended Articles
We hope that this EDUCBA information on “PostgreSQL Synonyms” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
- PostgreSQL Clustered Index
- PostgreSQL group_concat
- PostgreSQL Limit Offset
- PostgreSQL Float
PostgreSQL does not support SYNOSYM or ALIAS. Synonym is a non SQL 2003 feature implemented by Microsoft SQL 2005 (I think). While it does provide an interesting abstraction, but due to lack of relational integrity, it can be considered a risk.
That is, you can create a synonym, advertise it to you programmers, the code is written around it, including stored procedures, then one day the backend of this synonym (or link or pointer) is changed/deleted/etc leading to a run time error. I don’t even think a prepare would catch that.
It is the same trap as the symbolic links in unix and null pointers in C/C++.
But rather create a DB view and it is already updateable as long as it contains one table select only.
CREATE VIEW schema_name.synonym_name AS SELECT * FROM schema_name.table_name;
Подход 1:-
Наконец, я начал работать с использованием сторонней оболочки данных postgres_fdw, как показано ниже. У меня есть две базы данных с именами dba и dbb. У dbb есть таблица пользователей, и мне нужно получить к ней доступ в dba
CREATE SERVER myserver FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname 'dbb', port '5432');
CREATE USER MAPPING FOR postgres
SERVER myserver
OPTIONS (user 'user', password 'password');
CREATE FOREIGN TABLE users (
username char(1))
SERVER myserver
OPTIONS (schema_name 'public', table_name 'users');
CREATE FOREIGN TABLE users (users char(1));
Теперь я могу выполнить все запросы выбора / обновления в DBA.
Подход 2:- Может быть достигнуто путем создания двух схем в одном БД, ниже приведены шаги:
- создать две схемы ex app_schema, common_schema.
-
Предоставление доступа:
GRANT CREATE,USAGE ON SCHEMA app_schema TO myuser; GRANT CREATE,USAGE ON SCHEMA common_schema TO myuser; -
Теперь установите путь поиска пользователя, как показано ниже
alter user myuser set search_path to app_schema,common_schema;
Теперь таблицы в common_schema будут видны myuser. Например, допустим, у нас есть пользователь таблицы в common_schema и приложение таблицы в app_schema, тогда нижеуказанные запросы будут выполняться легко:
select * from user;
select * from app;
Это похоже на синонимы в оракуле.
Примечание. Над запросами будет работать PostgreSQL 9.5.3+.
You might have already seen our previous articles supporting Oracle to PostgreSQL and SQL server to PostgreSQL migrations. Our previous articles have provided solutions to some of the complexities during Oracle to PostgreSQL migrations. In this article, we are going to discuss about migration of synonyms from Oracle to PostgreSQL. The major reason behind this article is that the concept of SYNONYMS is not supported in Postgres. We shall now see the interesting work-arounds available in Postgres for Synonyms in Oracle.
What is a Synonym in Oracle ?
A Synonym in Oracle is an alias to a database object. This is very helpful in Oracle when a user has to access objects from different schemas without qualifying the object with its schema name. To understand the concept of Synonyms in Oracle, let us consider a simple example.
In our example, we shall consider 2 schemas S1 and S2. There exists a table named T1 in Schema : S1 and a table named T2 in Schema : S2. To join both the tables, the user of the schema : S2, has to fully qualify the table T1 of schema : S1.
SELECT T1.ID, T2.BONUS FROM S1.T1 T1 JOIN T2 ON T1.ID = T2.EMP_ID;
In some environments, there may be many such tables that belong to different schemas and a user might need to execute certain queries joining them. Each time, the user has to fully qualify the table including its schema and also have appropriate access granted to such tables individually.
A synonym in Oracle can help users create an alias in the Users schema that refers to an object in any schema. See the following syntax as an example. In the schema : S2, we can have a private synonym pointing to table T1 of Schema : S1
CREATE SYNONYM T1 FOR S1.T1;
As the synonym is now created in the schema of the user, the user can now access the table of the other schema : S2.
SELECT T1.ID, T2.BONUS FROM T1 JOIN T2 ON T1.ID = T2.EMP_ID;
Public and Private Synonyms in Oracle
A Public synonym is a synonym that is accessible to all users in an Oracle database. In order to create a public synonym, the keyword PUBLIC has to be used. A private synonym is created in the schema of the user and is only accessible to that user or any other users that are granted appropriate privileges to that object.
– Public Synonym SQL> CREATE PUBLIC SYNONYM SS1 FOR S1.T1; – Private Synonym SQL> CREATE SYNONYM SS2 FOR S1.T1;
Alternative to Synonym in PostgreSQL
An interesting point to understand is that there is no support for SYNONYM in PostgreSQL. However, it does not mean that the concept is not achievable. We can still create a work-around that allows us to achieve the exact same SYNONYM features of Oracle in PostgreSQL.
Following are the 2 approaches that can be leveraged to migrate SYNONYMs to PostgreSQL.
- Leveraging search_path to point users to objects in appropriate schemas
- Migrating Synonyms as VIEWS in PostgreSQL
Looking to Migrate from Oracle to PostgreSQL ? Contact MigOps today.
Creating an alias using search_path in PostgreSQL
In PostgreSQL, there exists a parameter called search_path. This parameter solves the purpose of avoiding qualified table names at each stage. See the following default setting for search_path to understand it in detail.
postgres=# show search_path ; search_path ----------------- "$user", public (1 row)
With the above default setting for search_path, when a user refers to an unqualified object, the object is searched within the schemas mentioned in the search_path. “$user” in this case is the user that established the connection. So, in this case, Postgres searches for the object in the schema with the same name as the user (if it exists). If the schema is not found or the object referred by the user is not found in the first schema, then, postgres searches for the object in the public schema. This is because public is the second schema mentioned in the default search_path.
See the following example where a table t1 is created in schema : s1 and a query on the unqualified table has failed.
postgres=# CREATE SCHEMA s1; CREATE SCHEMA postgres=# CREATE TABLE s1.t1 (id int); CREATE TABLE postgres=# show search_path ; search_path ----------------- "$user", public (1 row) postgres=# SELECT count(*) from t1; ERROR: relation "t1" does not exist LINE 1: SELECT count(*) from t1;
Let us set the search_path to schema : s1 and see if the query using an unqualified table name is successful.
postgres=# SET search_path TO "$user", s1, public; SET postgres=# SELECT count(*) from t1; count ------- 10 (1 row)
From the above log, it is clear that adding the schema to the search_path has helped us avoid writing a qualified table name. In the similar fashion, we can consider the above example we have used for Oracle synonyms.
postgres=# SET search_path TO "$user", s1, s2, public; SET postgres=# SELECT T1.ID, T2.BONUS FROM T1 JOIN T2 ON T1.ID = T2.EMP_ID; id | bonus ----+------- 1 | 100000 …………………………………. (10 rows)
The search_path in PostgreSQL can be set at following levels —
- Global — Applicable for all connections. Can be set by configuring search_path parameter in postgresql.conf or the other Postgres configuration files.
postgres=# ALTER SYSTEM SET search_path TO '"$user", s1, s2, public'; ALTER SYSTEM postgres=# show search_path ; search_path ------------------------- "$user", s1, s2, public (1 row)
- User — Applicable for connections established by a specific user.
In the following example, we are setting search_path to user : migops as s1, s2, public. When we now connect as user : migops, it would search for those tables in s1 and then in s2 and then in public schemas.
postgres=# ALTER USER migops SET search_path TO s1,s2,public; ALTER ROLE $ psql -d postgres -U migops -h localhost -c "select current_user, count(*) from t2" current_user | count --------------+------- migops | 10
- Session — Applicable for the specific session to which the search_path is being set.
postgres=# SET search_path TO "$user", s1, s2, public; SET postgres=# SELECT count(*) from t1; count ------- 10 (1 row)
Migrating Synonyms as Views in PostgreSQL
In certain scenarios, there may be Synonyms in Oracle created with different names when an object already exists with the same name as the object the synonym is referring to. For example, there may be a table called : T1 in schema : S1 and another table with the same name : T1 in schema : S2. In this case, we can have a Synonym created as T11 in Schema : S1 that points to table : T1 in schema : S2.
The above discussed scenario is complicated to achieve with the help of search_path. In such a case, we can have a VIEW in Postgres that could replace a Synonym in Oracle.
– Oracle Synonym CREATE SYNONYM T11 FOR S2.T1; – PostgreSQL View CREATE VIEW s1.t11 as SELECT * FROM s2.t1;
In the above example, we could see how a Synonym is rather migrated to a VIEW in PostgreSQL because of the conflict in object names.
Looking to Migrate from Oracle to PostgreSQL ? Contact MigOps today.
Conclusion
We have seen how Synonyms in Oracle can be safely migrated to PostgreSQL using multiple methods. It is easy to directly migrate Synonyms to VIEWS when compared to leveraging search_path for the same functionality. If you are using Ora2Pg or any other migration tool, most of them migrate Oracle Synonyms as Views in PostgreSQL. If you are in the process of migrating from Oracle to PostgreSQL or SQL Server to PostgreSQL and need guidance, please contact MigOps and we shall be happy to help you. You may also fill the following form and one of our team members will be in touch with you.
Как создавать и использовать синонимы на PostgreSQL, как в Oracle. Нужно ли создавать какую-либо ссылку на БД или что-то еще. Я не смог найти ни одного хорошего официального документа на эту тему.
Изменить 1
На самом деле, на данный момент у меня есть приложение, которое имеет два отдельных модуля, которые соединяются с двумя различными базами данных Oracle; Одним модулям нужен доступ к таблицам других, поэтому для оракула мы используем синонимы по db link. Сейчас мы переносим приложение в postgresql, поэтому нам нужны синонимы.
Изменить 2 Когда я говорю две разные базы данных Oracle, это означает, что это могут быть два разных экземпляра Oracle или две схемы одного и того же БД, это настраивается в приложении, и приложение должно поддерживать оба режима.
Версия PostgreSQL: 9.6.3
3 ответа
Лучший ответ
Подход 1:
Наконец, я начал работать с использованием сторонней оболочки данных postgres_fdw, как показано ниже. У меня есть две базы данных с именами dba и dbb. У dbb есть таблица пользователей, и мне нужно получить к ней доступ в dba
CREATE SERVER myserver FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname 'dbb', port '5432');
CREATE USER MAPPING FOR postgres
SERVER myserver
OPTIONS (user 'user', password 'password');
CREATE FOREIGN TABLE users (
username char(1))
SERVER myserver
OPTIONS (schema_name 'public', table_name 'users');
CREATE FOREIGN TABLE users (users char(1));
Теперь я могу выполнить все запросы выбора / обновления в DBA.
Подход 2: Может быть достигнуто путем создания двух схем в одном БД, ниже приведены шаги:
- создать две схемы ex app_schema, common_schema.
-
Предоставление доступа:
GRANT CREATE,USAGE ON SCHEMA app_schema TO myuser; GRANT CREATE,USAGE ON SCHEMA common_schema TO myuser; -
Теперь установите путь поиска пользователя, как показано ниже
alter user myuser set search_path to app_schema,common_schema;
Теперь таблицы в common_schema будут видны myuser. Например, допустим, у нас есть пользователь таблицы в common_schema и приложение таблицы в app_schema, тогда нижеуказанные запросы будут выполняться легко:
select * from user;
select * from app;
Это похоже на синонимы в оракуле.
Примечание — . Вышеупомянутые запросы будут работать в PostgreSQL 9.5.3+.
3
gajendra kumar
6 Фев 2018 в 06:14
Если предполагается, что таблицы также находятся в другой базе данных в PostgreSQL, вы должны создать чужую таблицу, используя стороннюю оболочку данных.
Если вы использовали синоним Oracle просто для того, чтобы избежать необходимости писать atable@dblink, вам не нужно ничего делать в PostgreSQL, потому что сторонние таблицы выглядят и работают так же, как локальные таблицы в PostgreSQL.
Если вы используете синоним для каких-то других целей, вы можете либо установить search_path для включения схемы, где находится целевая таблица, либо вы можете создать простое представление, которое просто выбирает все из целевой таблицы.
1
Laurenz Albe
21 Июл 2017 в 13:48
Я думаю, что вам не нужны синонимы в Postgres, как вам нужны в Oracle, потому что в отличие от Oracle, существует четкое различие между пользователем и схемой в Postgres. Это не отношение 1: 1, и несколько пользователей могут легко использовать несколько схем без необходимости полностью квалифицировать объекты, используя функцию Postgres «путь поиска» — mydb.public.mytable.
3
1ac0
21 Июл 2017 в 13:37
1 Answer
Sorted by:
Reset to default
2
That’s exactly what foreign data wrappers and foreign tables were created for:
You create a foreign server pointing to the source server, and then a foreign table that enables access to that remote server.
Some examples for that are in the description of the Postgres foreign data wrapper:
https://www.postgresql.org/docs/current/static/postgres-fdw.html
Improve this answer
answered Feb 28, 2017 at 9:29
a_horse_with_no_namea_horse_with_no_name
77.8k14 gold badges154 silver badges192 bronze badges
Add a comment
|
Your Answer
Sign up or log in
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Name
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you’re looking for? Browse other questions tagged
- postgresql
- postgresql-9.5
- dblink
- synonyms
or ask your own question.
Not the answer you’re looking for? Browse other questions tagged
- postgresql
- postgresql-9.5
- dblink
- synonyms
or ask your own question.
Здравствуйте.
Я правильно понимаю что «официального» словаря синонимов (для русского языка) и каких либо альтернативных для postgresql не существует либо они не распространены?
Интересует как для английского языка так и для русского.
-
Вопрос заданболее трёх лет назад
-
1329 просмотров





