# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import pymysql

def dump0(con, searchtype, sqlstr):
    print('%s' % (searchtype))
    c = con.cursor()
    c.execute(sqlstr)
    for row in c.fetchall():
        print('  %s - %s' % (row[0], row[1]))
    c.close()

def dump1(con, searchtype, sqlstr, searchterm):
    print('%s search for : %s' % (searchtype, searchterm))
    c = con.cursor()
    c.execute(sqlstr, (searchterm,))
    for row in c.fetchall():
        print('  %s - %s' % (row[0], row[1]))
    c.close()

with pymysql.connect(host='localhost',user='arne',password='hemmeligt',db='Test') as con:
    # all
    dump0(con, 'all', 'SELECT names, moves FROM chessopening')
    # one
    dump1(con, 'one natural', 'SELECT names, moves FROM chessopening WHERE MATCH(names) AGAINST (%s)', 'defense')
    dump1(con, 'one natural', 'SELECT names, moves FROM chessopening WHERE MATCH(moves) AGAINST (%s)', 'd4')
    # dual
    dump1(con, 'dual natural', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s)', 'defense')
    dump1(con, 'dual natural', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s)', 'd4')
    dump1(con, 'dual natural', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s)', 'defense d4') # implicit or
    # dual boolean
    dump1(con, 'dual boolean', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s IN BOOLEAN MODE)', 'defense')
    dump1(con, 'dual boolean', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s IN BOOLEAN MODE)', 'd4')
    dump1(con, 'dual boolean', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s IN BOOLEAN MODE)', 'defense d4') # implicit or
    dump1(con, 'dual boolean', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s IN BOOLEAN MODE)', '+defense+d4') # and
    dump1(con, 'dual boolean', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s IN BOOLEAN MODE)', '+defense-d4') # not
    dump1(con, 'dual boolean', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s IN BOOLEAN MODE)', 'def*') # wildcard
    dump1(con, 'dual boolean', 'SELECT names, moves FROM chessopening WHERE MATCH(names,moves) AGAINST (%s IN BOOLEAN MODE)', 'N*') # wildcard
