Postgres Query to find whether database is read-only mode - ruby-on-rails

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.

Related

Sybase database - Issue running stored proc

I am trying to run a stored proc "dbname..rr_deck_type_wrap_proc" through SQLDeveloper worksheet using the following code:
declare #return int, #message varchar(255)
exec #return = DBname..rr_deck_type_wrap_proc
#new_id = '123456789',
#remarks = 'Test',
#error_cd = #message output
select #return "#return", #message "#message"
However, I always get the message:
Error report - Invalid JDBC escape syntax at line position 22 '='
character expected.
This code works perfectly fine when run through another software/interface. It is probably a syntax issue with SQLDeveloper, tried different things but nothing worked. Can someone suggest anything. Thank you!
You're using 'Oracle SQL Developer' - the keyword there, being 'Oracle.'
You're connected to a SAP Sybase database. Which is perfectly fine. We provide this connectivity support for one reason, and one reason only:
To allow you to migrate it to Oracle Database.
It is NOT a T-SQL IDE. It does not provide any support really for running, debugging, playing with T-SQL.
If you have ANSI-SQL, then our parser will probably be OK with it.
If you need/want a hack, and are desperate to make your code go, then you can provide a hint to our parser, to just let the code go through to the driver, and hope it works.
An example:
/sqldev:query*/sp_help;
You could also try adding this
/*sqldev:stmt*/
This advice applies to MySQL, DB2, SQL Server, Teradata, or any other 3rd party JDBC driver we allow you to use in SQL Developer. It's there to help you move your schema and application code over into an Oracle Database.

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.

neo4jrb how to reset transaction timeout of an open transaction

Currently using neo4j-community-2.1.7
I understand that the facility has been included in this version.
Have been unable to find any reference to it in the ruby docs.
Would appreciate it very much if I may have some direction on how to reset the timeout using neo4jrb.
Regards
Ross
I am unaware of a way to reset the transaction timeout of an open transaction. Maybe someone more familiar with transactions in the Java API can clarify.
If you want to change the transaction timeout length at boot, that's handled in neo4j-server.properties as described at http://neo4j.com/docs/stable/server-configuration.html.
Within Neo4j-core, if using Neo4j-community or Neo4j-enterprise (and therefore Neo4j Embedded) the code suggests that you can specify a config file by giving a third argument to Neo4j::Session.open, a hash that contains config options. That method, if given :embedded_db as its first arg, will call Neo4j::Embedded#initialize and give that hash as an argument. If you do something like this:
Neo4j::Session.open(:embedded_db, 'path_to_db', properties_file: 'path_and_filename_to_neo4j-server.properties')
It will eventually use that properties file:
db_service.loadPropertiesFromFile(properties_file) if properties_file
This is not demonstrated in any of the specs, unfortunately, but you can see it in the initialize and start methods at https://github.com/neo4jrb/neo4j-core/blob/230d69371ed6bf39297786155ef4f3b1831dac08/lib/neo4j-embedded/embedded_session.rb.
RE: COMMENT INFO
If you're using :server_db, you don't need to include the neo4j-community gem. It isn't loaded, it isn't compatible with Neo4j in Server mode.
That's the first time I've seen the link you provided, good to know that's there. We don't expose a way to do that in Neo4j.rb and won't because it would require some threading magic that we can't support. If you want to do it manually, the best I can tell you is that you can get a current transaction ID this way:
tx = Neo4j::Transaction.new
# do stuff and before your long-running query...
tx.resource_data[:commit].split('/')[-2]
That will return the transaction number that you can use in POST as described in their support doc.
If you'd like help troubleshooting your long-running Cypher query, I'm sure people on SO will help.

How can I figure out where all these extra sqlite3 selects are being generated in my rails app?

I'm trying to figure out where a whole pile of extra queries are being generated by my rails app. I need some ideas on how to tackle it. Or, if someone can give me some hints, I'd be grateful.
I get these:
SQL (1.0ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
SQL (0.8ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
SQL (0.8ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
repeated over and over on every request to the DB (as much as 70 times for a single request)
I tried installing a plugin that traced the source of the queries, but it really didn't help at all. I'm using the hobofields gem, dunno if that is what's doing it but I'm somewhat wedded to it at the moment
Any tips on hunting down the source of these extra queries?
Have a look at ActiveRecord gem in connection_adapters/sqlite_adapter.rb on line 173 (I'm using ActiveRecord 3.0.7) you have a function called tables that generates the exact query you posted:
SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
In development mode this function gets called for every table from your database, on every request.
In production this function gets called only once, when the server starts, and the result is cached.
In development for each request rails looks into your database to see what columns each table has so it can generate methods on your models like "find_by_name". Since in production is unlikely that your database changes, rails does this lookup only on server start.
It's very difficult to tell this without look into the Code.
but i am sure you write your query in a certain loop
for i in 0..70
SqliteMaster.find(:all, :conditions=>["type=? and not name=?", 'table', 'sqlite_sequesnce'])
end
So my advice is that to check all the methods which gets called after requesting certain method and look whether the query called in a loop.
I've just seen this appearing in my logs when I do a search with the metasearch gem but ONLY in development mode.
I believe that it is caused by the plugin acts-as-taggable-on.
It will check if the table or the cache column exists.

Saving updates to objects in rails

I'm trying to update one of my objects in my rails app and the changes just don't stick. There are no errors, and stepping through with the debugger just reveals that it thinks everything is updating.
Anyway, here is the code in question...
qm = QuestionMembership.find(:first, :conditions => ["question_id = ? AND form_id = ?", q_id, form_id])
qm.position = x
qm.save
For reference sake, QuestionMembership has question_id, form_id, and position fields. All are integers, and have no db constraints.
That is basically my join table between Forms and Questions.
Stepping through the code, qm gets a valid object, the position of the object does get changed to the value of x, and save returns 'true'.
However, after the method exits, the object in the db is unchanged.
What am I missing?
You may not be finding the object that you think you are. Some experimenting in irb might be enlightening.
Also, as a general rule when changing only one attribute, it's better to write
qm.update_attribute(:position, x)
instead of setting and saving. Rails will then update only that column instead of the entire row. And you also get the benefit of the data being scrubbed.
Is there an after_save?
Is the correct SQL being emitted?
In development log, you can actually see the sql that is generated.
For something like this:
qm = QuestionMembership.find(:first, :conditions => ["question_id = ? AND form_id = ?", q_id, form_id])
qm.position = x
qm.save
You should see something to the effect of:
SELECT * FROM question_memberships WHERE question_id=2 AND form_id=6 LIMIT 1
UPDATE question_memberships SET position = x WHERE id = 5
Can you output what sql you are actually seeing so we can compare?
Either update the attribute or call:
qm.reload
after the qm.save
What is the result of qm.save? True or false? And what about qm.errors, does that provide anything that makes sense to you? And what does the development.log say?
I have run into this problem rather frequently. (I was about to say consistently, but I cannot, as that would imply that I would know when it was about to happen.)
While I have no solution to the underlying issue, I have found that it seems to happen to me only when I am trying to update mysql text fields. My workaround has been to set the field to do something like:
qm.position = ""
qm.save
qm.position = x
qm.save
And to answer everyone else... when I run qm.save! I get no errors. I have not tried qm.save?
When I run through my code in the rails console everything works perfectly as evidenced by re-finding the object using the same query brings the expected results.
I have the same issue when using qm.update_attribute(... as well
My workaround has gotten me limping this far, but hopefully someone on this thread will be able to help.
Try changing qm.save to qm.save! and see if you get an exception message.
Edit: What happens when you watch the log on the call to .save!? Does it generate the expected SQL?
Use ./script/console and run this script.. step by step..
see if the position field for the object is update or not when you run line 2
then hit qm.save or qm.save!... to test
see what happens. Also as mentioned by Tim .. check the logs
Check your QuestionMembership class and verify that position does not have something like
attr_readonly :position
Best way to debug this is to do
tail -f log/development.log
And then open another console and do the code executing the save statement. Verify that the actual SQL Update statement is executed.
Check to make sure your database settings are correct. If you're working with multiple databases (or haven't changed the default sqlite3 database to MySQL) you may be working with the wrong database.
Run the commands in ./script/console to see if you see the same behavior.
Verify that a similar object (say a Form or Question) saves.
If the Form or Question saves, find the difference between the QuestionMembership and Form or Question object.
Turns out that it was emitting the wrong SQL. Basically it was looking for the QuestionMembeship object by the id column which doesn't exist.
I was under the impression that that column was unnecessary with has_many_through relationships, although it seems I was misguided.
To fix, I simply added the id column to the table as a primary key. Thanks for all the pointers.

Resources