Here is an SQL snippet:
CREATE TABLE jsonb_null (
id bigserial PRIMARY KEY,
value jsonb
);
INSERT INTO jsonb_null (value) VALUES ('"null"'), ('null'), (NULL);
SELECT id, value, jsonb_typeof(value) FROM jsonb_null ORDER BY id;
which outputs the following:
id | value | jsonb_typeof
----+--------+--------------
1 | "null" | string
2 | null | null
3 | |
(3 rows)
I want the option (2) where there's a bare null jsonb value. How can I insert this?
Here is a failing example if we use ActiveRecord to select a value. It is not necessarily related to inserting but shows the problem.
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem 'rails'
gem 'pg'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
# `CREATE DATABASE rails_test;`
ActiveRecord::Base.establish_connection(adapter: 'postgresql', database: 'rails_test')
ActiveRecord::Base.logger = Logger.new($stdout)
ActiveRecord::Base.connection.execute(<<~SQL)
DROP TABLE IF EXISTS jsonb_nulls;
CREATE TABLE jsonb_nulls (
id bigserial PRIMARY KEY,
value jsonb
);
INSERT INTO jsonb_nulls (id, value) VALUES (1, '"null"'), (2, 'null'), (3, NULL);
SQL
class JsonbNull < ActiveRecord::Base; end
class JsonbNullTest < Minitest::Test
def test_jsonb_null
refute_equal JsonbNull.find(2).value, JsonbNull.find(3).value
end
end
INSERT INTO jsonb_nulls (id, value) VALUES (1, '"null"'), (2, 'null'), (3, {});{}. This is a fine alternative, unless one actually needs the empty hash value. I know that this can be applied universally like0for integers,""for strings,[]for arrays and{}for hashes. At the same time I would like to avoid hacks and just use what Postgres provides.