---
# file: roles/postgres/tasks/databases.yml

- name: "create database(s)"
  become: true
  become_user: postgres
  become_method: sudo
  postgresql_db:
    name: "{{ item.name }}"
    owner: "{{ item.owner }}"
    conn_limit: "{{ item.conn_limit | default(80) }}"
    lc_collate: "{{ item.lc_collate | default(omit) }}"
    lc_ctype: "{{ item.lc_ctype | default(omit) }}"
    template: "{{ item.template | default(omit) }}"
  loop: "{{ pg_databases }}"
  register: postgres_create_database
  tags: postgres

- name: "database extensions per database if defined"
  become: true
  become_user: postgres
  become_method: sudo
  postgresql_ext:
    name: "{{ item[1] }}"
    db: "{{ item[0].name }}"
  # The "default([])" parameter allows to do nothing if the "pg_databases" variable is not defined - Doc: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#defaulting-undefined-variables
  loop: "{{ pg_databases | default([]) | subelements('extension_list', skip_missing=True) }}"
  when:
    - pg_replication_role != "replica"
  tags: postgres

- name: "set fact postgres_share1_create_database"
  set_fact:
    postgres_share1_create_database: "{{ postgres_create_database }}"
  tags: postgres
