/*
    QAD - Qt ADvanced

	Ivan Pelipenko peri4ko@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser 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 Lesser General Public License for more details.

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

#ifndef sql_query_H
#define sql_query_H

#include "qad_sql_export.h"

#include <QMap>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <functional>


namespace QAD {

class QAD_SQL_EXPORT SQLQuery {
public:
	SQLQuery(QString query_ = QString(), QVariantMap params = QVariantMap(), QSqlDatabase db = QSqlDatabase());
	~SQLQuery();

	struct QAD_SQL_EXPORT Result {
		bool ok           = false;
		int rows          = 0;
		QVariant insertId = -1;
		QSqlQuery query;
		operator bool() const { return ok; }
	};

	typedef std::function<void(QString, QVariantMap, QSqlError)> HandlerFail;

	QSqlQuery & query() { return q; }

	bool exec() { return q.exec(); }

	static Result exec(QString query_, QVariantMap params = QVariantMap(), QSqlDatabase db = QSqlDatabase());

	/// INSERT INTO <table> (<values.keys>) VALUES (<values.values>)
	static Result insert(QString table, QVariantMap values = QVariantMap(), QSqlDatabase db = QSqlDatabase());

	/// DELETE FROM <table> [WHERE <filter>]
	static Result remove(QString table, QString filter = QString(), QSqlDatabase db = QSqlDatabase());

	/// DROP TABLE <table>
	static bool drop(QString table, QSqlDatabase db = QSqlDatabase());

	static void setFailHandler(HandlerFail h);

protected:
	QSqlQuery q;

private:
	struct Singleton {
		static Singleton * instance();
		HandlerFail fail_handler;
	};
};

} // namespace QAD

#endif
