How to unset (remove,not reset) a custom config parameter? - postgresql

I am using set_config to set some context on the session (i.e user context).
Once I set the context for a parameter - I can't seem to get rid of it. RESET/SET param TO DEFAULT will empty the value but not remove it altogether.
select current_setting('my.test1'); -- SQL Error [42704]: ERROR: unrecognized configuration parameter "my.test1"
select set_config('my.test1','123',false);
select current_setting('my.test1'); -- returns 123
set my.test1 to default; --same as reset my.test1
select current_setting('my.test1'); --returns an empty string rather than an exception
How to remove it (raise exception again) ?
I am catching 42704 but it won't be thrown if I just "reset" it.
p.s I assume pg_reload_conf might help - but it seems too aggressive for this simple task.
Thanks.

The answer is that you cannot (in postgres 10), if you are in the same session.
Those empty parameters ONLY go away if you exit the session and open a new session. pg_reload_conf() has no effect on the custom variables that have been set in a session, or local to a transaction, and doesn't work to remove the parameter. They just stay as '' ... empty string.
For me this is a very legitimate question and issue also ...
i have been finding the same behaviour with custom ( ie name_one.name_two ) configuration parameters, whilst i've been developing a configuration setting wrapper to overlay into individual schemas.
Once the parameter has been set locally with eg set_config ( _name_ , _value_ , TRUE ) OR at session level with set_config ( _name_ , _value_ , FALSE) ... it is not removed if set to NULL or UNSET or to DEFAULT ... there is no way around this i have found, after testing and testing and questioning my own perception of my slightly nested functions and scoping ... and so my only answer has been to alter one of my pure SQL language functions to PLPGSQL and make a test for the particlular parameter that i was relying on as being not existing, because my call that allows missing_ok : current_setting ( '_pre._global_int_' , TRUE )does not return NULL if at some point earlier in any transaction in the session it has been set locally or not locally !!!
It had been frustrating me also, and i was very happy to find that this question had already been asked, and so here i give the answer :
it cannot be done in the same session in PG 10
( i have not tried it yet in 11 or 12 or 13 )
UPDATE :
i just found this answer, https://stackoverflow.com/a/50929568/14653862, of Laurenz Albe, which also says that in the same session you cannot

Related

Why does this result in a "org.postgresql.util.PSQLException: The column index is out of range" exception?

I'm trying to run a function in a PostgreSQL 11 server from Ignition (8.0.16) as a named-query and getting a column index error. Everywhere that has discussed this error with regards to Postgres shows it is an issue of the parameters provided and expected not matching in number.
It always shows as one more than the number provided as being out of range. Even when changed to use a different number of parameters.
I count 13 everywhere: Ignition parameters, test parameters, the function call in Ignition, the function definition, the table. Here is the function call from Ignition:
SELECT insert_run_data(
:speed_in,
:avg_speed_in,
:coater_num_in,
:coater_op_in,
:finisher_in,
:helper1_in,
:helper2_in,
:coater_down_in,
:current_downtime_reason_in,
:hanging_downtime_reason_in,
:tabcode_in,
:start_time_in,
:end_time_in
);
In the same named-query window, if I comment out the function call and try to write directly using the same parameters, it writes without issue:
insert into
nh_coater_tabcode_operator_data(
speed, avg_speed, coater_num, coater_op, finisher, helper1,
helper2, coater_down, current_downtime_reason,
hanging_downtime_reason, tabcode, start_time, end_time
)
values(:speed_in, :avg_speed_in, :coater_num_in, :coater_op_in,
:finisher_in, :helper1_in, :helper2_in, :coater_down_in,
:current_downtime_reason_in, :hanging_downtime_reason_in, :tabcode_in,
:start_time_in, :end_time_in
);
The function also runs fine from within PGAdmin.
Here are gists showing the SQL used to create the table and function, the stack trace from Ignition, and an image showing the named-query authoring window parameters matching:
create function gist
create table gist
stack trace of error gist
parameters in Ignition
The Ignition Designer seems to cache the function. So, if it is changed, you will need to save and reopen the project: open another then switch back or close and open a new designer window.

Add a missing key to JSON in a Postgres table via Rails

I'm trying to use update_all to update any records that is missing a key in a JSON stored in a table cell. ids is the ids of those records and I've tried the below...
User.where(id: ids).
update_all(
"preferences = jsonb_set(preferences, '{some_key}', 'true'"
)
Where the error returns is...
Caused by PG::SyntaxError: ERROR: syntax error at or near "WHERE"
LINE 1: ...onb_set(preferences, '{some_key}', 'true' WHERE "user...
The key takes a string value so not sure why the query is failing.
UPDATE:
Based on what was mentioned, I added the parentheses and also added / modified the last two arguments...
User.where(id: ids).
update_all(
"preferences = jsonb_set(preferences, '{some_key}', 'true'::jsonb, true)"
)
still running into issues and this time it seems related to the key I'm passing
I know this key doesn't currently exist for the set of ids
I added true for create_missing so that 1 isn't an issue
I get this error now...
Caused by PG::UndefinedFunction: ERROR: function jsonb_set(hstore, unknown, jsonb, boolean) does not exis
some_key should be a key in preferences
You're passing in raw SQL so you are 100% responsible for ensuring that is actually valid SQL. What you have there isn't. Check your parentheses:
User.where(id: ids).
update_all(
"preferences = jsonb_set(preferences, '{some_key}', 'true')"
)
If you look more closely at the error message it was telling you there was a problem precisely at the introduction of the WHERE clause, and right after ...true' so that was a good place to look for problems.
Syntax errors like this can be really annoying, but don't forget your database will usually do its best to pin down the place where the problem occurs.

How to get permission to change run-time parameter?

In this wonderful answer is proposed GUC-pattern to use run-time parameters to detect current user inside trigger (as one solution). It seemed to suit to me too. But problem is: when I declare the variable in postgresql.conf it is usable inside trigger and I can access it from queries, but can't change it:
# SET rkdb.current_user = 'xyzaaa';
ERROR: syntax error at or near "current_user"
LINE 1: SET rkdb.current_user = 'xyzaaa';
The error message is misleading, so I did not dig it a while, but now it seems this user (database owner) has no permissions to change params set in global configuration.
I can set any other params:
# SET jumala.kama = 24;
SET
And read it back:
# SHOW jumala.kama;
jumala.kama
-------------
24
(1 row)
I can't SHOW globally set params:
# SHOW rkdb.current_user;
ERROR: syntax error at or near "current_user"
LINE 1: SHOW rkdb.current_user;
^
but I can reach it with current_setting() function:
# select current_setting('rkdb.current_user');
current_setting
-----------------
www
(1 row)
So my guess is, my database owner does not have permissions to access this param. How could I:
set needed permissions?
or even better
set run-time params with database owner rights?
current_user is an SQL standard function, so your use of that name confuses the parser.
Either use a different name or surround it with double quotes like this:
rkdb."current_user"

Transact-SQL DEFAULT keyword deprecated? Why?

In MSDN article
Deprecated Database Engine Features in SQL Server 2016
there is a statement on deprecation of DEFAULT keyword (among the others).
Quoted from the table:
Category: Transact-SQL
Deprecated feature: Use of DEFAULT keyword as default value.
Replacement: Do not use the word DEFAULT as a default value.
Feature name: DEFAULT keyword as a default value.
Feature ID: 187.
What is the logic behind this change? I find nothing wrong with
CREATE FUNCTION dbo.GetFirstIdByCode(#Code nvarchar(20), #ExcludeThisId int)
and in most cases, where I don't use 2nd parameter, call it like
IF dbo.GetFirstIdByCode(#Id, DEFAULT) = 0 --- etc...
Of course, I can replace DEFAULT with NULL at every call of the function. To me, this looks like anything but a progress. Why is this planned?
How should I adjust my coding style preparing for this?
The wording was incorrect:Erland raised a connect item for this..please see this connect for more details..
Pasting relevant items from connect item:
Depreceated feature is ..
using the word DEFAULT as the DEFAULT value.
Example:
CREATE TABLE T1
(Col1 int PRIMARY KEY,
Status varchar(10) DEFAULT 'DEFAULT' )
or
CREATE DEFAULT phonedflt AS 'DEFAULT'

I can create a stored procure with invalid user defined function names in it

I just noticed that I could alter my stored procedure code with a misspelled user defined function in it.
I noticed that at 1st time I execute the SP.
Is there any way to get a compile error when an SP include an invalid user-defined function name in it?
At compile time? No.
You can, however, use some of SQL's dependency objects (if using MS SQL) to find problems just after deployment, or as part of your beta testing. Aaron Bertran has a pretty nice article rounding up the options, depending upon the version of SQL Server.
Here is an example using SQL Server 2008 sys object called sql_expression_dependencies
CREATE FUNCTION dbo.scalarTest
(
#input1 INT,
#input2 INT
)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE #ResultVar int
-- Add the T-SQL statements to compute the return value here
SELECT #ResultVar = #input1 * #input2
-- Return the result of the function
RETURN #ResultVar
END
GO
--Fn Works!
SELECT dbo.ScalarTest(2,2)
GO
CREATE PROCEDURE dbo.procTest
AS
BEGIN
SELECT TOP 1 dbo.scalarTest(3, 3) as procResult
FROM sys.objects
END
GO
--Sproc Works!
EXEC dbo.procTest
GO
--Remove a dependency needed by our sproc
DROP FUNCTION dbo.scalarTest
GO
--Does anything have a broken dependency? YES
SELECT OBJECT_NAME(referencing_id) AS referencing_entity_name,
referenced_entity_name, *
FROM sys.sql_expression_dependencies
WHERE referenced_id IS NULL --dependency is missing
GO
--Does it work? No
EXEC dbo.procTest
GO