Skip to content

Instantly share code, notes, and snippets.

@yatt
Created June 23, 2011 12:52
Show Gist options
  • Select an option

  • Save yatt/1042478 to your computer and use it in GitHub Desktop.

Select an option

Save yatt/1042478 to your computer and use it in GitHub Desktop.
update/delete google appengine entity by sql like syntax
#! /usr/bin/env python
# coding: utf-8
#
# update/delete google appengine entity by sql like syntax...
#
# sample:
# - update
# noresult('update MyModel set name = \'hoge\', age = 10') # update all entities
# noresult('update MyModel set name = \'fuga\' where id = 10') # update entities which is specified in where clause
# * unavailable - multiple inequality filter property
# noresult('udpate MyModel set name = \'fugo\' where rank > 10')
# - delete
# noresult('delete from MyModel') # delete all entities
# noresult('delete from MyModel where age < 10') # delete entities which is specified in where clause
#
#
#
from google.appengine.ext import db
# ref: http://code.google.com/intl/ja/appengine/docs/python/datastore/overview.html
MAX_BATCH_PUT_OR_DELETE = 500
def noresult(stmt):
lst = stmt.split()
op = lst[0]
model = lst[1] if op == 'update' else lst[2]
def build_query_delete():
q = 'select * from %s' % model
if stmt.find('where') >= 0:
q = q + ' ' + stmt[stmt.index('where'):]
return db.GqlQuery(q)
def build_query_update(key):
q = 'select * from ' + model
b = not (key is None)
c = stmt.find('where') >= 0
if b or c:
q += ' where '
conds = []
if b: conds.append(' __key__ > :1 ')
if c: conds.append(stmt[stmt.index('where')+5:])
q += ' AND '.join(conds)
q += ' order by __key__'
args = [q]
if b: args.append(key)
return db.GqlQuery(*args)
def update(bq, ulist):
key = None
q = bq(key)
while True:
lst = q.fetch(MAX_BATCH_PUT_OR_DELETE)
if len(lst) == 0:
break
for model in lst:
for prop,value in ulist:
setattr(model, prop, value)
db.put(lst)
key = lst[-1].key()
q = bq(key)
def delete(bq):
q = bq()
while True:
lst = q.fetch(MAX_BATCH_PUT_OR_DELETE)
if len(lst) == 0:
break
db.delete(lst)
q = bq()
if op == 'update':
fieldlist = stmt[stmt.index('set')+3:]
if fieldlist.find('where') >= 0:
fieldlist = fieldlist[:fieldlist.index('where')]
fieldlist = fieldlist.split(',')
def convert(item):
index = item.index('=')
prop = item[:index].strip()
value = item[index+1:].strip()
try:
value = eval(value)
except:
pass
return prop,value
updatelist = map(convert, fieldlist)
update(build_query_update, updatelist)
elif op == 'delete':
delete(build_query_delete)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment