CREATE EXTENSION test_lwlock_tranches;

-- Test lock tranches created with RequestNamedLWLockTranche()
SELECT test_startup_lwlocks();

-- Test creating new lock tranches with LWLockNewTrancheId()
CREATE TEMP TABLE test_tranches(tranche_name text, tranche_id int);
INSERT INTO test_tranches VALUES
    ('test_tranche_a', test_lwlock_tranche_create('test_tranche_a')),
    ('test_tranche_b', test_lwlock_tranche_create('test_tranche_b'));

-- You can create multiple tranches with the same name. It's confusing, so
-- not recommended, but test it.
INSERT INTO test_tranches VALUES
    ('test_tranche_duplicate', test_lwlock_tranche_create('test_tranche_duplicate')),
    ('test_tranche_duplicate', test_lwlock_tranche_create('test_tranche_duplicate'));

-- Check that all tranches were assigned different tranche IDs, including
-- the ones with duplicate names
select count(distinct tranche_id) from  test_tranches;

-- Test GetLWLockIdentifier() on tranches created with LWLockNewTrancheId()
select tranche_name, test_lwlock_get_lwlock_identifier(tranche_id) as lookup_result
from test_tranches;

-- negative tests
SELECT test_lwlock_tranche_create(NULL);
SELECT test_lwlock_tranche_create(repeat('a', 64));
SELECT test_lwlock_tranche_lookup('bogus');
SELECT test_lwlock_tranche_lookup('test_tranche_a');
SELECT test_lwlock_initialize(65535);

-- Test what happens when you use up all the slots.
--
-- MAX_USER_DEFINED_TRANCHES is 256. Two locks were created with
-- RequestNamedLWLockTranche() when the library was loaded, and we created
-- four more.
insert into test_tranches
    select 'test_tranche_consume_all', test_lwlock_tranche_create('test_tranche_consume_all')
    from generate_series(1, 256 - 2 - 4);

select test_lwlock_tranche_create('out-of-tranches');
