- name: "Check if domain table in {{ pdns_postgres_database }} exist"
  postgresql_query:
    db: "{{ pdns_postgres_database }}"
    login_host: "{{ pdns_postgres_host }}"
    login_password: "{{ pdns_postgres_password }}"
    login_user: "{{ pdns_postgres_username }}"
    query: "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema='public' AND table_name='domains');"
  register: result
    
- name: "Convert the SELECT result"
  set_fact:
    converted_result: "{{ result | from_yaml }}"

- name: "Set variable"
  set_fact:
    domain_table_exist: "{{ item.exists }}"
  with_items: "{{ converted_result.query_result }}"

- name: "Copy SQL script"
  copy:
    src: "{{ playbook_dir }}/templates/pdns/schema.pgsql.sql"
    dest: /tmp/schema.pgsql.sql
    mode: '0644'
  when: 
    - not domain_table_exist

- name: "Run queries from SQL script"
  postgresql_query:
    db: "{{ pdns_postgres_database }}"
    login_host: "{{ pdns_postgres_host }}"
    login_password: "{{ pdns_postgres_password }}"
    login_user: "{{ pdns_postgres_username }}"
    as_single_query: yes
    path_to_script: /tmp/schema.pgsql.sql
  when: 
    - not domain_table_exist

- name: "Remove SQL script if present"
  file:
    path: /tmp/schema.pgsql.sql
    state: absent
