0

I want to simulate a distributed database, so I am generating 10 isolated databases, 3 replicas each, for a total of 30 database instances. I am doing this all locally for the moment, and am running something like this:

drop database if exists ddsjs_test_1_replica_1;
drop database if exists ddsjs_test_2_replica_1;
drop database if exists ddsjs_test_3_replica_1;
drop database if exists ddsjs_test_4_replica_1;
drop database if exists ddsjs_test_5_replica_1;
drop database if exists ddsjs_test_6_replica_1;
drop database if exists ddsjs_test_7_replica_1;
drop database if exists ddsjs_test_8_replica_1;
drop database if exists ddsjs_test_9_replica_1;
drop database if exists ddsjs_test_10_replica_1;

create database ddsjs_test_1_replica_1;
create database ddsjs_test_2_replica_1;
create database ddsjs_test_3_replica_1;
create database ddsjs_test_4_replica_1;
create database ddsjs_test_5_replica_1;
create database ddsjs_test_6_replica_1;
create database ddsjs_test_7_replica_1;
create database ddsjs_test_8_replica_1;
create database ddsjs_test_9_replica_1;
create database ddsjs_test_10_replica_1;

...

How do I make this dynamic in SQL for Postgres? Like looping and incrementing i?

1
  • Not sure how you would do this in SQL as you can't create a database within a transaction which you would likely need as part of the incrementing number. You could wrap this in a scripting language script. Commented Feb 13, 2022 at 20:43

1 Answer 1

1

Sample Function:

CREATE OR REPLACE FUNCTION create_databases_dynamic()
RETURNS bool 
LANGUAGE plpgsql
AS $function$
declare
    v_index integer;
    sql_drop text;
    sql_create text;
begin
    
    sql_drop   = 'drop database if exists ddsjs_test_%s_replica_1'; 
    sql_create = 'create database ddsjs_test_%s_replica_1';
    
    for v_index in 1..10 
    loop
        EXECUTE format(sql_drop, v_index);
        EXECUTE format(sql_create, v_index);
    end loop;

    return true; 

END;
$function$;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.