{#
  NateMan – Nachschreibtermin-Manager
  templates/admin/sql_access.html.j2
  Copyright © 2020  Niklas Elsbrock

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <https://www.gnu.org/licenses/>.
-#}

{% extends 'base.html.j2' %}

{% block title %}SQL-Zugriff{% endblock %}
{% block header %}SQL-Zugriff{% endblock %}

{# result: Ergebnis einer SQL-Abfrage als sqlalchemy.engine.ResultProxy #}

{% block content %}
<p>
  Diese Seite erlaubt direkten Zugriff auf die SQL-Datenbank von NateMan durch die Eingabe von SQL-Abfragen.<br>
  <strong>
    Bei falscher Anwendung können Daten unwiderruflich verloren gehen.<br>
    Außerdem kann es bei der Veränderung bestimmter Daten zu unerwarteten Fehlern in der NateMan-Anwendung kommen.<br>
    <span class="marked">Benutzen Sie diese Seite nur, wenn Sie wissen, was Sie tun.</span>
  </strong>
</p>

<p>
  {% set nateman_erm_url = url_for('static', filename='img/nateman-erm.svg') %}
  <a href="{{ nateman_erm_url }}" target="_blank" rel="noreferrer noopener">
    <img src="{{ nateman_erm_url }}" height="500" alt="Entity-Relationship-Modell der NateMan-Datenbank"
         title="Entity-Relationship-Modell der NateMan-Datenbank">
  </a>
</p>

<form method="post">
  <p>
    <textarea name="query" class="monospace" rows="8" cols="80" placeholder="SQL-Abfrage hier eingeben"
              required autofocus>{{ query }}</textarea>
  </p>

  <p><input type="submit" value="Ausführen"></p>
</form>

{% if result is not none and result.returns_rows %}
  {% set result_rows = result.fetchall() %}

  <h3>Ergebnis ({{ result_rows|length }} Zeilen):</h3>

  <table class="monospace">
    <thead>
      <tr>
        {% for col_name in result.keys() %}
          <th>{{ col_name }}</th>
        {% endfor %}
      </tr>
    </thead>

    <tbody>
      {% for row in result_rows %}
        <tr>
          {% for value in row._mapping.values() %}
            {% if value is none %}
              <td class="detail">NULL</td>
            {% else %}
              <td>{{ value }}</td>
            {% endif %}
          {% endfor %}
        </tr>
      {% endfor %}
    </tbody>
  </table>
{% endif %}
{% endblock %}
