This is the code responsible for adding new row (which inserts into a database) and updating a table cell (which updates the database). Every time I click on the ‘Add row’ button an update in ‘if’ is being run too which I don’t want to. Click on ‘Add new row’ button should only execute ‘elif’ part of the code but for that I need to distinguish between clicks. The way I have it at the moment doesn’t do that. I tried to extract adding new row into a new function but for that I need to have the same output Output(‘my-datatable’, ‘rows’) and Dash doesn’t support it. Is there any other way to do this? I am using data-table-experiments.
import dash_table_experiments as dt
from dash.dependencies import Input, Output, State
app.layout = html.Div(children=[
dt.DataTable(
    id='my-table',
    rows=df.sort_values('id').to_dict('records'),
    editable=True,
    row_update=True,
    filterable=True,
    sortable=True,
    row_selectable=True
),
html.Button('Add Row', id='add-row-button', n_clicks=0)])
@app.callback( 
Output('my-table', 'rows'),
[Input('my-table', 'row_update'),
Input('add-row-button', 'n_clicks')],
[State('my-table', 'rows')])
def update_rows(row_update, n_clicks, rows):
    if (type(row_update) != bool):
        value = list(row_update[0]['updated'].values())[0]
        column = list(row_update[0]['updated'].keys())[0]
        row_index = row_update[0]['from_row']
        query=f"""BEGIN
        UPDATE my_table
        SET  {column}='{value}'
        WHERE id={row_index + 1}
      END;"""
        cursor.execute(query)
        connection.commit()
        get_query = "SELECT * FROM my-table ORDER BY id"
        rows = pd.read_sql(get_query, connection)
        rows = rows.sort_values('id').to_dict('records')
    # else if 'add new row' button has been clicked, 
    # insert a new empty row in a database which will show as a new row 
    # with index number on a DataTable and treat it as an update later
    elif n_clicks:
        query_insert = f"""BEGIN
                  INSERT INTO my-table
                  DEFAULT VALUES
               END;"""
        cursor.execute(query_insert)
        connection.commit()
        get_query = "SELECT * FROM my-table ORDER BY id"
        rows = pd.read_sql(get_query, connection)
        rows = rows.sort_values('id').to_dict('records')
    return rows