# Buggy code
def save_datasource(self, name, source_type, source, file_path=None):
    if source_type == "file" and (file_path is None):
        raise Exception('`file_path` argument required when source_type == "file"')

    for i in range(1, 1000):
        if name in [x["name"] for x in self.get_datasources()]:
            previous_index = i - 1
            name = name.replace(f"__{previous_index}__", "")
            name = f"{name}__{i}__"
        else:
            break

    ds_meta_dir = os.path.join(self.dir, name)
    os.mkdir(ds_meta_dir)

    ds_dir = os.path.join(ds_meta_dir, "datasource")
    os.mkdir(ds_dir)

    if source_type == "file":
        source = os.path.join(ds_dir, source)
        os.replace(file_path, source)
        ds = FileDS(source)
        picklable = {"class": "FileDS", "args": [source], "kwargs": {}}
    elif source_type == "clickhouse":
        user = self.config["integrations"]["default_clickhouse"]["user"]
        password = self.config["integrations"]["default_clickhouse"]["password"]
        # TODO add host port params
        ds = ClickhouseDS(source, user=user, password=password)
        picklable = {
            "class": "ClickhouseDS",
            "args": [source],
            "kwargs": {"user": user, "password": password},
        }
    elif source_type == "mariadb":
        user = self.config["integrations"]["default_mariadb"]["user"]
        password = self.config["integrations"]["default_mariadb"]["password"]
        host = self.config["integrations"]["default_mariadb"]["host"]
        port = self.config["integrations"]["default_mariadb"]["port"]
        ds = MariaDS(source, user=user, password=password, host=host, port=port)
        picklable = {
            "class": "MariaDS",
            "args": [source],
            "kwargs": {"user": user, "password": password, "host": host, "port": port},
        }
    else:
        # This probably only happens for urls
        print("Create URL data source !")
        ds = FileDS(source)
        picklable = {"class": "FileDS", "args": [source], "kwargs": {}}

    df = ds.df

    df_with_types = cast_df_columns_types(df, self.get_analysis(df)["data_analysis_v2"])
    create_sqlite_db(os.path.join(ds_dir, "sqlite.db"), df_with_types)

    with open(os.path.join(ds_dir, "ds.pickle"), "wb") as fp:
        pickle.dump(picklable, fp)

    with open(os.path.join(ds_dir, "metadata.json"), "w") as fp:
        json.dump(
            {
                "name": name,
                "source_type": source_type,
                "source": source,
                "created_at": str(datetime.datetime.now()).split(".")[0],
                "updated_at": str(datetime.datetime.now()).split(".")[0],
                "row_count": len(df),
                "columns": [dict(name=x) for x in list(df.keys())],
            },
            fp,
        )

    return self.get_datasource_obj(name, raw=True)


# Traceback (Exception)
Using configuration file: config.json
Traceback (most recent call last):
File "/usr/local/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/zoran/MyProjects/mindsdb/mindsdb/__main__.py", line 61, in <module>
dbw.register_predictors(model_data_arr)
File "/home/zoran/MyProjects/mindsdb/mindsdb/interfaces/database/database.py", line 41, in register_predictors
for integration in it: integration.register_predictors(model_data_arr)
File "/home/zoran/MyProjects/mindsdb/mindsdb/integrations/clickhouse/clickhouse.py", line 115, in register_predictors
self._query(q)
File "/home/zoran/MyProjects/mindsdb/mindsdb/integrations/clickhouse/clickhouse.py", line 58, in _query
raise Exception(f'Error: {response.content}\nQuery:{query}')
Exception: Error: b'Code: 62, e.displayText() = DB::Exception: Syntax error: failed at position 51 (line 2, col 50): -class\n                    ( `Number of times pregnant` Nullable(String) , `Plasma glucose concentration` Nullable(Int64) , `Diastolic blood pressure` Nullable(. Expected one of: storage definition, ENGINE, AS, UUID, OpeningRoundBracket, ON, Dot, token (version 20.5.2.7 (official build))\n'
Query:
CREATE TABLE mindsdb.diabetes-class
( `Number of times pregnant` Nullable(String) , `Plasma glucose concentration` Nullable(Int64) , `Diastolic blood pressure` Nullable(Int64) , `Triceps skin fold thickness` Nullable(Int64) , `2-Hour serum insulin` Nullable(Int64) , `Body mass index` Nullable(Float64) , `Diabetes pedigree function` Nullable(Float64) , `Age` Nullable(Int64) , `Class` Nullable(String) , `Class_original` Nullable(String) ,`select_data_query` Nullable(String),`Class_confidence` Nullable(Float64),`Class_explain` Nullable(String)
) ENGINE=MySQL('127.0.0.1:47335', 'mindsdb', 'diabetes-class_clickhouse', 'root', 'somepass')

# Fixed code
def save_datasource(self, name, source_type, source, file_path=None):
    if source_type == "file" and (file_path is None):
        raise Exception('`file_path` argument required when source_type == "file"')

    for i in range(1, 1000):
        if name in [x["name"] for x in self.get_datasources()]:
            previous_index = i - 1
            name = name.replace(f"__{previous_index}__", "")
            name = f"{name}__{i}__"
        else:
            break

    ds_meta_dir = os.path.join(self.dir, name)
    os.mkdir(ds_meta_dir)

    ds_dir = os.path.join(ds_meta_dir, "datasource")
    os.mkdir(ds_dir)

    if source_type == "file":
        source = os.path.join(ds_dir, source)
        os.replace(file_path, source)
        ds = FileDS(source)
        picklable = {"class": "FileDS", "args": [source], "kwargs": {}}
    elif source_type == "clickhouse":
        user = self.config["integrations"]["default_clickhouse"]["user"]
        password = self.config["integrations"]["default_clickhouse"]["password"]
        # TODO add host port params
        ds = ClickhouseDS(query=source, user=user, password=password)
        picklable = {
            "class": "ClickhouseDS",
            "args": [],
            "kwargs": {"query": source, "user": user, "password": password},
        }
    elif source_type == "mariadb":
        user = self.config["integrations"]["default_mariadb"]["user"]
        password = self.config["integrations"]["default_mariadb"]["password"]
        host = self.config["integrations"]["default_mariadb"]["host"]
        port = self.config["integrations"]["default_mariadb"]["port"]
        ds = MariaDS(query=source, user=user, password=password, host=host, port=port)
        picklable = {
            "class": "MariaDS",
            "args": [],
            "kwargs": {
                "query": source,
                "user": user,
                "password": password,
                "host": host,
                "port": port,
            },
        }
    else:
        # This probably only happens for urls
        print("Create URL data source !")
        ds = FileDS(source)
        picklable = {"class": "FileDS", "args": [source], "kwargs": {}}

    df = ds.df

    df_with_types = cast_df_columns_types(df, self.get_analysis(df)["data_analysis_v2"])
    create_sqlite_db(os.path.join(ds_dir, "sqlite.db"), df_with_types)

    with open(os.path.join(ds_dir, "ds.pickle"), "wb") as fp:
        pickle.dump(picklable, fp)

    with open(os.path.join(ds_dir, "metadata.json"), "w") as fp:
        json.dump(
            {
                "name": name,
                "source_type": source_type,
                "source": source,
                "created_at": str(datetime.datetime.now()).split(".")[0],
                "updated_at": str(datetime.datetime.now()).split(".")[0],
                "row_count": len(df),
                "columns": [dict(name=x) for x in list(df.keys())],
            },
            fp,
        )

    return self.get_datasource_obj(name, raw=True)