# Built-in modules #
import sqlite3
from itertools import islice

# Internal modules #
from color import Color
from autopaths import FilePath
from cache import property_cached

################################################################################
def convert_to_sql(source, dest, keys, values, sql_field_types=None):
    if sql_field_types is None: sql_field_types = {}
    with sqlite3.connect(dest) as connection:
        # Prepare #
        cursor = connection.cursor()
        fields = ','.join(['"' + f + '"' + ' ' + sql_field_types.get(f, 'text') for f in keys])
        cursor.execute("CREATE table 'data' (%s)" % fields)
        question_marks = '(' + ','.join(['?' for x in keys]) + ')'
        sql_command = "INSERT into 'data' values " + question_marks
        # Main loop #
        try:
            cursor.executemany(sql_command, values)
        except (ValueError, sqlite3.OperationalError, sqlite3.ProgrammingError, sqlite3.InterfaceError) as err:
            first_elem = islice(values, 0, 1)
            message1 = "The command <%s%s%s> on the database '%s' failed with error:\n %s%s%s"
            message1 = message1 % (Color.cyn, sql_command, Color.end, dest, Color.u_red, err, Color.end)