How to delete postgresql9.6 database on centos7? - postgresql-9.6

I'm am using postgresql 9.6; while deleting my mrt_210119 database, getting an error like "ERROR: database "mrt_210119" is being accessed by other users DETAIL: There is 1 other session using the database"

you cannot drop a database while clients are connected to it.
then also, if you want to drop database than you need some sql statement to run which required superuser and database owner privileges .
first make sure no one connect to database further any more by using below update statement.
UPDATE pg_database SET datallowconn = 'false' WHERE datname = 'mydb';`
Below select statement terminate all current connection which is connected to database.
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'mydb';
than drop statement-
DROP DATABASE mydb;

If you have an active connection to your database, close it. If you don't, try pkill postgres and then delete.

Related

No error on updating deleted object in rails

Rails executing update on deleted records.
I have a web app on ruby on rails in which I created some users and after that I opened the rails console and assigned U1 to one of my user let say last user then assigned the same User to U2. Then I run U1.destroy which executes successfully
after that I updated the name of user through U2 and it returns me true Although, user was destroyed from database when I checked it. My concern is rails should give me false as there was no object in database against that ID.
If you want to double check that record exists before updating you can use reload
user.reload.update(name: "Some Name")
It will raise ActiveRecord::RecordNotFound if record with such id is absent
UPDATE changes the values of the specified columns in all rows that satisfy the condition.
https://www.postgresql.org/docs/current/sql-update.html
Rails doesn't return false or raise an exception because the UPDATE is still a valid query in the database, even if no rows match the condition. If you connect directly to your PostgreSQL database and run...
UPDATE users
SET name = 'test'
WHERE id = 123
...if 123 is an id that no longer exists, then the database will successfully execute the query and respond with:
UPDATE 0
If it is an id that still exists, the database will respond with:
UPDATE 1
This is similar to how Rails behaves if you use update_all. If you were to run update_all on a record that no longer exists, you'd see something like:
User.where(id: 123).update_all(name: 'test')
=> 0
But if the record exists you'd see:
User.where(id: 123).update_all(name: 'test')
=> 1
No error will be raised.
The purpose of the Rails update and update_all methods is just to attempt to run an UPDATE query in the database. If there is a timing issue and the record no longer exists, that's not something that the database or Rails is designed to give warnings about.

PSQL command-line option to require transactions

I'd like to stop myself from doing something stupid. I'd like to tell psql to reject any DML (updates, inserts) that isn't explicitly enclosed in a transaction.
postgres=# update "employees" set salary = salary * 1.5;
ERROR: cannot update outside of a transaction
postgres=# start transaction;
START TRANSACTION
postgres=# update "employees" set salary = salary * 1.5;
UPDATE 331805
postgres=# rollback;
ROLLBACK
postgres=#
Actually, what would be almost as good (and better in some situations) for me would be an option that forbid psql from executing any DML at all.
(Yes, in a formal sense, I could just "stop doing stupid things", but you know, baby steps.)
\set autocommit off to automatically open a new transaction and not commit it immediately if you run standalone statements. This applies to all statement types.
There's no facility to prohibit or control DML separately to DDL though. To psql they're just statements.
For scripts you should also use -v ON_ERROR_STOP=1.
If you're keen you could write an ExecutorStart_hook as a C extension loaded via session_preload_libraries that checks a configuration variable (GUC) set by the psql session and uses that to ERROR if DML is attempted while still permitting DDL (which runs through ProcessUtility_hook instead). You will need basic C programming knowledge and to read the PostgreSQL manual on extensions plus some of the example extensions.
The correct answer to do this manually in psql is:
\set AUTOCOMMIT off
(Capitals, not lowercase like in the other answer)
Note: The autocommit-on mode is PostgreSQL's traditional behavior, but autocommit-off is closer to the SQL spec. If you prefer autocommit-off, you might wish to set it in the system-wide psqlrc file or your ~/.psqlrc file.

Execute stored procedure created by a different user over dblink

I have created a stored procedure PROCA in Database A with user USERA and given
execute permission to USERB and I could execute this stored proc in Database A when logged in with USERB.
Now I logged in to Database X and created a dblink Akink and this dblink conntects to
Database A with user USERB. Now when I execute stored proc using below syntax ,
it got executed without any error but whatever DML operations stored proc have done,
are not committed.
Code to invoke stored proc from Databse X
declare
begin
USERA.PROCA#Alink();
COMMIT;
end;
Please suggest what could be the issue.
It seems there are no good solutions for such situations.
But here is a suggestion for you; try using this:
Exec dbms_utility.exec_ddl_statement#db_link('some ddl sql statment');
For example:
Exec dbms_utility.exec_ddl_statement#db_link('truncate table test_tab');

Postgres Query to find whether database is read-only mode

I am new to postgres. In mysql we can check whether the database is in read-only mode by triggering the below query.
SELECT ##global.read_only
Likewise can anyone pls help me with the query to do the same in postgres? I tried few things like below
SELECT schemaname||'.'||tablename FROM pg_tables
WHERE
has_table_privilege ( 'postgres', schemaname||'.'||tablename, 'select' )
AND schemaname NOT IN ( 'pg_catalog','information_schema');
But it is listing like below which I am not expecting.
?column?
----------------------------------------
public.schema_migrations
public.credential_methods
public.notifications
public.site_defaults
public.apis
public.client_applications
public.api_groups
public.operations
public.client_application_labels
public.client_application_label_values
public.roles
public.users
public.sdm_user_roles
public.permissions_roles
public.keys
public.o_two_access_tokens
public.settings
public.sdm_users
public.permissions
public.audits
public.oauth_requesttokens
public.oauth_access_tokens
public.oauth_verifiers
public.logged_exceptions
public.api_call_details
public.api_access_roles
public.api_access_users
public.login_attempts
public.system_scopes
public.keys_system_scopes
public.o_two_auth_codes
public.o_two_refresh_tokens
public.service_profiles
public.error_traces
I also tried "\du" but this one is working only in terminal but not from a ruby file.
query=ActiveRecord::Base.connection.execute("\du;")
ActiveRecord::StatementInvalid: PGError: ERROR: syntax error at or near "du"
LINE 1: du;
Thanks,
Rafiu
You probably want something of the has_*_privilege() family function for relevant tables and relevant privileges. See here. Other than that I'm not sure if postgres has a concept of read-only mode.
Well, there's also show transaction_read_only inside a read-only transaction, but that doesn't seem to be like what you're asking for. And I don't think that transaction being readonly affects privileges of the user.
I'm not sure what you expect from your query, but if you want something boolean, as in whether you have access anywhere, you can use count(*)!=0 (and, probably, not select).
If you have a multi-node instance cluster, and you have the hot standby configuration. The output of SELECT pg_is_in_recovery() can tell you if the cluster is in the read-only mode.

How to restart id counting on a table in PostgreSQL after deleting some previous data?

I'm using PostgreSQL database on Rails 2.3.8 and I need to restart auto increment ID on my table. How can I do that?
If you truncate the table you can use the RESTART IDENTITY clause on the end.
Example:
TRUNCATE TABLE foo RESTART IDENTITY;
TRUNCATE DOCUMENTATION
You could do it in the following way:
ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY")
You can do it directly in PostgreSQL using "alter sequence": http://www.postgresql.org/docs/current/static/sql-altersequence.html
Particularly "restart with"
I don't know how you would do it via the rails abstraction.
Try:
ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
and check this answer for more details:
https://stackoverflow.com/a/7814519/1392282
Check out setval
SELECT setval('foo', 42); Next nextval will return 43
SELECT setval('foo', 42, true); Same as above
SELECT setval('foo', 42, false); Next nextval will return 42
If you want to delete all data from table and want to reset id as well then try below code.
ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name
RESTART IDENTITY")
But if some relationship is present with table and you want to delete all data from table as well as related table data then try below code.
ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name
RESTART IDENTITY CASCADE")
Thanks and
please suggest if correction needed.
You can use ActiveRecord in Rails.
You can easily do it from your rails console by running the following command:
Table_name.reset_primary_key
You can also use SQL :
TRUNCATE TABLE foo RESTART IDENTITY;

Resources