model.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter database
  5. name:__base__.py
  6. author:rabin
  7. """
  8. import os
  9. import uuid
  10. import short_url
  11. import json
  12. import traceback
  13. import re
  14. import math
  15. from demeter.core import *
  16. class Model(object):
  17. __table__ = ''
  18. __comment__ = ''
  19. def __init__(self, type, db, config):
  20. self.db = db
  21. self._type = type
  22. self._config = config
  23. self._table = self._config['prefix'] + '_' + self.__table__
  24. self._set = ''
  25. self._bind = {}
  26. self._attr = {}
  27. self._key = {}
  28. self.create()
  29. def cur(self):
  30. return self.db.cursor()
  31. def query(self, sql, method='select', fetch='fetchall'):
  32. cur = self.cur()
  33. bind = []
  34. if self._set:
  35. for key in self._set:
  36. if self._set[key] == 'time':
  37. self._set[key] = self.time()
  38. elif self._set[key] == 'True':
  39. self._set[key] = True
  40. elif self._set[key] == 'False':
  41. self._set[key] = False
  42. elif 'date' in key:
  43. self._set[key] = self.mktime(self._set[key])
  44. bind.append(self._set[key])
  45. for value in self._key:
  46. if value[0] in self._bind and self._bind[value[0]] != None:
  47. val = self._bind[value[0]]
  48. self._attr[value[0]].unset()
  49. if type(val) == list and val:
  50. for i in val:
  51. bind.append(i)
  52. else:
  53. bind.append(val)
  54. if method == 'select' and ';' in sql:
  55. temp = sql.split(';')
  56. sql = temp[1]
  57. totalSql = temp[0]
  58. cur.execute(totalSql, bind)
  59. Demeter.config['page']['totalNum'] = self.fetch(cur, 'fetchone', 'count')
  60. Demeter.config['page']['total'] = int(math.ceil(round(float(Demeter.config['page']['totalNum'])/float(Demeter.config['page']['num']),2)))
  61. cur.execute(sql, bind)
  62. if method == 'select':
  63. return self.fetch(cur, fetch)
  64. id = True
  65. if method == 'insert':
  66. id = cur.fetchone()[0]
  67. self.db.commit()
  68. self._set = {}
  69. return id
  70. """
  71. try:
  72. except Exception, e:
  73. print e.message
  74. os._exit(0)
  75. """
  76. def fetch(self, cur, type, method = ''):
  77. load = getattr(cur, type)
  78. rows = load()
  79. if type == 'fetchall':
  80. result = []
  81. if rows:
  82. for key in rows:
  83. row = {}
  84. i = 0
  85. for v in key:
  86. row[self._key[i][0]] = v
  87. i = i + 1
  88. result.append(row)
  89. elif method == 'count':
  90. return rows[0]
  91. else:
  92. result = {}
  93. i = 0
  94. if rows:
  95. for key in rows:
  96. if not key:
  97. key = ''
  98. result[self._key[i][0]] = key
  99. i = i + 1
  100. return result
  101. def attr(self, method):
  102. fields = vars(self.__class__)
  103. self._attr = {}
  104. self._bind = {}
  105. self._key = {}
  106. col = (int, str, long, float, unicode, bool, uuid.UUID)
  107. for field in fields:
  108. if isinstance(fields[field], Fields):
  109. self._attr[field] = fields[field]
  110. self._key[field] = self._attr[field].getKey()
  111. insert = (method == 'insert')
  112. if insert and self._attr[field].uuid:
  113. self.setUuid(field, col)
  114. bind = False
  115. val = self._attr[field].getArgv()
  116. if val:
  117. bind = True
  118. else:
  119. val = getattr(self, field)
  120. if isinstance(val, col):
  121. setattr(self, field, self._attr[field])
  122. bind = True
  123. elif insert and self._attr[field].default:
  124. val = self._attr[field].default
  125. bind = True
  126. if val == 'time':
  127. val = self.time()
  128. elif '.' in val:
  129. temp = val.split('.')
  130. val = Demeter.config[temp[0]][temp[1]]
  131. elif method == 'select' and self._attr[field].default and field == 'state':
  132. val = self._attr[field].default
  133. bind = True
  134. if bind and val != None:
  135. if type(val) == list:
  136. length = len(val)
  137. if length <= 1:
  138. val = val[0]
  139. if insert and self._attr[field].md5:
  140. val = self.createMd5(val)
  141. if self._attr[field].type == 'boolean' and isinstance(val, (str, unicode)):
  142. val = Demeter.bool(val)
  143. #self.check(field, val, self._attr[field])
  144. if type(val) == list:
  145. val = tuple(val)
  146. self._bind[field] = val
  147. self._attr[field].val(self._bind[field])
  148. self._attr[field].bind('%s')
  149. self._key = sorted(self._key.items(), key=lambda d:d[1], reverse = False)
  150. Counter().unset()
  151. def check(self, field, val, attr):
  152. if attr.match == 'not':
  153. if not val:
  154. Demeter.error(field + ' not exists')
  155. elif attr.match:
  156. result = re.search(attr.match, val)
  157. if not result:
  158. Demeter.error(field + ' not match:' + attr.match)
  159. def time(self):
  160. return Demeter.time()
  161. def mktime(self, value):
  162. return Demeter.mktime(value)
  163. def setUuid(self, field, col):
  164. id = getattr(self, self._attr[field].uuid)
  165. if isinstance(id, col):
  166. system = short_url.encode_url(id)
  167. else:
  168. system = self._attr[field].uuid
  169. name = system + '.' + self.__table__
  170. result = uuid.uuid5(uuid.uuid1(), name)
  171. result = str(result)
  172. setattr(self, field, result)
  173. def createMd5(self, value):
  174. return Demeter.md5(value, salt=True)
  175. def createState(self):
  176. if 'create' in self._config:
  177. create = Demeter.bool(self._config['create'])
  178. if create:
  179. return Demeter.runtime(self._type, self.__table__, json.dumps(self._key))
  180. return False
  181. def drop(self):
  182. return self.handle('drop')
  183. def create(self):
  184. return self.handle('create')
  185. def insert(self):
  186. return self.handle('insert')
  187. def update(self, *args, **kwargs):
  188. if args:
  189. self._set = args[0]
  190. else:
  191. self._set = kwargs
  192. return self.handle('update', set=self._set)
  193. def delete(self):
  194. return self.handle('delete')
  195. def select(self, type='fetchall',col = '*', order = 'cdate desc', group = '', limit = '0,100', page=False):
  196. pageConfig = {}
  197. if page and 'page' in Demeter.config:
  198. pageConfig['current'] = Demeter.config['page']['current']
  199. if page == True:
  200. pageConfig['num'] = 15
  201. elif 'num' in page:
  202. pageConfig['num'] = page['num']
  203. Demeter.config['page']['num'] = pageConfig['num']
  204. return self.handle('select', type=type, col=col, order=order, group=group, limit=limit, page=pageConfig)
  205. def manage(self):
  206. self.attr(method)
  207. return
  208. def handle(self, method='select', type='fetchall', col = '*', order = '', group = '', limit = '0,100', page=False, set = ''):
  209. self.attr(method)
  210. if method == 'create':
  211. create = self.createState()
  212. if create == False:
  213. return False
  214. if type == 'fetchone':
  215. limit = '0,1'
  216. load = getattr(Sql(self._type), method)
  217. return self.query(load(self._table, {'key':self._key, 'fields':self._attr, 'col':col, 'order':order, 'group':group, 'limit':limit, 'page':page, 'set':set, 'table_comment':self.__comment__}), method, type)
  218. class Fields(object):
  219. 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=''):
  220. self.type = type
  221. self.default = default
  222. self.primaryKey = primaryKey
  223. self.autoIncrement = autoIncrement
  224. self.null = null
  225. self.unique = unique
  226. self.check = check
  227. self.constraint = constraint
  228. self.comment = comment
  229. self.uuid = uuid
  230. self.index = index
  231. self.indexs = indexs
  232. self.md5 = md5
  233. self.key = Counter().inc()
  234. self.match = match
  235. self.value = ''
  236. self.argv = ''
  237. self.bindValue = ''
  238. self.expValue = '='
  239. self.logicValue = 'and'
  240. self.manage = manage
  241. def assgin(self, value, exp='=', logic='and'):
  242. self.add(value)
  243. self.exp(exp)
  244. self.logic(logic)
  245. return self
  246. def bind(self, value):
  247. self.bindValue = value
  248. return self
  249. def exp(self, value):
  250. if type(self.expValue) != list:
  251. self.expValue = []
  252. self.expValue.append(value)
  253. return self
  254. def logic(self, value):
  255. if type(self.logicValue) != list:
  256. self.logicValue = []
  257. self.logicValue.append(value)
  258. return self
  259. def val(self, value, exp='=', logic='and'):
  260. if type(value) == list:
  261. length = len(value)
  262. if length <= 1:
  263. value = value[0]
  264. self.value = value
  265. if not self.expValue:
  266. self.exp(exp)
  267. if not self.logicValue:
  268. self.logic(logic)
  269. return self
  270. def getArgv(self):
  271. return self.argv
  272. def getVal(self):
  273. return self.value
  274. def getBind(self):
  275. return self.bindValue
  276. def getExp(self):
  277. if not self.expValue:
  278. return ''
  279. if type(self.expValue) == list:
  280. length = len(self.expValue)
  281. if length <= 1:
  282. result = self.expValue[0]
  283. else:
  284. result = self.expValue
  285. else:
  286. result = self.expValue
  287. return result
  288. def getKey(self):
  289. return self.key
  290. def getLogic(self):
  291. if not self.logicValue:
  292. return ''
  293. if type(self.logicValue) == list:
  294. length = len(self.logicValue)
  295. if length <= 1:
  296. result = self.logicValue[0]
  297. else:
  298. result = self.logicValue
  299. else:
  300. result = self.logicValue
  301. return result
  302. def unset(self):
  303. self.argv = None
  304. self.value = None
  305. self.bindValue = None
  306. self.expValue = '='
  307. self.logicValue = 'and'
  308. return self
  309. def add(self, value):
  310. if not self.argv:
  311. self.argv = []
  312. self.argv.append(value)
  313. return self
  314. def ins(self, value):
  315. self.argv = value
  316. self.exp('in')
  317. return self
  318. def nq(self, value):
  319. self.argv = value
  320. self.exp('!=')
  321. return self
  322. def like(self, value):
  323. self.argv = '%' + value + '%'
  324. self.exp('like')
  325. return self
  326. def mlike(self, value):
  327. self.argv = value
  328. self.exp('~')
  329. self.logic('and')
  330. return self
  331. def time(self, value):
  332. self.add(Demeter.mktime(value))
  333. return self
  334. def start(self, value):
  335. self.time(value)
  336. self.exp('>=')
  337. self.logic('and')
  338. return self
  339. def end(self, value):
  340. self.time(value)
  341. self.exp('<=')
  342. self.logic('and')
  343. return self
  344. class Counter(object):
  345. num = 0
  346. instance = None
  347. def __new__(cls, *args, **kwd):
  348. if Counter.instance is None:
  349. Counter.instance = object.__new__(cls, *args, **kwd)
  350. return Counter.instance
  351. def inc(self):
  352. self.num = self.num + 1
  353. return self.num
  354. def dec(self):
  355. self.num = self.num - 1
  356. return self.num
  357. def unset(self):
  358. self.num = 0
  359. return self.num
  360. class Sql(object):
  361. instance = None
  362. def __new__(cls, *args, **kwd):
  363. if Sql.instance is None:
  364. Sql.instance = object.__new__(cls, *args, **kwd)
  365. return Sql.instance
  366. def __init__(self, type):
  367. self.type = type
  368. def drop(self, table, args):
  369. sql = 'DROP TABLE IF EXISTS ' + table
  370. return sql
  371. def alter(self, table, args):
  372. sql = 'ALTER TABLE ' + table + ' ADD COLUMN '
  373. return sql
  374. def create(self, table, args):
  375. create = []
  376. primary = []
  377. unique = []
  378. indexs = []
  379. index = []
  380. comment = {}
  381. for value in args['key']:
  382. key = value[0]
  383. val = args['fields'][key]
  384. if val.primaryKey:
  385. primary.append(key)
  386. if val.unique:
  387. unique.append(key)
  388. if val.index:
  389. index.append((key, val.index))
  390. if val.indexs:
  391. indexs.append(key)
  392. fields = []
  393. fields.append(key)
  394. if val.autoIncrement and self.type == 'postgresql':
  395. fields.append('SERIAL')
  396. else:
  397. fields.append(val.type)
  398. if not val.null:
  399. fields.append('NOT NULL')
  400. if val.autoIncrement and self.type == 'mysql':
  401. fields.append('AUTO_INCREMENT')
  402. #约束
  403. if val.constraint:
  404. fields.append('CONSTRAINT ' + val.constraint)
  405. if val.check:
  406. fields.append('CHECK ' + val.check)
  407. if val.default:
  408. default = val.default
  409. if val.default == 'time':
  410. default = '0'
  411. if '.' in val.default:
  412. temp = val.default.split('.')
  413. default = Demeter.config[temp[0]][temp[1]]
  414. fields.append('DEFAULT \'' + str(default) + '\'')
  415. if val.comment:
  416. if self.type == 'mysql':
  417. fields.append('COMMENT \'' + val.comment + '\'')
  418. else:
  419. comment[key] = val.comment
  420. fields = ' '.join(fields)
  421. create.append(fields)
  422. if primary:
  423. create.append('PRIMARY KEY (' + ','.join(primary) + ')')
  424. if unique:
  425. create.append('UNIQUE (' + ','.join(unique) + ')')
  426. create = ','.join(create)
  427. sql = 'CREATE TABLE ' + table + '(' + create + ')'
  428. sql = self.drop(table, args) + ';' + sql
  429. if indexs:
  430. name = '_'.join(indexs)
  431. value = ','.join(indexs)
  432. sql = sql + ';' + 'CREATE INDEX ' + table + '_' + name +' ON ' + table + '(' + value + ')'
  433. if index:
  434. for value in index:
  435. sql = sql + ';' + 'CREATE INDEX ' + table + '_' + value[0] +' ON ' + table + value[1]
  436. if comment:
  437. if args['table_comment']:
  438. sql = sql + ';' + 'COMMENT ON TABLE ' + table + ' IS \''+args['table_comment']+'\''
  439. for key in comment:
  440. sql = sql + ';' + 'COMMENT ON COLUMN ' + table + '.'+key+' IS \''+comment[key]+'\''
  441. return sql
  442. def insert(self, table, args):
  443. fields = []
  444. values = []
  445. for value in args['key']:
  446. key = value[0]
  447. val = args['fields'][key].getBind()
  448. if val:
  449. values.append(val)
  450. fields.append(key)
  451. fields = ','.join(fields)
  452. values = ','.join(values)
  453. sql = 'INSERT INTO ' + table + ' (' + fields + ') VALUES (' + values + ')'
  454. if self.type == 'postgresql':
  455. sql = sql + ' RETURNING id'
  456. return sql
  457. def update(self, table, args):
  458. fields = []
  459. for key in args['set']:
  460. fields.append(key + ' = %s')
  461. fields = ','.join(fields)
  462. sql = 'UPDATE ' + table + ' SET ' + fields + self.where(args['key'], args['fields'])
  463. return sql
  464. def delete(self, table, args):
  465. sql = 'DELETE FROM ' + table + self.where(args['key'], args['fields'])
  466. return sql
  467. def select(self, table, args):
  468. string = ' FROM ' + table + self.where(args['key'], args['fields']) + ' ' + self.group(args['group'])
  469. sql = ''
  470. if args['page']:
  471. sql = 'SELECT count(1) as total' + string + ';'
  472. sql = sql + 'SELECT ' + args['col'] + string + ' ' + self.order(args['order']) + ' ' + self.limit(args['limit'], args['page'])
  473. return sql
  474. def where(self, key, fields):
  475. fields = self.fields(key, fields)
  476. if fields:
  477. return ' WHERE ' + fields
  478. return ''
  479. def fields(self, key, fields):
  480. result = ''
  481. k = 0
  482. for value in key:
  483. key = value[0]
  484. field = fields[key]
  485. bind = field.getBind()
  486. val = field.getVal()
  487. logic = field.getLogic()
  488. exp = field.getExp()
  489. if type(val) == list and val:
  490. n = 0
  491. for i in val:
  492. data = self.field(field, bind, key, k, logic[n], exp[n])
  493. n = n + 1
  494. if data:
  495. result = result + data
  496. k = 1
  497. else:
  498. data = self.field(field, bind, key, k, logic, exp)
  499. if data:
  500. result = result + data
  501. k = 1
  502. return result
  503. def field(self, field, val, key, k, logic, exp):
  504. result = ''
  505. if val:
  506. if k == 0:
  507. logic = ''
  508. else:
  509. logic = ' ' + logic
  510. result = logic + ' ' + key + ' ' + exp + ' ' + str(val)
  511. return result
  512. def order(self, value):
  513. result = ''
  514. if value:
  515. result = ' ORDER BY ' + value
  516. return result
  517. def group(self, value):
  518. result = ''
  519. if value:
  520. result = ' GROUP BY ' + value
  521. return result
  522. def limit(self, value, page):
  523. result = ''
  524. if page:
  525. value = str((int(page['current'])-1) * page['num']) + ',' + str(page['num'])
  526. if value:
  527. value = value.split(',')
  528. if self.type == 'mysql':
  529. result = ' LIMIT ' + value[0] + ',' + value[1]
  530. elif self.type == 'postgresql':
  531. result = ' LIMIT ' + value[1] + ' OFFSET ' + value[0]
  532. return result