__sql__.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter database
  5. name:__sql__.py
  6. author:rabin
  7. """
  8. from demeter import *
  9. class Fields(object):
  10. def __init__(self, type='', default='', primaryKey=False, autoIncrement=False, null=True, unique=False, check='', constraint='', comment='', uuid='', index=False, indexs=False, md5=False, match='', manage=''):
  11. self.type = type
  12. self.default = default
  13. self.primaryKey = primaryKey
  14. self.autoIncrement = autoIncrement
  15. self.null = null
  16. self.unique = unique
  17. self.check = check
  18. self.constraint = constraint
  19. self.comment = comment
  20. self.uuid = uuid
  21. self.index = index
  22. self.indexs = indexs
  23. self.md5 = md5
  24. self.key = Counter().inc()
  25. self.match = match
  26. self.value = ''
  27. self.argv = ''
  28. self.bindValue = ''
  29. self.expValue = '='
  30. self.logicValue = 'and'
  31. self.manage = manage
  32. def assgin(self, value, exp='=', logic='and'):
  33. self.add(value)
  34. self.exp(exp)
  35. self.logic(logic)
  36. return self
  37. def bind(self, value):
  38. self.bindValue = value
  39. return self
  40. def exp(self, value):
  41. if type(self.expValue) != list:
  42. self.expValue = []
  43. self.expValue.append(value)
  44. return self
  45. def logic(self, value):
  46. if type(self.logicValue) != list:
  47. self.logicValue = []
  48. self.logicValue.append(value)
  49. return self
  50. def val(self, value, exp='=', logic='and'):
  51. if type(value) == list:
  52. length = len(value)
  53. if length <= 1:
  54. value = value[0]
  55. self.value = value
  56. if not self.expValue:
  57. self.exp(exp)
  58. if not self.logicValue:
  59. self.logic(logic)
  60. return self
  61. def getArgv(self):
  62. return self.argv
  63. def getVal(self):
  64. return self.value
  65. def getBind(self):
  66. return self.bindValue
  67. def getExp(self):
  68. if not self.expValue:
  69. return ''
  70. if type(self.expValue) == list:
  71. length = len(self.expValue)
  72. if length <= 1:
  73. result = self.expValue[0]
  74. else:
  75. result = self.expValue
  76. else:
  77. result = self.expValue
  78. return result
  79. def getKey(self):
  80. return self.key
  81. def getLogic(self):
  82. if not self.logicValue:
  83. return ''
  84. if type(self.logicValue) == list:
  85. length = len(self.logicValue)
  86. if length <= 1:
  87. result = self.logicValue[0]
  88. else:
  89. result = self.logicValue
  90. else:
  91. result = self.logicValue
  92. return result
  93. def unset(self):
  94. self.argv = None
  95. self.value = None
  96. self.bindValue = None
  97. self.expValue = '='
  98. self.logicValue = 'and'
  99. return self
  100. def add(self, value):
  101. if not self.argv:
  102. self.argv = []
  103. self.argv.append(value)
  104. return self
  105. def ins(self, value):
  106. self.argv = value
  107. self.exp('in')
  108. return self
  109. def nq(self, value):
  110. self.argv = value
  111. self.exp('!=')
  112. return self
  113. def like(self, value):
  114. self.argv = '%' + value + '%'
  115. self.exp('like')
  116. return self
  117. def mlike(self, value):
  118. self.argv = value
  119. self.exp('~')
  120. self.logic('and')
  121. return self
  122. def time(self, value):
  123. self.add(Demeter.mktime(value))
  124. return self
  125. def start(self, value):
  126. self.time(value)
  127. self.exp('>=')
  128. self.logic('and')
  129. return self
  130. def end(self, value):
  131. self.time(value)
  132. self.exp('<=')
  133. self.logic('and')
  134. return self
  135. class Counter(object):
  136. num = 0
  137. instance = None
  138. def __new__(cls, *args, **kwd):
  139. if Counter.instance is None:
  140. Counter.instance = object.__new__(cls, *args, **kwd)
  141. return Counter.instance
  142. def inc(self):
  143. self.num = self.num + 1
  144. return self.num
  145. def dec(self):
  146. self.num = self.num - 1
  147. return self.num
  148. def unset(self):
  149. self.num = 0
  150. return self.num
  151. class Sql(object):
  152. instance = None
  153. def __new__(cls, *args, **kwd):
  154. if Sql.instance is None:
  155. Sql.instance = object.__new__(cls, *args, **kwd)
  156. return Sql.instance
  157. def __init__(self, type):
  158. self.type = type
  159. def drop(self, table, args):
  160. sql = 'DROP TABLE IF EXISTS ' + table
  161. return sql
  162. def alter(self, table, args):
  163. sql = 'ALTER TABLE ' + table + ' ADD COLUMN '
  164. return sql
  165. def create(self, table, args):
  166. create = []
  167. primary = []
  168. unique = []
  169. indexs = []
  170. index = []
  171. comment = {}
  172. for value in args['key']:
  173. key = value[0]
  174. val = args['fields'][key]
  175. if val.primaryKey:
  176. primary.append(key)
  177. if val.unique:
  178. unique.append(key)
  179. if val.index:
  180. index.append((key, val.index))
  181. if val.indexs:
  182. indexs.append(key)
  183. fields = []
  184. fields.append(key)
  185. if val.autoIncrement and self.type == 'postgresql':
  186. fields.append('SERIAL')
  187. else:
  188. fields.append(val.type)
  189. if not val.null:
  190. fields.append('NOT NULL')
  191. if val.autoIncrement and self.type == 'mysql':
  192. fields.append('AUTO_INCREMENT')
  193. #约束
  194. if val.constraint:
  195. fields.append('CONSTRAINT ' + val.constraint)
  196. if val.check:
  197. fields.append('CHECK ' + val.check)
  198. if val.default:
  199. default = val.default
  200. if val.default == 'time':
  201. default = '0'
  202. if '.' in val.default:
  203. temp = val.default.split('.')
  204. default = Demeter.config[temp[0]][temp[1]]
  205. fields.append('DEFAULT \'' + str(default) + '\'')
  206. if val.comment:
  207. if self.type == 'mysql':
  208. fields.append('COMMENT \'' + val.comment + '\'')
  209. else:
  210. comment[key] = val.comment
  211. fields = ' '.join(fields)
  212. create.append(fields)
  213. if primary:
  214. create.append('PRIMARY KEY (' + ','.join(primary) + ')')
  215. if unique:
  216. create.append('UNIQUE (' + ','.join(unique) + ')')
  217. create = ','.join(create)
  218. sql = 'CREATE TABLE ' + table + '(' + create + ')'
  219. sql = self.drop(table, args) + ';' + sql
  220. if indexs:
  221. name = '_'.join(indexs)
  222. value = ','.join(indexs)
  223. sql = sql + ';' + 'CREATE INDEX ' + table + '_' + name +' ON ' + table + '(' + value + ')'
  224. if index:
  225. for value in index:
  226. sql = sql + ';' + 'CREATE INDEX ' + table + '_' + value[0] +' ON ' + table + value[1]
  227. if comment:
  228. if args['table_comment']:
  229. sql = sql + ';' + 'COMMENT ON TABLE ' + table + ' IS \''+args['table_comment']+'\''
  230. for key in comment:
  231. sql = sql + ';' + 'COMMENT ON COLUMN ' + table + '.'+key+' IS \''+comment[key]+'\''
  232. return sql
  233. def insert(self, table, args):
  234. fields = []
  235. values = []
  236. for value in args['key']:
  237. key = value[0]
  238. val = args['fields'][key].getBind()
  239. if val:
  240. values.append(val)
  241. fields.append(key)
  242. fields = ','.join(fields)
  243. values = ','.join(values)
  244. sql = 'INSERT INTO ' + table + ' (' + fields + ') VALUES (' + values + ')'
  245. if self.type == 'postgresql':
  246. sql = sql + ' RETURNING id'
  247. return sql
  248. def update(self, table, args):
  249. fields = []
  250. for key in args['set']:
  251. fields.append(key + ' = %s')
  252. fields = ','.join(fields)
  253. sql = 'UPDATE ' + table + ' SET ' + fields + self.where(args['key'], args['fields'])
  254. return sql
  255. def delete(self, table, args):
  256. sql = 'DELETE FROM ' + table + self.where(args['fields'])
  257. return sql
  258. def select(self, table, args):
  259. string = ' FROM ' + table + self.where(args['key'], args['fields']) + ' ' + self.group(args['group'])
  260. sql = ''
  261. if args['page']:
  262. sql = 'SELECT count(1) as total' + string + ';'
  263. sql = sql + 'SELECT ' + args['col'] + string + ' ' + self.order(args['order']) + ' ' + self.limit(args['limit'], args['page'])
  264. return sql
  265. def where(self, key, fields):
  266. fields = self.fields(key, fields)
  267. if fields:
  268. return ' WHERE ' + fields
  269. return ''
  270. def fields(self, key, fields):
  271. result = ''
  272. k = 0
  273. for value in key:
  274. key = value[0]
  275. field = fields[key]
  276. bind = field.getBind()
  277. val = field.getVal()
  278. logic = field.getLogic()
  279. exp = field.getExp()
  280. if type(val) == list and val:
  281. n = 0
  282. for i in val:
  283. data = self.field(field, bind, key, k, logic[n], exp[n])
  284. n = n + 1
  285. if data:
  286. result = result + data
  287. k = 1
  288. else:
  289. data = self.field(field, bind, key, k, logic, exp)
  290. if data:
  291. result = result + data
  292. k = 1
  293. return result
  294. def field(self, field, val, key, k, logic, exp):
  295. result = ''
  296. if val:
  297. if k == 0:
  298. logic = ''
  299. else:
  300. logic = ' ' + logic
  301. result = logic + ' ' + key + ' ' + exp + ' ' + str(val)
  302. return result
  303. def order(self, value):
  304. result = ''
  305. if value:
  306. result = ' ORDER BY ' + value
  307. return result
  308. def group(self, value):
  309. result = ''
  310. if value:
  311. result = ' GROUP BY ' + value
  312. return result
  313. def limit(self, value, page):
  314. result = ''
  315. if page:
  316. value = str((int(page['current'])-1) * page['num']) + ',' + str(page['num'])
  317. if value:
  318. value = value.split(',')
  319. if self.type == 'mysql':
  320. result = ' LIMIT ' + value[0] + ',' + value[1]
  321. elif self.type == 'postgresql':
  322. result = ' LIMIT ' + value[1] + ' OFFSET ' + value[0]
  323. return result