Example #1
0
 def test_delete(self):
     """delete test data"""
     db.delete(self.save_data)
     check_delete = (
         db.Task.select().where((db.Task.task_name == "unittest data")
                                & (db.Task.date == "0000-01-01")))
     self.assertTrue(check_delete.count() == 0)
Example #2
0
    def test_delete(self):
        row_dict = {'type': 'weight'}
        row_dict = db.insert('data', row_dict)
        db.delete('data', row_dict)

        assert_equal(None, row_dict.get('id'))
        assert_equal([], db.rows('select * from data'))
Example #3
0
def delete():
    if not isLoggedIn():
        return render_template('login.html', loggedIn=False)
    else:
        db.delete(session["username"], request.form["data-type"], request.form["data"])
        flash('Deleted {} from your music'.format(request.form["data"]))
        return redirect(url_for('search'))
Example #4
0
def cancel_item():
    # print(request.form)
    # return "你的账号已成功开启自动打卡功能,如需要取消自动打卡请联系:QQ 2033465789"
    print("cancel_item", (request.form['appId'], request.form['password']))
    db.delete((request.form['appId'], request.form['password']))
    print(db.alluser())
    return render_template('cancel_success.html')
Example #5
0
 def record_del(self, Name):
     try:
         del self.address_book[Name]
         db.delete(Name, self.username)
         return True
     except:
         return False
Example #6
0
def lambda_handler(event, context):
    purchaseID = None
    print("event")
    print(event)
    print("context")
    print(context)

    userID = event['session']['user']['userId']

    name = extract_name(event, context)
    location = extract_lat_long(event, context)
    phoneNumber = extract_phone(event, context)
    # This is the user phone number
    productResponse = get_product_response(event, context)
    endSession = True
    if event["request"]["type"] == "LaunchRequest":
        speech = responses.start_response()
        endSession = False
    elif event["request"]["type"] == "IntentRequest":

        if event["request"]["intent"]["name"] == 'whatBuy':
            speech = responses.what_can_i_buy()
        else:
            isPurchased = productResponse['inSkillProducts'][0][
                'entitlementReason'] == 'PURCHASED'

            if isPurchased and db.get_user(userID) != None:
                restaraunt = event["request"]["intent"]["slots"]["restaraunt"][
                    "value"]
                speech, uuid, restaurantNumber = on_intent(
                    event["request"], event["session"], location, name,
                    phoneNumber)
                db.add(userID, restaraunt, location, uuid, restaurantNumber)
                echo.make_call(restaurantNumber, db.get_user(userID)['uuid'])
                db.delete(userID)

            else:
                purchaseID = productResponse['inSkillProducts'][0]['productId']
                restaraunt = event["request"]["intent"]["slots"]["restaraunt"][
                    "value"]
                dateVal = event["request"]["intent"]["slots"]["dateVal"][
                    "value"]
                timeVal = event["request"]["intent"]["slots"]["timeVal"][
                    "value"]
                speech, uuid, restaurantNumber = on_intent(
                    event["request"], event["session"], location, name,
                    phoneNumber, dateVal, timeVal)
                db.add(userID, restaraunt, location, uuid, restaurantNumber)
    else:
        echo.make_call(
            db.get_user(userID)['restaurant_number'],
            db.get_user(userID)['uuid'])
        # echo.make_call(RESTAURANT_PHONE_NUMBER, db.get_user(userID)['uuid'])
        db.delete(userID)
        speech = "We will let you know after the reservation has been made"
        send_text(
            "Reservation has been successfully placed for {}".format(name))
    x = returnSpeech(speech, product=purchaseID, endSession=endSession)
    print(x)
    return x
Example #7
0
def route_delete(name):
    generic_error = "no"
    if not db.has(name):
        return generic_error

    if not name in delete_keys:
        delete_keys[name] = random_string(32)

    key = request.args.get('key', '')

    if key == "":
        requests.post(config.slack_webhook,
                      json={
                          "text":
                          "Delete {}: {}".format(
                              name, "https://{}{}".format(
                                  config.zone,
                                  url_for('route_delete',
                                          name=name,
                                          key=delete_keys[name])))
                      })
        return generic_error

    if delete_keys[name] != key:
        return generic_error

    ret = ns.delete(name)

    if not ret:
        return "something bad happened"

    db.delete(name)
    del delete_keys[name]
    return "ok"
Example #8
0
def downvote(videoid):

    # Set vote value
    vote = -1

    # Calculating the votes for video
    total_votes = db.calcVotes(videoid)

    if total_votes == None:
        total_votes = 0

    # This deletes a video if it has a total score of -5
    if total_votes > -4:
        try:
            # Getting username
            user_name = db.getLogin()

            # Getting user id
            userid = db.getUserId(user_name)

            # Make vote
            db.vote(videoid, userid, vote)
            return redirect('/videos')

        except:
            redirect('/')

    else:
        db.delete(videoid)
        return redirect('/videos')
 def test_with_one_value(self):
     connection = MockConector(test_env)
     delete(connection, 'TestTable', 'test condition')
     cursor = connection.cursor.return_value
     cursor.execute.assert_called_with(
         'DELETE FROM "TestTable" WHERE test condition;')
     cursor.execute.assert_called_once()
Example #10
0
def delete_expense(expense_id: int):
    """
    Функция удаления расхода
    :param expense_id: идентификатор расхода
    :return: None
    """
    db.delete("expenses", row_id=expense_id)
Example #11
0
def delete(event, context):
    log.info('DELETE to delete')
    db_connection = db.get_db_connection()
    key = event['pathParameters']['id']
    db.delete(db_connection, key)

    return {'statusCode': 200}
Example #12
0
 def delete(self):
     self.pre_delete and self.pre_delete()  # 这里用一种逻辑短路的写法,若pre_delete为空,则跳过
     pk = self.__primary_key__.name
     db.delete(
         'delete from `%s` where %s=?' %
         (self.__table__, self.__primary_key__.name), getattr(self, pk))
     return self
Example #13
0
 def delete(self):
     items = self.items_view.selectedItems()
     if items:
         self.items.pop(self.items_view.currentRow())
         db.delete(self.items_view.currentRow() + 1)
         self.items_view.clear()
         self.list_items()
Example #14
0
    def delete(self, req, resp, id):
        does_service_exist = db.does_service_exist(id)
        if not does_service_exist:
            message = "Service %s does not exist"
            tokens = [id]
            code = "DSM-LITE-404"
            resp.status = falcon.HTTP_404
            resp.body = error_response(code=code,
                                       message=message,
                                       tokens=tokens)
            return

        service_data = db.get(id)
        service_state = service_data.get("serviceState")
        if service_state not in ["Draft", "Reserved"]:
            message = "Invalid service state %s. Only services in Draft or Reserved state can be deleted."
            tokens = [service_state]
            code = "DSM-LITE-405"
            resp.status = falcon.HTTP_405
            resp.body = error_response(code=code,
                                       message=message,
                                       tokens=tokens)
            return

        db.delete(id)
        resp.content_type = 'application/json'
        resp.body = success_response(None)
        resp.status = falcon.HTTP_200
Example #15
0
def runDoneQueue():
    while 1:
        if (Qdone.empty() != True):
            print "Task done!"
            db.delete(Qdone.get())

        
    

    
    #Send all status codes
    #print "StatusCodes"
    #for statuscode in db.get_all(StatusCode):
    #    networkcomponent.send(ip,statuscode,'db_add_or_update')
    #    print statuscode
    
    #Send all missions
    #print "Missions"
    #for mission in db.get_all(Mission):
    #    networkcomponent.send(ip,mission,'db_add_or_update')
    #    print mission
    
    #Send all employees
    #print "Employees"
    #for employee in db.get_all(Employee): 
    #    networkcomponent.send(ip,employee,'db_add_or_update')
    #    print employee
Example #16
0
async def deleteUser(id: int, db: Session = Depends(db.get_db)):
    selectUserById = db.query(DB_User).filter(DB_User.id == id).first()
    if selectUserById is None:
        raise HTTPException(status_code=404, detail="Don't exist user")

    db.delete(selectUserById)
    db.commit()
    return "OK"
Example #17
0
 def _post_delete_(self):
     key = self.request.get('key')
     event = db.get(key)
     db.delete(event)
     self.response.out.write(
         simplejson.dumps({'data': {
             'key': key
         }}, ensure_ascii=False))
def handle_send_failure(command_id):
    sql = """
        DELETE
        FROM command_log
        WHERE id = {0}
    """.format(command_id)
    print("updating command for failure {0}".format(command_id))
    db.delete(sql)
Example #19
0
def confirm_delete(student_id):
    if request.method == 'GET':
        return render_template('confirm_delete.html')
    elif request.method == 'POST':
        if request.form['submit_button'] == 'Yes':
            db.delete(id=student_id)
            return redirect('/students')
        else:
            return redirect('/students')
Example #20
0
def deluser():
    if not session.get('name'):
        return redirect('/login')
#前端get请求,逻辑端通过request.args.get获取参数
    uid = request.args.get("uid")
    table = 'users'
    print uid
    db.delete(table, uid)
    return json.dumps({"code": 0, "result": "delete user success"})
Example #21
0
def delcabinet():
    id = request.args.get('id')
    table = 'cabinet'
    try:
	db.delete(id,table)
	return json.dumps({'code':0, 'result': 'delete cabinet success'})
    except:
	print traceback.print_exc()
	return json.dumps({'code':1, 'result': 'delete cabinet failed'})
Example #22
0
 def _post_delete_(self):
     key = self.request.get('key')
     event = db.get(key)
     db.delete(event)
     self.response.out.write(simplejson.dumps({
         'data': {
             'key': key
         }
     }, ensure_ascii=False))
Example #23
0
 def close(self, reason):
     """
     :param reason:
     :return:所有url请求完毕之后关闭爬虫的回调函数
     """
     # 删除被删除的公众号 被删除的公众号content_url为空
     from db import delete
     delete(self.current_nickname, content_url="")
     print(self.name, "爬虫关闭")
Example #24
0
def confirm_email(token):
    try:
        email = s.loads(token, salt='email-confirm', max_age=600)
        api.update(email)
        return render_template('untitled.html')
    except SignatureExpired:
        email = s.loads(token, salt='email-confirm')
        api.delete(email)
        return '<h1>Token expired</h1>'
Example #25
0
def remove():
    try:
        n = int(input("Enter the number of the item you want to remove: "))
        if n <= 0: raise IndexError
        item_id = items[n-1][0]
        db.delete(item_id)
    except IndexError:
        print()
        print("Sorry, that number is not on the list, try again.")
def get_note(notebook_id, db): 
    session = bottle.request.environ.get('beaker.session')   
    user_id = session.get('user_id')
    try:
        notebook = db.query(Notebook).filter_by(user_id = user_id, id = notebook_id, deflt=False).one()
        db.delete(notebook)
        db.commit()
        return {}
    except NoResultFound:
        return {}  
Example #27
0
 def remove_from_db(self):
     current_row = self.table.currentRow()
     id = {'_id': self.ids[current_row]}
     if current_row == -1:
         QtWidgets.QMessageBox.about(self, 'Ошибка', 'Строчка не выбрана')
         return 1
     self.table.removeRow(current_row)
     self.ids.remove(self.ids[current_row])
     db.delete(id)
     QtWidgets.QMessageBox.about(self, 'Успешно', 'Элемент удален!')
Example #28
0
def showall_del():
    if request.method == 'POST':
        form = request.form
        code = form['code']
        user = db.getUserByCode(code)
        if (user != None):
            db.delete(code)
            return redirect('/showall')

        return "something went wrong"
Example #29
0
def forget_link(request):
    if type(request) == list and len(request) == 2:
        if request[1] in Links:
            db.delete(links_db, request[1])
            del Links[request[1]]

            return "'%s' forgotten" % request[1]
        else:
            return "'%s' cannot be found" % request[1]
    else:
        return "Wrong number of parameters. Usage: /forget <name>"
Example #30
0
 def do_DELETE(self):
     if re.match(r'\/product\/\d+', self.path): # match "/product/{ID}"
         #send response code:
         self.send_response(200)
         #send headers:
         self.send_header("Content-type:", "application/json")
         # send a blank line to end headers:
         self.wfile.write("\n")
         #send response:
         db.delete(re.search(r'[^/]*$', self.path).group(0)), self.wfile
         return
Example #31
0
def delete_last(user_id: int) -> str:
    """ Delete last added expense, returns status of whether it deleted or not """
    cursor = db.get_cursor()
    cursor.execute("SELECT id FROM expenses "
                   f"WHERE user_id = {user_id} "
                   "ORDER BY created DESC LIMIT 1")
    result = cursor.fetchone()
    if not result:
        return "There are no expenses yet."
    db.delete("expenses", {"id": result[0]})
    return "Last expense was successfully deleted\n"
Example #32
0
 def do_DELETE(self):
     if re.match(r'\/product\/\d+', self.path):  # match "/product/{ID}"
         #send response code:
         self.send_response(200)
         #send headers:
         self.send_header("Content-type:", "application/json")
         # send a blank line to end headers:
         self.wfile.write("\n")
         #send response:
         db.delete(re.search(r'[^/]*$', self.path).group(0)), self.wfile
         return
Example #33
0
def delete():
    if not session.get('name',None):
        return redirect('/login')
    id = request.args.get('id')
    table = 'users'
    try:
        db.delete(id,table)
	return json.dumps({'code':0, 'result':'delete user success'})
    except:
        print traceback.print_exc()
	return json.dumps({'code':1, 'result':'delete user failed'})
Example #34
0
def main():

    while True:
        i = int(
            input(
                " 1=> add user, 2=> view user, 3=>remove user ,4=> view all 5=> quit"
            ))
        if i == 1:
            name = input("give user name: ")
            if db.contains(name):
                print("ERROR!! user {} already exists".format(name))
            else:
                pwd = getpass.getpass("give password:"******"confirm passwd:")
                if pwd == pwd2:
                    db.add(name, pwd)
                    print("{} sucessfully added".format(name))
                    disc = input("give description:?? ")
                    db.adddisc(name, pwd, disc)
                else:
                    print("{} not added as typed password not matched".format(
                        name))
        elif i == 2:
            name = input("give user name: ")
            if db.contains(name):
                pwd = getpass.getpass("give password: "******"NAME:   ", name, '\nDISCRIPTION:   ',
                          db.discription(name, pwd))
                else:
                    print("you entered a wrong password for user".format(name))
            else:
                print("user {} does not exist".format(name))
        elif i == 3:
            name = input("give user name: ")
            if db.contains(name):
                pwd = getpass.getpass("give password: "******"you entered a wrong password for user {}".format(
                        name))
            else:
                print("user {} does not exist".format(name))
        elif i == 4:
            db.view()
        elif i == 5:
            print("thank you")
            break
        else:
            print("not a choice")
    else:
        db.close()
Example #35
0
def canDeleteBoardFromDB():
	test_name = "Database: Delete a board from the collection"

	try:
		database = createTestDB()
		board = createTestBoard()
		db.add(board,database,"boards")

		db.delete(board,database,"boards")
		passTest(test_name)
	except:
		failTest(test_name, sys.exc_info()[1])
Example #36
0
def canDeleteCardFromDB():
	test_name = "Database: Delete a card from the collection"

	try:
		database = createTestDB()
		card = createTestCard()
		db.add(card,database,"items")

		db.delete(card,database,"items")
		passTest(test_name)
	except:
		failTest(test_name, sys.exc_info()[1])
Example #37
0
def delidc():
    #    if not session.get('username',None):
    #        return redirect('/login')
    id = request.args.get('id')
    print id
    table = 'idc'
    try:
        db.delete(id, table)
        return json.dumps({'code': 0, 'result': 'delete idc success'})
    except:
        print traceback.print_exc()
        return json.dumps({'code': 1, 'result': 'delete idc failed'})
def delete_note(note_id, db):    
    session = bottle.request.environ.get('beaker.session')
    user_id = session.get('user_id')
    try:
        note = db.query(Note).filter_by(id = note_id).one()
        if note.notebook.user_id != user_id:
            bottle.abort(401,'Unauthorized')
        db.delete(note)
        db.commit()
        return {};
    except NoResultFound:
            bottle.abort(404, 'Not Found')
Example #39
0
 def POST(self):
     """ receive new label """
     if not CheckAuth(web.ctx.env.get('HTTP_AUTHORIZATION')):
         raise web.seeother('/login')
         return
     user_data = web.input(u=None)
     if user_data.u == None:
         print("INCOMPLETE")
         return "FAIL"
     else:
         #print("Delete "+str(user_data.u))
         db.delete(str(user_data.u))
         return "OK"
Example #40
0
    def POST(self, category):
        i = web.input(id=None, redirect_url=None)
        redirect_url = i.redirect_url

        id = i.id and safeint(i.id, None)
        if id:
            db.delete(id)
            if redirect_url:
                raise web.seeother(redirect_url)
            else:
                return 'cover has been deleted successfully.'
        else:
            return 'no such id: %s' % id
Example #41
0
    def test_delete():
        # Deletes a record from the primary index
        indexname = 'ID' + '_' + name + '.json'
        db.deleteFromIndex(indexname, 5)
        db.deleteFromIndex(indexname, 1000)          # this does not exist   # ERROR 2

        # Deletes a record from the secondary index
        indexname = 'name' + '_' + name + '.json'
        db.deleteFromIndex(indexname, 1, 'seimenis') # this does not exist   # ERROR 3
        db.deleteFromIndex(indexname, 5070, 'souloumeni')
        db.deleteFromIndex(indexname, 5, 'hadfadd')

        # deletes completely the primary key from all the indexes of the given database
        db.delete(5070, database)
def admin_get_notebook(notebook_id, db):
    session = bottle.request.environ.get('beaker.session')
    cur_user_id = session.get('user_id')   
    try:
        user = db.query(User).filter_by(id=cur_user_id, admin=True).one()
        if user:
            notebook = db.query(Notebook).filter_by(id=notebook_id).one()
            db.delete(notebook)
            db.commit()
            return {}
        else:
            bottle.abort(401,"Unauthorized")
    except NoResultFound:
        return {}
Example #43
0
def canDeleteProjectFromDB():
	test_name = "Database: Delete a project from the collection"

	try:
		database = createTestDB()
		project = createTestProject()

		db.add(project, database, "projects")
		db.delete(project,database,"projects")

		passTest(test_name)

	except:
		failTest(test_name, sys.exc_info()[1])
Example #44
0
def idcdelete():
    id = request.form.get('id')
    columns = ['id', 'name']
    where = "id=" + id
    idc = json.loads(db.get_one(columns, where, 'idc'))
    util.WriteLog('infoLogger').warning('%s delete idc %s' % (session['username'], idc['name']))
    return json.dumps(db.delete(where, 'idc'))
Example #45
0
def serverdelete():
    id = request.form.get('id')
    columns = ['id', 'hostname']
    where = 'id=' + id
    hostname = json.loads(db.get_one(columns, where, 'server'))
    util.WriteLog('infoLogger').warning('%s delete server hostname %s' % (session['username'], hostname['hostname']))
    return json.dumps(db.delete(where, 'server'))
Example #46
0
def cabinetdelete():
    id = request.form.get('id')
    columns = ['id', 'name']
    where = 'id=' + id
    cabinet = json.loads(db.get_one(columns, where, 'cabinet'))
    util.WriteLog('infoLogger').warning('%s delete cabinet %s' % (session['username'], cabinet['name']))
    return json.dumps(db.delete(where, 'cabinet'))
Example #47
0
def virtualdel():
    id = request.form.get('id')
    columns = ['id', 'hostname']
    where = "id=" + id
    hostname = json.loads(db.get_one(columns, where, 'virtuals'))
    util.WriteLog('infoLogger').warning('%s delete virtual hostname %s' % (session['username'], hostname['hostname']))
    return json.dumps(db.delete(where, 'virtuals'))
Example #48
0
 def get(self):
     ID=self.get_argument('ID','')
     if db.delete(ID):
         tohtml.html().ALL()
         os.remove("./html/%s.html" % ID)
         self.write("0")
     else:
         self.write("数据库异常,刪除失败!")
Example #49
0
 def setUp(self):
     setattr(db, '__db', {})
     db.setup(config,adapter='pymysql')
     _create()
     users = []
     for i in range(1, 6):
         users.append((i, 'user_' + str(i)))
     db.execute('INSERT INTO users VALUES(%s, %s)', users)
     self.delete = db.delete('users')
Example #50
0
def delete_idcinfo(params):
    id = params.get('id')
    idcname = params.get('idcname')
    date = params.get('date')
    # _sql = 'delete from idc_data where id = %s and date = %s and idcname = %s'
    # _args = (id,date,idcname)
    _sql_count, rt_list = db.delete("id = '%s' and date = '%s' and idcname = '%s'" % (id,date,idcname) ,'idc_bill')
    if _sql_count != 0:
        return True, '删除成功'
    return False, '删除失败'
Example #51
0
def backupServer_monitor_cron():
    ip_list = db.get_list(['wan_ip','qufu','hostname'], 'virtuals')
    for ip in ip_list:
        dirname = '/data/mongobackup/' + ip['wan_ip']
        backNum = util.paramiko_command('121.201.72.22', 'ls %s|wc -l' % dirname)
        ip['backNum'] = backNum
        backName = util.paramiko_command('121.201.72.22', 'ls -rt %s|tail -1' % dirname)
        ip['backName'] = backName
        backSize = util.paramiko_command('121.201.72.22', "ls -lrt --block-size=M %s |tail -1|awk '{print $5}'" % dirname)
        ip['backSize'] = backSize
        if len(ip['backSize']) >= 5:
            ip['backSize'] = str(round(float(float(ip['backSize'][0:-1]) / 1024), 2)) + 'G'
        if len(json.loads(db.get_one(['wan_ip'], "wan_ip='%s'" % str(ip['wan_ip']), 'backupServerMonitor'))) > 1:
            db.delete("wan_ip='%s'" % ip['wan_ip'], 'backupServerMonitor')
            db.create(ip, 'backupServerMonitor')
        elif len(json.loads(db.get_one(['wan_ip'], "wan_ip='%s'" % str(ip['wan_ip']), 'backupServerMonitor'))) == 1:
            db.update(ip, "wan_ip='%s'" % ip['wan_ip'], 'backupServerMonitor')
        elif len(json.loads(db.get_one(['wan_ip'], "wan_ip='%s'" % str(ip['wan_ip']), 'backupServerMonitor'))) == 0:
            db.create(ip, 'backupServerMonitor')
Example #52
0
 def delete(self):
     """ 实例方法,删除实例
     """
     self.pre_delete and self.pre_delete()
     pk = self.__primary_key__.name
     if hasattr(self, pk):
         args = getattr(self, pk)
         rownum = db.delete("DELETE FROM `%s` WHERE `%s`=?" % (self.__table__, pk), args)
         return rownum
     else:
         raise StandardError(r"current object cannot delete by '%s'" % pk )
Example #53
0
def innerdel():
    id = request.form.get('id')
    where = 'id=' + id
    reason = db.delete(where, 'innerServer')
    return json.dumps(reason)
Example #54
0
	return redirect('login')
    id = request.args.get('id',None)
    if not id:
	errmsg = 'must have id '
	return render_template('userlist.html',result = errmsg)
'''
    try:
	sql = 'delete from users where id = %s' % id
	cur.execute(sql)
	return redirect('/userlist')
    except:
	errmsg = 'delete failed '
	print traceback.print_exc()
	return render_template('userlist.html',result = errmsg)
'''
    delete(id)
    return redirect('/userlist')


@app.route('/update',methods=['POST','GET'])
def update():
    if not session.get('name',None):
	return redirect('login')
    if request.method == 'POST':
	data = dict(request.form)
'''
	condition = ["%s='%s'" % (k,v[0]) for k,v in data.items()]
	sql = 'update users set %s where id = %s' % (','.join(condition),data['id'][0])
	cur.execute(sql)
'''
	modify(data)	
Example #55
0
def delete_my_id(frm):
    print "delete_my_id called, removing %s" % frm
    db.delete(frm)
    send_message(frm['gid'], 'your txtnonymous id (#' + frm['tag'] + ') has been deleted.')
Example #56
0
 def delete(self, user):
     return db.delete(self.table).condition('uid', user.uid).execute()
Example #57
0
def del_user():
    uid = request.args.get("id")
    delete(uid)
    return redirect("/")
Example #58
0
 def delete(self, page_id):
     return db.delete(self.table).condition('pid', page_id).execute()
     
Example #59
0
 def delete(self):
     self.pre_delete and self.pre_delete()
     pk = self.__primary_key__.name
     db.delete(self.__table__, where=[(self.__primary_key__.name, getattr(self, pk))])
     return self
Example #60
0
    if group:
        sql += " GROUP BY " + group
    if order:
        get_direction = lambda c: (c if isinstance(c, basestring)
                                    else "DESC" if c else "ASC")
        sql += " ORDER BY "
        for i, col in enumerate(order):
            name = col[0] if isinstance(col, (list, tuple)) else col
            direction = "" if name == col else " " + get_direction(col[1])
            sql += (", " if i else "") + name + direction
    if limit:
        sql += " LIMIT %s" % (", ".join(map(str, limit)))
    return sql, args



if "__main__" == __name__:
    import db
    db.init(":memory:", "CREATE TABLE test (id INTEGER PRIMARY KEY, val TEXT)")

    print("Inserted ID %s." % db.insert("test", val=None))
    for i in range(5): print("Inserted ID %s." % db.insert("test", {"val": i}))
    print("Fetch ID 1: %s." % db.fetch("test", id=1))
    print("Fetch all up to 3, order by val: %s." % db.fetchall("test", order="val", limit=3))
    print("Updated %s row where val is NULL." % db.update("test", {"val": "new"}, val=None))
    print("Select where val IN [0, 1, 2]: %s." % db.fetchall("test", val=("IN", range(3))))
    print("Delete %s row where val=0." % db.delete("test", val=0))
    print("Fetch all, order by val: %s." % db.fetchall("test", order="val"))
    db.execute("DROP TABLE test")
    db.close()