ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

PL/pgSQL Dynamic SQL for Schema Migration

PL/pgSQL

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE OR REPLACE FUNCTION add_column_to_tables_by_pattern(
2p_pattern VARCHAR,
3p_column_name VARCHAR,
4p_column_type VARCHAR,
5p_default_value TEXT DEFAULT NULL
6) RETURNS VOID AS $$
7DECLARE
8v_table_name TEXT;
9v_sql TEXT;
10v_column_exists BOOLEAN;
11cur_tables CURSOR FOR
12SELECT tablename
13FROM pg_tables
14WHERE schemaname = current_schema()
15AND tablename LIKE p_pattern;
16BEGIN
17OPEN cur_tables;
18LOOP
19FETCH cur_tables INTO v_table_name;
20EXIT WHEN NOT FOUND;
21
22-- Check if the column already exists in the table
23SELECT EXISTS (
24SELECT 1
25FROM information_schema.columns
26WHERE table_schema = current_schema()
27AND table_name = v_table_name
28AND column_name = p_column_name
29) INTO v_column_exists;
30
31IF NOT v_column_exists THEN
32-- Construct the dynamic SQL statement
33v_sql := format(
34'ALTER TABLE %I ADD COLUMN %I %s',
35v_table_name,
36p_column_name,
37p_column_type
38);
39
40-- Add default value if provided
41IF p_default_value IS NOT NULL THEN
42v_sql := v_sql || format(' DEFAULT %s', p_default_value);
43END IF;
44
45RAISE NOTICE 'Executing: %', v_sql;
46EXECUTE v_sql;
47ELSE
48RAISE NOTICE 'Column % already exists in table %.', p_column_name, v_table_name;
49END IF;
50END LOOP;
51CLOSE cur_tables;
52END;
53$$ LANGUAGE plpgsql;
Algorithm description viewbox

PL/pgSQL Dynamic SQL for Schema Migration

Algorithm description:

This PL/pgSQL function automates schema modifications by dynamically generating and executing `ALTER TABLE` statements. It targets tables matching a specified pattern, adds a new column with a given type, and optionally assigns a default value. Crucially, it first checks if the column already exists in each table to prevent errors and redundant operations. This is invaluable for managing database schema evolution across multiple tables consistently and efficiently, especially in large or complex database environments.

Algorithm explanation:

The function `add_column_to_tables_by_pattern` uses a cursor (`cur_tables`) to iterate through table names in the current schema that match the provided `p_pattern`. For each table, it queries `information_schema.columns` to check if `p_column_name` already exists. If the column does not exist, it constructs an `ALTER TABLE` statement using `format()` for safe identifier quoting (`%I`). The `p_column_type` is directly appended, and if `p_default_value` is provided, it's appended using `format()` as well. The generated SQL is then executed using `EXECUTE`. The time complexity is roughly O(T * (C + E)), where T is the number of tables matching the pattern, C is the cost of checking column existence (querying `information_schema`), and E is the cost of executing the `ALTER TABLE` statement. Space complexity is O(1) for variables, plus the space for the dynamic SQL string.

Pseudocode:

FUNCTION add_column_to_tables_by_pattern(pattern, column_name, column_type, default_value):
  DECLARE cursor FOR SELECT tablename FROM pg_tables WHERE schemaname = current_schema() AND tablename LIKE pattern

  OPEN cursor
  LOOP:
    FETCH cursor INTO table_name
    IF NOT FOUND:
      EXIT LOOP

    CHECK IF column_name EXISTS in table_name (using information_schema)

    IF column_name DOES NOT EXIST:
      sql_statement = 'ALTER TABLE ' + quote_identifier(table_name) + ' ADD COLUMN ' + quote_identifier(column_name) + ' ' + column_type
      IF default_value IS NOT NULL:
        sql_statement = sql_statement + ' DEFAULT ' + default_value

      LOG sql_statement
      EXECUTE sql_statement
    ELSE:
      LOG 'Column already exists'
  END LOOP
  CLOSE cursor
END FUNCTION