Postgresql ошибка ссылки между базами не реализованы

I am trying to convert SQL inner join query into PostgreSQL inner join query. In this inner join query which tables are using that all tables are not present in one database. we separated tables into two databases i.e. application db and security db

  1. users and permission table are present in security db
  2. userrolemapping and department are present in application db

I tried like below but I am getting following error

Error

ERROR:  cross-database references are not implemented: "Rockefeller_ApplicationDb.public.userrolemapping"
LINE 4:         INNER JOIN "Rockefeller_ApplicationDb".public.userro..

SQL Stored Function

SELECT   Department.nDeptID 
    FROM Users INNER JOIN Permission 
         ON Users.nUserID = Permission.nUserID INNER JOIN UserRoleMapping
         ON Users.nUserID = UserRoleMapping.nUserID INNER JOIN Department
         ON Permission.nDeptInst = Department.nInstID
         AND  Department.nInstID = 60
    WHERE     
         Users.nUserID = 3;

PostgreSQL Stored Function

SELECT dep.ndept_id 
        FROM "Rockefeller_SecurityDb".public.users as  u 
        INNER JOIN  "Rockefeller_SecurityDb".public.permissions p ON u.nuser_id = p.nuser_id
        INNER JOIN "Rockefeller_ApplicationDb".public.userrolemapping as urm ON u.nuser_id = urm.nuser_id
        INNER JOIN "Rockefeller_ApplicationDb".public.department dep ON p.ndept_inst = dep.ninst_id
           AND  dep.ninst_id = 60
                        WHERE     
                            u.nuser_id = 3;

Braiam's user avatar

asked Aug 10, 2018 at 10:52

SpringUser's user avatar

1

You cannot join tables from different databases.

Databases are logically separated in PostgreSQL by design.

If you want to join the tables, you should put them into different schemas in one database rather than into different databases.

Note that what is called “database” in MySQL is called a “schema” in standard SQL.

If you really need to join tables from different databases, you need to use a foreign data wrapper.

answered Aug 10, 2018 at 12:43

Laurenz Albe's user avatar

Laurenz AlbeLaurenz Albe

211k17 gold badges207 silver badges266 bronze badges

8

For future searchs, you can to use dblink to connect to other database.

Follow commands:

create extension dblink;

SELECT dblink_connect('otherdb','host=localhost port=5432 dbname=otherdb user=postgres password=???? options=-csearch_path=');

SELECT * FROM dblink('otherdb', 'select field1, field2 from public.tablex')
AS t(field1 text, field2 text);

answered Jul 22, 2020 at 11:58

rafaelnaskar's user avatar

New to postrgreSQL and I had the same requirement. FOREIGN DATA WRAPPER did the job.

IMPORT FOREIGN SCHEMA — import table definitions from a foreign server

But first I had to:

  1. enable the fdw extension

  2. define the foreign server (which was the locahost in this case!)

  3. create a mapping between the local user and the foreign user.

CREATE EXTENSION postgres_fdw;

CREATE SERVER localsrv
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'localhost', dbname 'otherdb', port '5432');

CREATE USER MAPPING FOR <local_user>
SERVER localsrv
OPTIONS (user 'ohterdb_user', password 'ohterdb_user_password');

IMPORT FOREIGN SCHEMA public
FROM SERVER localsrv 
INTO public;

After that I could use the foreign tables as if they were local. I did not notice any performance cost.

Jeremy Caney's user avatar

Jeremy Caney

7,12471 gold badges48 silver badges77 bronze badges

answered Dec 6, 2021 at 20:40

Antony Economou's user avatar

In my case, I changed my query from:

SELECT * FROM myDB.public.person

to this:

SELECT * FROM "myDB".public.cats

and it worked.

You can read more at mathworks.com.

Timothy Alexis Vass's user avatar

answered Feb 20, 2022 at 9:57

Behnam's user avatar

BehnamBehnam

1,0492 gold badges14 silver badges39 bronze badges

I’m trying to create a database and then create a table in it. I wrote the query in an sql file to go with the postgres image using docker-compose.yml

When I to use docker-compose build and then docker-compose up I get an error

«psql:/docker-entrypoint-initdb.d/init.sql:18: ERROR: cross-database references are not implemented: «real_estate.public.estate»
postgres | LINE 1: CREATE TABLE real_estate.public.estate («

Here is my init.sql file

CREATE DATABASE "real_estate"
    WITH OWNER "postgres"
    ENCODING 'UTF8';
CREATE TABLE real_estate.public.estate (
    estate_title TEXT,
    estate_address TEXT,
    estate_area TEXT,
    estate_description TEXT,
    estate_price TEXT,
    estate_type TEXT,
    estate_tag TEXT,
    estate_date TEXT,
    estate_seller_name TEXT,
    estate_seller_address TEXT,
    estate_seller_phone TEXT,
    estate_seller_mobile TEXT,
    estate_seller_email TEXT
 );

Alejandro Galera's user avatar

asked Aug 2, 2018 at 2:48

Zerontelli's user avatar

You get that error because you are not connected to the real_estate database.

I assume that you are connected to postgres, because that’s what you typically do to run CREATE DATABASE.

You’ll have to terminate the existing database connection and then start one to the newly created database. Only then you are allowed to create objects in the database.

It is a feature that different databases are strictly separated, and any request to change that will be turned down.

How to do this best depends on how you run the script. If you run it with psql, a simple \c real_estate would do.

answered Aug 2, 2018 at 8:18

Laurenz Albe's user avatar

Laurenz AlbeLaurenz Albe

211k17 gold badges207 silver badges266 bronze badges

1

Есть таблица artist и user_artist

artist:
- id (PK)
- name
user_artist:
- id (PK)
- userId(FK)
- artistId(FK)
- added

Следующий запрос возвращает ошибку

ссылки между базами не реализованы: user_artist.added

return db.query(`
                SELECT artist.name  AS "artistName", artist.id AS "artistId", user_artist.added
                FROM user_artist
                INNER JOIN artist
                ON artist.id = user_artist."artistId"
                WHERE user_artist."userId" = $(userId) 
                AND user_artist.added::timestamp < to_timestamp($(index) / 1000)
                ORDER BY user_artist.added $(order)
                LIMIT $(limit);`, obj);

Если убрать ORDER BY user_artist.added $(order) то ошибка исчезает.
Вот точная структура таблица user_artist

create table user_artist
(
  "id" serial primary key,
  "userId" serial REFERENCES user (id) on delete cascade,
  "artistId" serial REFERENCES artist (id) on delete cascade,
  "added" timestamp,
  unique ("userId", "artistId")
);

Что не так?

Introduction

The restore process which is focusing only into the execution of an insert statement ended in a failure. Actually, there is an SQL file containing hundreds of records or rows available as values for insert query in its associated columns.  But the process for importing those records or row data fail because of a certain cause. The following is the execution of the process for importing records or row data from an SQL file with the name of ‘insert-active-employee.sql’ :

C:\>psql -Udb_user -d db_app < "C:\Users\Personal\Downloads\insert-active-employee.sql" 
Password for user db_user: ERROR: cross-database references are not implemented: "main.dbo.employee" 
LINE 1: INSERT INTO main.dbo.employee (name,birthdate,address... 
^

Solution

Actually, the solution for solving the above problem is very simple. It exist in the name of the database which is being the target for the import process. There is no cross-reference database in this context. The SQL file actually exist as the process from Microsoft SQL Server backup or SQL insert statement generated process. In other words, the SQL file source is from Microsoft SQL Server. But the target for the restore process is not a Microsoft SQL Server. Instead, it is a PostgreSQL database server as the target of the database. The solution is very simple, just replace the cross-database references above with another suitable format.

So, check the database PostgreSQL name and then look up for the table. Actually in the command for restoring or importing the records or the row data, the database name is already becoming part of the value from one of the argument. The argument exist in ‘-d db_app’ where the database name is ‘db_app.

The only part left is to edit the SQL file further. Just replace the cross-database references exist in the above which is ‘main.dbo.employee’ into a name of a table from the database ‘db_app’. In this context as an example it is ”. The following is the pattern of the INSERT statement available in the SQL file before the editing process :

INSERT INTO main.dbo.employee (name,birthdate,address...  VALUES(...,,,)

Following after, below is the actual content of the SQL file after the editing process :

INSERT INTO public.org_employee (name,birthdate,address...  VALUES(...,,,)

Since, PostgreSQL has a default schema of ‘public’, so the definition of the table will have a reference of ‘public.org_employee’ where ‘org_employee’ is the name of the table itself. After editing it, just execute it once more and the INSERT query process will be proceed normally if there are no more errors exist.

  • Yes the tabel ( product ) in the public schema
  • postgreSQL version : postgresql-9.2.1-1-windows-x64
  • The following is restsql.properties file:

logging.facility=log4j
logging.config=resources/properties/log4j.properties
logging.dir=/geronimo/geronimo-tomcat7-javaee6-web-3.0.0-bin/var/log

sqlresources.dir=sqlresources

request.useXmlDirective=false
request.useXmlSchema=false
response.useXmlSchema=false
response.useXmlDirective=false

database.driverClassName=org.postgresql.Driver
database.url=jdbc:postgresql://localhost:5432/jeisDB
database.user=testUser
database.password=testUsers

org.restsql.core.SqlResourceMetaData=org.restsql.core.impl.SqlResourceMetaDataPostgreSql

org.restsql.core.Factory.RequestFactory=org.restsql.core.impl.RequestFactoryImpl
org.restsql.core.Factory.RequestDeserializerFactory=org.restsql.core.impl.RequestDeserializerFactoryImpl
org.restsql.core.Factory.ResponseSerializerFactory=org.restsql.core.impl.ResponseSerializerFactoryImpl
org.restsql.core.HttpRequestAttributes=org.restsql.core.impl.HttpRequestAttributesImpl
org.restsql.core.RequestLogger=org.restsql.core.impl.RequestLoggerImpl
org.restsql.core.SqlBuilder=org.restsql.core.impl.SqlBuilderImpl
org.restsql.security.Authorizer=org.restsql.security.impl.AuthorizerImpl

  • The following is the product.xml file:
    xml version=»1.0″ encoding=»UTF-8″?
    rs:sqlResource xmlns:rs=»http://restsql.org/schema» xmlns:xsi=»http://www.w3.org/2001/XMLSchema-instance» xsi:schemaLocation=»http://restsql.org/schema SqlResource.xsd «
    query
    SELECT productid «id», name «thisName» FROM product
    /query
    metadata
    database default=»jeisDB» table role=»Parent» name=»product»

    /metadata
    /rs:sqlResource

Понравилась статья? Поделить с друзьями:
  • Postgresql ошибка синтаксиса примерное положение select
  • Powershell продолжить выполнение скрипта при ошибке
  • Postgresql ошибка при запуске
  • Powershell подавить вывод ошибок
  • Postgresql вывод сообщения об ошибке