5

How do I get the username on the current layer PostGIS in QGIS 3.16.2-Hannover? We tried examples: Getting active PostgreSQL connection username when stored through authentication configuration in QGIS 3, but they don't work.

When running this script, variable username is empty:

layer = iface.activeLayer()
provider = layer.dataProvider()
username = QgsDataSourceUri(provider.dataSourceUri()).username()
print (username)

This is result of provider.dataSourceUri()):

<QgsDataSourceUri: dbname='postgres' host= localhost port=5432 sslmode=disable key='id' srid=4326 type=Point checkPrimaryKeyUnicity='1' table="locations"."airlines" (geom)>

The value of the username is missing, the question is how to get the username for the current layer?

10
  • 1
    What does "they don't work" mean?
    – Ian Turton
    Commented Jan 9, 2021 at 18:55
  • 1
    I have tried it as well. I got also username is empty but the reason (in my case) I am connected with local credentials so there is no user and psw. Can you check if you see the 'user' when you print out provider.dataSourceUri()?
    – Nil
    Commented Jan 10, 2021 at 13:39
  • I don't understand: you are referring to a question that gives you the solution, doesn't it ?
    – dd_a
    Commented Jan 10, 2021 at 16:33
  • the solution to the question I am referring to does not answer my question. Function - QgsDataSourceUri(provider.dataSourceUri()).username() return empty string Commented Jan 11, 2021 at 8:05
  • 1
    @AndreySirbu what does it return if you call only provider.dataSourceUri()??
    – Nil
    Commented Jan 11, 2021 at 8:11

2 Answers 2

0

You can select your PostgreSQL user using the 'PostgreSQL Execute SQL' command in the Processing toolbox.

Query:

SELECT user;

enter image description here

2
  • how to get user name from script? Commented Aug 13, 2021 at 7:50
  • How to use python function? Commented Oct 18, 2023 at 5:17
0

Maybe this have changed since version 3.16 but in 3.32 you can simply do:

layer = iface.activeLayer()
print(layer.source())
#dbname='data' host=localhost port=5432 user='postgres' 
#sslmode=disable key='id' estimatedmetadata=true srid=3006 
#type=MultiPolygon checkPrimaryKeyUnicity='1' table="lmv"."ok_ak_riks" (geom)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.