Package: simple-query-builder
QueryBuilder python moduleThis is a small easy-to-use module for working with a database. It provides some public methods to compose SQL queries and manipulate data. Each SQL query is prepared and safe. QueryBuilder fetches data todictionaryby default. At present time the component supports SQLite (file or memory).ContributingBug reports and/or pull requests are welcomeLicenseThe module is available as open source under the terms of theMIT licenseInstallationInstall the current version withPyPI:pipinstallsimple-query-builderOr from Github:pipinstallhttps://github.com/co0lc0der/simple-query-builder-python/archive/main.zipHow to useMain public methodsget_sql()returns SQL query string which will be executedget_params()returns a tuple of parameters for a queryget_result()returns query's resultget_count()returns result's rows countget_error()returnsTrueif an error is hadget_error_message()returns an error message if an error is hadset_error(message)sets_errortoTrueand_error_messageget_first()returns the first item of resultsget_last()returns the last item of resultsreset()resets state to default valuesall()executes SQL query and returns all rows of result (fetchall())one()executes SQL query and returns the first row of result (fetchone())column(col)executes SQL query and returns the needed column of result by its index or name,colis0by defaultpluck(key, col)executes SQL query and returns a list of tuples/dicts (the key (usually ID) and the needed column of result) by its indexes or names,keyis0andcolis1by defaultgo()this method is for nonSELECTqueries. it executes SQL query and returns nothing (but returns the last inserted row ID forINSERTmethod)exists()returnsTrueif SQL query has a row andFalseif it hasn'tcount()prepares a query with SQLCOUNT(*)function and executes itquery(sql, params, fetch_type, col_index)executes preparedsqlwithparams, it can be used for custom queries'SQL' methods are presented inUsage sectionImport the module and initQueryBuilderwithDatabase()fromsimple_query_builderimport*# if you want to get results as a list of dictionaries (by default since 0.3.5)qb=QueryBuilder(DataBase(),'my_db.db')# result_dict=True, print_errors=False# or if you want to get results as a list of tuples (since 0.3.5)qb=QueryBuilder(DataBase(),'my_db.db',result_dict=False)# for printing errors into terminal (since 0.3.5)qb=QueryBuilder(DataBase(),'my_db.db',print_errors=True)Usage examplesSelect all rows from a tableresults=qb.select('users').all()SELECT*FROM`users`;Select a row with a conditionresults=qb.select('users').where([['id','=',10]]).one()# or since 0.3.4results=qb.select('users').where([['id',10]]).one()SELECT*FROM`users`WHERE`id`=10;Select rows with two conditionsresults=qb.select('users').where([['id','>',1],'and',['group_id','=',2]]).all()# or since 0.3.4results=qb.select('users').where([['id','>',1],'and',['group_id',2]]).all()SELECT*FROM`users`WHERE(`id`>1)AND(`group_id`=2);Select a row with aLIKEandNOT LIKEconditionresults=qb.select('users').like(['name','%John%']).all()# orresults=qb.select('users').where([['name','LIKE','%John%']]).all()# or since 0.3.5results=qb.select('users').like('name','%John%').all()SELECT*FROM`users`WHERE(`name`LIKE'%John%');results=qb.select('users').not_like(['name','%John%']).all()# orresults=qb.select('users').where([['name','NOT LIKE','%John%']]).all()# or since 0.3.5results=qb.select('users').not_like('name','%John%').all()SELECT*FROM`users`WHERE(`name`NOTLIKE'%John%');Select a row with aIS NULLandIS NOT NULLcondition (since 0.3.5)results=qb.select('users').is_null('phone').all()# orresults=qb.select('users').where([['phone','is null']]).all()SELECT*FROM`users`WHERE(`phone`ISNULL);results=qb.select('customers').is_not_null('address').all()# orresults=qb.select('customers').not_null('address').all()# orresults=qb.select('customers').where([['address','is not null']]).all()SELECT*FROM`customers`WHERE(`address`ISNOTNULL);Select rows withOFFSETandLIMITresults=qb.select('posts')\.where([['user_id','=',3]])\.offset(14)\.limit(7)\.all()# or since 0.3.4results=qb.select('posts')\.where([['user_id',3]])\.offset(14)\.limit(7)\.all()SELECT*FROM`posts`WHERE(`user_id`=3)OFFSET14LIMIT7;Select custom fields with additional SQLCOUNT()results=qb.select('users',{'counter':'COUNT(*)'}).one()# orresults=qb.count('users').one()SELECTCOUNT(*)AS`counter`FROM`users`;ORDER BYresults=qb.select({'b':'branches'},['b.id','b.name'])\.where([['b.id','>',1],'and',['b.parent_id',1]])\.order_by('b.id','desc')\.all()# or since 0.3.4results=qb.select({'b':'branches'},['b.id','b.name'])\.where([['b.id','>',1],'and',['b.parent_id',1]])\.order_by('b.id desc')\.all()SELECT`b`.`id`,`b`.`name`FROM`branches`AS`b`WHERE(`b`.`id`>1)AND(`b`.`parent_id`=1)ORDERBY`b`.`id`DESC;GROUP BYandHAVINGresults=qb.select('posts',['id','category','title'])\.where([['views','>=',1000]])\.group_by('category')\.all()SELECT`id`,`category`,`title`FROM`posts`WHERE(`views`>=1000)GROUPBY`category`;groups=qb.select('orders',{'month_num':'MONTH(`created_at`)','total':'SUM(`total`)'})\.where([['YEAR(`created_at`)','=',2020]])\.group_by('month_num')\.having([['total','=',20000]])\.all()# or since 0.3.4groups=qb.select('orders',{'month_num':'MONTH(`created_at`)','total':'SUM(`total`)'})\.where([['YEAR(`created_at`)',2020]])\.group_by('month_num')\.having([['total',20000]])\.all()SELECTMONTH(`created_at`)AS`month_num`,SUM(`total`)AS`total`FROM`orders`WHERE(YEAR(`created_at`)=2020)GROUPBY`month_num`HAVING(`total`=20000);JOIN. SupportsINNER,LEFT OUTER,RIGHT OUTER,FULL OUTERandCROSSjoins (INNERis by default)results=qb.select({'u':'users'},['u.id','u.email','u.username',{'perms':'groups.permissions'}])\.join('groups',['u.group_id','groups.id'])\.limit(5)\.all()SELECT`u`.`id`,`u`.`email`,`u`.`username`,`groups`.`permissions`AS`perms`FROM`users`AS`u`INNERJOIN`groups`ON`u`.`group_id`=`groups`.`id`LIMIT5;results=qb.select({'cp':'cabs_printers'},['cp.id','cp.cab_id',{'cab_name':'cb.name'},'cp.printer_id',{'printer_name':'p.name'},{'cartridge_type':'c.name'},'cp.comment'])\.join({'cb':'cabs'},['cp.cab_id','cb.id'])\.join({'p':'printer_models'},['cp.printer_id','p.id'])\.join({'c':'cartridge_types'},'p.cartridge_id=c.id')\.where([['cp.cab_id','in',[11,12,13]],'or',['cp.cab_id','=',5],'and',['p.id','>','c.id']])\.all()SELECT`cp`.`id`,`cp`.`cab_id`,`cb`.`name`AS`cab_name`,`cp`.`printer_id`,`p`.`name`AS`printer_name`,`c`.`name`AS`cartridge_type`,`cp`.`comment`FROM`cabs_printers`AS`cp`INNERJOIN`cabs`AS`cb`ON`cp`.`cab_id`=`cb`.`id`INNERJOIN`printer_models`AS`p`ON`cp`.`printer_id`=`p`.`id`INNERJOIN`cartridge_types`AS`c`ONp.cartridge_id=c.idWHERE(`cp`.`cab_id`IN(11,12,13))OR(`cp`.`cab_id`=5)AND(`p`.`id`>`c`.`id`);# since 0.3.4results=qb.select({'cp':'cabs_printers'},['cp.id','cp.cab_id',{'cab_name':'cb.name'},'cp.printer_id',{'cartridge_id':'c.id'},{'printer_name':'p.name'},{'cartridge_type':'c.name'},'cp.comment'])\.join({'cb':'cabs'},['cp.cab_id','cb.id'])\.join({'p':'printer_models'},['cp.printer_id','p.id'])\.join({'c':'cartridge_types'},['p.cartridge_id','c.id'])\.group_by(['cp.printer_id','cartridge_id'])\.order_by(['cp.cab_id','cp.printer_id desc'])\.all()SELECT`cp`.`id`,`cp`.`cab_id`,`cb`.`name`AS`cab_name`,`cp`.`printer_id`,`c`.`id`AS`cartridge_id`,`p`.`name`AS`printer_name`,`c`.`name`AS`cartridge_type`,`cp`.`comment`FROM`cabs_printers`AS`cp`INNERJOIN`cabs`AS`cb`ON`cp`.`cab_id`=`cb`.`id`INNERJOIN`printer_models`AS`p`ON`cp`.`printer_id`=`p`.`id`INNERJOIN`cartridge_types`AS`c`ON`p`.`cartridge_id`=`c`.`id`GROUPBY`cp`.`printer_id`,`cartridge_id`ORDERBY`cp`.`cab_id`ASC,`cp`.`printer_id`DESC;Insert a rownew_id=qb.insert('groups',{'name':'Moderator','permissions':'moderator'}).go()INSERTINTO`groups`(`name`,`permissions`)VALUES('Moderator','moderator');Insert many rowsqb.insert('groups',[['name','role'],['Moderator','moderator'],['Moderator2','moderator'],['User','user'],['User2','user']]).go()INSERTINTO`groups`(`name`,`role`)VALUES('Moderator','moderator'),('Moderator2','moderator'),('User','user'),('User2','user');Update a rowqb.update('users',{'username':'John Doe','status':'new status'})\.where([['id','=',7]])\.limit()\.go()# or since 0.3.4qb.update('users',{'username':'John Doe','status':'new status'})\.where([['id',7]])\.limit()\.go()UPDATE`users`SET`username`='John Doe',`status`='new status'WHERE`id`=7LIMIT1;Update rowsqb.update('posts',{'status':'published'})\.where([['YEAR(`updated_at`)','>',2020]])\.go()UPDATE`posts`SET`status`='published'WHERE(YEAR(`updated_at`)>2020);Delete a rowqb.delete('users')\.where([['name','=','John']])\.limit()\.go()# or since 0.3.4qb.delete('users')\.where([['name','John']])\.limit()\.go()DELETEFROM`users`WHERE`name`='John'LIMIT1;Delete rowsqb.delete('comments')\.where([['user_id','=',10]])\.go()# or since 0.3.4qb.delete('comments')\.where([['user_id',10]])\.go()DELETEFROM`comments`WHERE`user_id`=10;Truncate a tableThis method will be moved to another classqb.truncate('users').go()TRUNCATETABLE`users`;Drop a tableThis method will be moved to another classqb.drop('temporary').go()DROPTABLEIFEXISTS`temporary`;