Wednesday, August 10, 2011

mysql execute immediate

I had a requirement to generate a sharded schema where no of shards and no of tables in the shard were dynamic. Basically we wanted to shard one table so we ended up creating 8 schemas and each schema will hold 8 tables that are copy of the same schema. Now I didnt wanted to hand write the 64 table/schema creation statement so came up with this procedure that allows to dynamically build and execute sql queries.  Oracle was so easy, mysql is a little bit verbose.


    drop procedure if exists create_rdb_tables;
    delimiter #
    create procedure create_rdb_tables()
    begin
    declare v_max int unsigned default 9;
    declare v_counteri int unsigned default 1;
    declare v_counterj int unsigned default 1;
      while v_counteri < v_max do
        while v_counterj < v_max do
            set @sql_text := concat('drop table if exists metadata_rdb_schema',v_counteri, '.metadata_rdb_t', v_counterj,';');
            prepare stmt from @sql_text;
            execute stmt;
            DEALLOCATE PREPARE stmt;
    
            set @sql_text := concat('CREATE TABLE metadata_rdb_schema',v_counteri, '.metadata_rdb_t', v_counterj, ' (user_id INT NOT NULL, object_id VARCHAR(255) NOT NULL,group_id VARCHAR(36) NOT NULL,entry_id VARCHAR(36) NOT NULL,created_time DATETIME NOT NULL, primary key(object_id))TYPE=innodb;');
            prepare stmt from @sql_text;
            execute stmt;
            DEALLOCATE PREPARE stmt;
            set v_counterj=v_counterj+1;
        end while;
       set v_counteri=v_counteri+1;
      end while;
    end #
    delimiter ;
    call create_rdb_tables();
    drop procedure if exists create_rdb_tables; 



Finally it started becoming messy and kludgy so I ended up writing clean python code to generate the ddl :). This effort was a waste but I ended up learning how to do dynamic sql execution in mysql.

No comments:

Post a Comment