model.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. import random
  2. import re
  3. import sqlite3 as db
  4. import sys
  5. import uuid
  6. from datetime import timedelta, datetime
  7. from math import floor
  8. import db_setup
  9. from game import CURRENCY_NAME
  10. from util import random_chars
  11. from debug import debug
  12. # connection: db.Connection = None
  13. # cursor: db.Cursor = None
  14. connection = None # no type annotations in python 3.5
  15. cursor = None # no type annotations in python 3.5
  16. db_name = None
  17. def query_save_name():
  18. global db_name
  19. if debug:
  20. db_name = 'test.db'
  21. return
  22. while True:
  23. save_name = input('Name of the savegame: ')
  24. if re.match(r"[A-Za-z0-9.-]{0,50}", save_name):
  25. db_name = save_name + '.db'
  26. return
  27. else:
  28. print('Must match "[A-Za-z0-9.-]{0,50}"')
  29. def connect(reconnect=False):
  30. global connection
  31. global cursor
  32. global db_name
  33. if reconnect:
  34. connection.commit()
  35. connection.close()
  36. cursor = None
  37. connection = None
  38. db_name = None
  39. if connection is None or cursor is None:
  40. query_save_name()
  41. try:
  42. connection = db.connect(db_name)
  43. # connection.text_factory = lambda x: unicode(x, 'utf-8', 'ignore')
  44. cursor = connection.cursor()
  45. except db.Error as e:
  46. print("Database error %s:" % e.args[0])
  47. sys.exit(1)
  48. # finally:
  49. # if con is not None:
  50. # con.close()
  51. def setup():
  52. connect()
  53. db_setup.setup(cursor)
  54. connection.commit()
  55. def used_key_count():
  56. connect()
  57. cursor.execute('''
  58. SELECT COUNT(*)
  59. FROM keys
  60. WHERE used_by_user_id IS NOT NULL
  61. ''')
  62. return cursor.fetchone()[0]
  63. def login(username, password):
  64. connect()
  65. # do not allow login as bank
  66. if password == '':
  67. return None
  68. cursor.execute('''
  69. SELECT rowid
  70. FROM users
  71. WHERE username = ?
  72. AND password = ?
  73. ''', (username, password))
  74. user_id = cursor.fetchone()
  75. if user_id:
  76. return new_session(user_id)
  77. else:
  78. return None
  79. def register(username, password, game_key):
  80. connect()
  81. if username == '':
  82. return False
  83. if password == '':
  84. return False
  85. cursor.execute('''
  86. INSERT INTO users
  87. (username, password)
  88. VALUES (? , ?)
  89. ''', (username, password))
  90. own(get_user_id_by_name(username), CURRENCY_NAME)
  91. if game_key != '':
  92. if valid_key(game_key):
  93. activate_key(game_key, get_user_id_by_name(username))
  94. return True
  95. def own(user_id, ownable_name):
  96. if not isinstance(ownable_name, str):
  97. return AssertionError('A name must be a string.')
  98. cursor.execute('''
  99. WITH one_ownable_id AS (SELECT rowid FROM ownables WHERE name = ?),
  100. one_user_id AS (SELECT ?)
  101. INSERT INTO ownership (user_id, ownable_id)
  102. SELECT *
  103. FROM one_user_id, one_ownable_id
  104. WHERE NOT EXISTS (
  105. SELECT * FROM ownership
  106. WHERE ownership.user_id IN one_user_id
  107. AND ownership.ownable_id IN one_ownable_id
  108. )
  109. ''', (ownable_name, user_id,))
  110. def send_ownable(from_user_id, to_user_id, ownable_name, amount):
  111. connect()
  112. if amount < 0:
  113. return False
  114. if from_user_id != bank_id():
  115. cursor.execute('''
  116. UPDATE ownership
  117. SET amount = amount - ?
  118. WHERE user_id = ?
  119. AND ownable_id = (SELECT rowid FROM ownables WHERE name = ?)
  120. ''', (amount, from_user_id, ownable_name,))
  121. cursor.execute('''
  122. UPDATE ownership
  123. SET amount = amount + ?
  124. WHERE user_id = ?
  125. AND ownable_id = (SELECT rowid FROM ownables WHERE name = ?)
  126. ''', (amount, to_user_id, ownable_name))
  127. return True
  128. def valid_key(key):
  129. connect()
  130. cursor.execute('''
  131. SELECT key
  132. FROM keys
  133. WHERE used_by_user_id IS NULL
  134. AND key = ?
  135. ''', (key,))
  136. if cursor.fetchone():
  137. return True
  138. else:
  139. return False
  140. def new_session(user_id):
  141. connect()
  142. session_id = str(uuid.uuid4())
  143. cursor.execute('''
  144. INSERT INTO SESSIONS
  145. (user_id, session_id)
  146. VALUES (? , ?)
  147. ''', (user_id[0], session_id))
  148. return session_id
  149. def save_key(key):
  150. connect()
  151. cursor.execute('''
  152. INSERT INTO keys
  153. (key)
  154. VALUES (?)
  155. ''', (key,))
  156. def drop_old_sessions():
  157. connect()
  158. cursor.execute('''
  159. DELETE FROM sessions
  160. WHERE
  161. (SELECT COUNT(*) as newer
  162. FROM sessions s2
  163. WHERE user_id = s2.user_id
  164. AND rowid < s2.rowid) >= 10
  165. ''')
  166. def user_exists(username):
  167. connect()
  168. cursor.execute('''
  169. SELECT rowid
  170. FROM users
  171. WHERE username = ?
  172. ''', (username,))
  173. if cursor.fetchone():
  174. return True
  175. else:
  176. return False
  177. def unused_keys():
  178. connect()
  179. cursor.execute('''
  180. SELECT key
  181. FROM keys
  182. WHERE used_by_user_id IS NULL
  183. ''')
  184. return [str(key[0]).strip().upper() for key in cursor.fetchall()]
  185. def get_user_id_by_session_id(session_id):
  186. connect()
  187. cursor.execute('''
  188. SELECT users.rowid
  189. FROM sessions, users
  190. WHERE sessions.session_id = ?
  191. AND users.rowid = sessions.user_id
  192. ''', (session_id,))
  193. ids = cursor.fetchone()
  194. if not ids:
  195. return False
  196. return ids[0]
  197. def get_user_id_by_name(username):
  198. connect()
  199. cursor.execute('''
  200. SELECT users.rowid
  201. FROM users
  202. WHERE username = ?
  203. ''', (username,))
  204. return cursor.fetchone()[0]
  205. def get_user_ownership(user_id):
  206. connect()
  207. cursor.execute('''
  208. SELECT
  209. ownables.name,
  210. ownership.amount,
  211. COALESCE (
  212. CASE -- sum score for each of the users ownables
  213. WHEN ownership.ownable_id = ? THEN 1
  214. ELSE (SELECT price
  215. FROM transactions
  216. WHERE ownable_id = ownership.ownable_id
  217. ORDER BY dt DESC
  218. LIMIT 1)
  219. END, 0) AS price,
  220. (SELECT MAX("limit")
  221. FROM orders, ownership o2
  222. WHERE o2.rowid = orders.ownership_id
  223. AND o2.ownable_id = ownership.ownable_id
  224. AND buy
  225. AND NOT stop_loss) AS bid,
  226. (SELECT MIN("limit")
  227. FROM orders, ownership o2
  228. WHERE o2.rowid = orders.ownership_id
  229. AND o2.ownable_id = ownership.ownable_id
  230. AND NOT buy
  231. AND NOT stop_loss) AS ask
  232. FROM ownership, ownables
  233. WHERE user_id = ?
  234. AND ownership.amount > 0
  235. AND ownership.ownable_id = ownables.rowid
  236. ''', (currency_id(), user_id,))
  237. return cursor.fetchall()
  238. def activate_key(key, user_id):
  239. connect()
  240. cursor.execute('''
  241. UPDATE keys
  242. SET used_by_user_id = ?
  243. WHERE used_by_user_id IS NULL
  244. AND key = ?
  245. ''', (user_id, key,))
  246. send_ownable(bank_id(), user_id, CURRENCY_NAME, 1000)
  247. def bank_id():
  248. connect()
  249. cursor.execute('''
  250. SELECT users.rowid
  251. FROM users
  252. WHERE username = 'bank'
  253. ''')
  254. return cursor.fetchone()[0]
  255. def valid_session_id(session_id):
  256. connect()
  257. cursor.execute('''
  258. SELECT rowid
  259. FROM sessions
  260. WHERE session_id = ?
  261. ''', (session_id,))
  262. if cursor.fetchone():
  263. return True
  264. else:
  265. return False
  266. def get_user_orders(user_id):
  267. connect()
  268. cursor.execute('''
  269. SELECT
  270. CASE
  271. WHEN orders.buy THEN 'Buy'
  272. ELSE 'Sell'
  273. END,
  274. ownables.name,
  275. (orders.ordered_amount - orders.executed_amount) || '/' || orders.ordered_amount,
  276. orders."limit",
  277. CASE
  278. WHEN orders."limit" IS NULL THEN NULL
  279. WHEN orders.stop_loss THEN 'Yes'
  280. ELSE 'No'
  281. END,
  282. datetime(orders.expiry_dt),
  283. orders.rowid
  284. FROM orders, ownables, ownership
  285. WHERE ownership.user_id = ?
  286. AND ownership.ownable_id = ownables.rowid
  287. AND orders.ownership_id = ownership.rowid
  288. ORDER BY ownables.name ASC, orders.stop_loss ASC, orders.buy DESC, orders."limit" ASC
  289. ''', (user_id,))
  290. return cursor.fetchall()
  291. def get_ownable_orders(ownable_id):
  292. connect()
  293. cursor.execute('''
  294. SELECT
  295. CASE
  296. WHEN orders.buy THEN 'Buy'
  297. ELSE 'Sell'
  298. END,
  299. ownables.name,
  300. orders.ordered_amount - orders.executed_amount,
  301. orders."limit",
  302. CASE
  303. WHEN orders."limit" IS NULL THEN NULL
  304. WHEN orders.stop_loss THEN 'Yes'
  305. ELSE 'No'
  306. END,
  307. datetime(orders.expiry_dt),
  308. orders.rowid
  309. FROM orders, ownables, ownership
  310. WHERE ownership.ownable_id = ?
  311. AND ownership.ownable_id = ownables.rowid
  312. AND orders.ownership_id = ownership.rowid
  313. ORDER BY ownables.name ASC, orders.stop_loss ASC, orders.buy DESC, orders."limit" ASC
  314. ''', (ownable_id,))
  315. return cursor.fetchall()
  316. def sell_ordered_amount(user_id, ownable_id):
  317. connect()
  318. # if ownable_id == currency_id():
  319. # return 0
  320. cursor.execute('''
  321. SELECT COALESCE(SUM(orders.ordered_amount - orders.executed_amount),0)
  322. FROM orders, ownership
  323. WHERE ownership.rowid = orders.ownership_id
  324. AND ownership.user_id = ?
  325. AND ownership.ownable_id = ?
  326. AND NOT orders.buy
  327. ''', (user_id, ownable_id))
  328. return cursor.fetchone()[0]
  329. def user_owns_at_least(amount, user_id, ownable_id):
  330. connect()
  331. if not isinstance(amount, float) and not isinstance(amount, int):
  332. # comparison of float with strings does not work so well in sql
  333. raise AssertionError()
  334. cursor.execute('''
  335. SELECT rowid
  336. FROM ownership
  337. WHERE user_id = ?
  338. AND ownable_id = ?
  339. AND amount - ? >= ?
  340. ''', (user_id, ownable_id, sell_ordered_amount(user_id, ownable_id), amount))
  341. if cursor.fetchone():
  342. return True
  343. else:
  344. return False
  345. def news():
  346. connect()
  347. cursor.execute('''
  348. SELECT * FROM
  349. (SELECT *
  350. FROM news
  351. ORDER BY dt DESC
  352. LIMIT 20) n
  353. ORDER BY dt ASC
  354. ''')
  355. return cursor.fetchall()
  356. def ownable_name_exists(name):
  357. connect()
  358. cursor.execute('''
  359. SELECT rowid
  360. FROM ownables
  361. WHERE name = ?
  362. ''', (name,))
  363. if cursor.fetchone():
  364. return True
  365. else:
  366. return False
  367. def new_stock(timeout=60, name=None):
  368. connect()
  369. while name is None:
  370. name = random_chars(6)
  371. if ownable_name_exists(name):
  372. name = None
  373. cursor.execute('''
  374. INSERT INTO ownables(name)
  375. VALUES (?)
  376. ''', (name,))
  377. cursor.execute('''
  378. INSERT INTO news(title)
  379. VALUES (?)
  380. ''', ('A new stock can now be bought: ' + name,))
  381. if random.getrandbits(1):
  382. cursor.execute('''
  383. INSERT INTO news(title)
  384. VALUES (?)
  385. ''', ('Experts expect the price of ' + name + ' to fall',))
  386. else:
  387. cursor.execute('''
  388. INSERT INTO news(title)
  389. VALUES (?)
  390. ''', ('Experts expect the price of ' + name + ' to rise',))
  391. amount = random.randrange(100, 10000)
  392. price = random.randrange(10000, 20000) / amount
  393. ownable_id = ownable_id_by_name(name)
  394. own(bank_id(), name)
  395. bank_order(False,
  396. ownable_id,
  397. price,
  398. amount,
  399. timeout)
  400. return name
  401. def new_stocks(timeout=60, count=1):
  402. return [new_stock(timeout=timeout) for _ in range(count)]
  403. def ownable_id_by_name(ownable_name):
  404. connect()
  405. cursor.execute('''
  406. SELECT rowid
  407. FROM ownables
  408. WHERE name = ?
  409. ''', (ownable_name,))
  410. return cursor.fetchone()[0]
  411. def get_ownership_id(ownable_id, user_id):
  412. connect()
  413. cursor.execute('''
  414. SELECT rowid
  415. FROM ownership
  416. WHERE ownable_id = ?
  417. AND user_id = ?
  418. ''', (ownable_id, user_id,))
  419. return cursor.fetchone()[0]
  420. def currency_id():
  421. connect()
  422. cursor.execute('''
  423. SELECT rowid
  424. FROM ownables
  425. WHERE name = ?
  426. ''', (CURRENCY_NAME,))
  427. return cursor.fetchone()[0]
  428. def user_money(user_id):
  429. connect()
  430. cursor.execute('''
  431. SELECT amount
  432. FROM ownership
  433. WHERE user_id = ?
  434. AND ownable_id = ?
  435. ''', (user_id, currency_id()))
  436. return cursor.fetchone()[0]
  437. def delete_order(order_id):
  438. connect()
  439. cursor.execute('''
  440. DELETE FROM orders
  441. WHERE rowid = ?
  442. ''', (order_id,))
  443. def current_value(ownable_id):
  444. connect()
  445. cursor.execute('''SELECT price
  446. FROM transactions
  447. WHERE ownable_id = ?
  448. ORDER BY dt DESC
  449. LIMIT 1
  450. ''', (ownable_id,))
  451. return cursor.fetchone()[0]
  452. def execute_orders(ownable_id):
  453. connect()
  454. while True:
  455. # find order to execute
  456. cursor.execute('''
  457. SELECT buy_order.*, sell_order.*, buyer.user_id, seller.user_id, buy_order.rowid, sell_order.rowid
  458. FROM orders buy_order, orders sell_order, ownership buyer, ownership seller
  459. WHERE buy_order.buy AND NOT sell_order.buy
  460. AND buyer.rowid = buy_order.ownership_id
  461. AND seller.rowid = sell_order.ownership_id
  462. AND buyer.ownable_id = ?
  463. AND seller.ownable_id = ?
  464. AND (buy_order."limit" IS NULL
  465. OR sell_order."limit" IS NULL
  466. OR (sell_order."limit" <= buy_order."limit"
  467. AND NOT sell_order.stop_loss
  468. AND NOT buy_order.stop_loss))
  469. ORDER BY CASE WHEN sell_order."limit" IS NULL THEN 0 ELSE 1 END ASC,
  470. CASE WHEN buy_order."limit" IS NULL THEN 0 ELSE 1 END ASC,
  471. buy_order."limit" DESC,
  472. sell_order."limit" ASC,
  473. buy_order.ordered_amount - buy_order.executed_amount DESC,
  474. sell_order.ordered_amount - sell_order.executed_amount DESC
  475. LIMIT 1
  476. ''', (ownable_id, ownable_id,))
  477. matching_orders = cursor.fetchone()
  478. # return type: (ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  479. # ownership_id,buy,limit,stop_loss,ordered_amount,executed_amount,expiry_dt,
  480. # user_id,user_id,rowid,rowid)
  481. if not matching_orders:
  482. break
  483. buy_ownership_id, _, buy_limit, _, buy_order_amount, buy_executed_amount, buy_expiry_dt, \
  484. sell_ownership_id, _, sell_limit, _, sell_order_amount, sell_executed_amount, sell_expiry_dt, \
  485. buyer_id, seller_id, buy_order_id, sell_order_id \
  486. = matching_orders
  487. if buy_limit is None and sell_limit is None:
  488. price = current_value(ownable_id)
  489. elif buy_limit is None:
  490. price = sell_limit
  491. elif sell_limit is None:
  492. price = buy_limit
  493. else: # both not NULL
  494. price = (float(sell_limit) + float(buy_limit)) / 2
  495. if price == 0:
  496. raise AssertionError()
  497. buyer_money = user_money(buyer_id)
  498. amount = min(buy_order_amount - buy_executed_amount,
  499. sell_order_amount - sell_executed_amount,
  500. floor(buyer_money / price))
  501. if amount == 0: # probable because buyer has not enough money
  502. delete_order(buy_order_id)
  503. continue
  504. buy_order_finished = (buy_order_amount - buy_executed_amount - amount <= 0) or (
  505. buyer_money - amount * price < price)
  506. sell_order_finished = (sell_order_amount - sell_executed_amount - amount <= 0)
  507. if price < 0 or amount <= 0:
  508. return AssertionError()
  509. # actually execute the order, but the bank does not send or receive anything
  510. if buyer_id != bank_id(): # buyer pays
  511. cursor.execute('''
  512. UPDATE ownership
  513. SET amount = amount - ?
  514. WHERE user_id = ?
  515. AND ownable_id = ?
  516. ''', (price * amount, buyer_id, currency_id()))
  517. if seller_id != bank_id(): # seller pays
  518. cursor.execute('''
  519. UPDATE ownership
  520. SET amount = amount - ?
  521. WHERE rowid = ?
  522. ''', (amount, sell_ownership_id))
  523. if buyer_id != bank_id(): # buyer receives
  524. cursor.execute('''
  525. UPDATE ownership
  526. SET amount = amount + ?
  527. WHERE rowid = ?
  528. ''', (amount, buy_ownership_id))
  529. if seller_id != bank_id(): # seller receives
  530. cursor.execute('''
  531. UPDATE ownership
  532. SET amount = amount + ?
  533. WHERE user_id = ?
  534. AND ownable_id = ?
  535. ''', (price * amount, seller_id, currency_id()))
  536. # update order execution state
  537. cursor.execute('''
  538. UPDATE orders
  539. SET executed_amount = executed_amount + ?
  540. WHERE rowid = ?
  541. OR rowid = ?
  542. ''', (amount, buy_order_id, sell_order_id))
  543. if buy_order_finished:
  544. delete_order(buy_order_id)
  545. if sell_order_finished:
  546. delete_order(sell_order_id)
  547. if seller_id != buyer_id: # prevent showing self-transactions
  548. cursor.execute('''
  549. INSERT INTO transactions
  550. (price, ownable_id, amount)
  551. VALUES(?, ?, ?)
  552. ''', (price, ownable_id, amount,))
  553. # trigger stop-loss orders
  554. if buyer_id != seller_id:
  555. cursor.execute('''
  556. UPDATE orders
  557. SET stop_loss = NULL,
  558. "limit" = NULL
  559. WHERE stop_loss IS NOT NULL
  560. AND stop_loss
  561. AND ? IN (SELECT ownable_id FROM ownership WHERE rowid = ownership_id)
  562. AND ((buy AND "limit" < ?) OR (NOT buy AND "limit" > ?))
  563. ''', (ownable_id, price, price,))
  564. def ownable_id_by_ownership_id(ownership_id):
  565. connect()
  566. cursor.execute('''
  567. SELECT ownable_id
  568. FROM ownership
  569. WHERE rowid = ?
  570. ''', (ownership_id,))
  571. return cursor.fetchone()[0]
  572. def ownable_name_by_id(ownable_id):
  573. connect()
  574. cursor.execute('''
  575. SELECT name
  576. FROM ownables
  577. WHERE rowid = ?
  578. ''', (ownable_id,))
  579. return cursor.fetchone()[0]
  580. def bank_order(buy, ownable_id, limit, amount, time_until_expiration):
  581. if not limit:
  582. raise AssertionError('The bank does not give away anything.')
  583. place_order(buy,
  584. get_ownership_id(ownable_id, bank_id()),
  585. limit,
  586. False,
  587. amount,
  588. time_until_expiration)
  589. ownable_name = ownable_name_by_id(ownable_id)
  590. cursor.execute('''
  591. INSERT INTO news(title)
  592. VALUES (?)
  593. ''', ('External investors are selling ' + ownable_name + ' atm',))
  594. def current_time(): # might differ from datetime.datetime.now() for time zone reasons
  595. connect()
  596. cursor.execute('''
  597. SELECT datetime('now')
  598. ''')
  599. return cursor.fetchone()[0]
  600. def place_order(buy, ownership_id, limit, stop_loss, amount, time_until_expiration):
  601. connect()
  602. expiry = datetime.strptime(current_time(), '%Y-%m-%d %H:%M:%S') + timedelta(minutes=time_until_expiration)
  603. cursor.execute('''
  604. INSERT INTO orders
  605. (buy, ownership_id, "limit", stop_loss, ordered_amount, expiry_dt)
  606. VALUES (?, ?, ?, ?, ?, ?)
  607. ''', (buy, ownership_id, limit, stop_loss, amount, expiry))
  608. execute_orders(ownable_id_by_ownership_id(ownership_id))
  609. return True
  610. def transactions(ownable_id):
  611. connect()
  612. cursor.execute('''
  613. SELECT dt, amount, price
  614. FROM transactions
  615. WHERE ownable_id = ?
  616. ORDER BY dt DESC
  617. ''', (ownable_id,))
  618. return cursor.fetchall()
  619. def drop_expired_orders():
  620. connect()
  621. cursor.execute('''
  622. DELETE FROM orders
  623. WHERE expiry_dt < DATETIME('now')
  624. ''')
  625. return cursor.fetchall()
  626. def generate_keys(count=1):
  627. # source https://stackoverflow.com/questions/17049308/python-3-3-serial-key-generator-list-problems
  628. for i in range(count):
  629. key = '-'.join(random_chars(5) for _ in range(5))
  630. save_key(key)
  631. print(key)
  632. def user_has_order_with_id(session_id, order_id):
  633. connect()
  634. cursor.execute('''
  635. SELECT orders.rowid
  636. FROM orders, ownership, sessions
  637. WHERE orders.rowid = ?
  638. AND sessions.session_id = ?
  639. AND sessions.user_id = ownership.user_id
  640. AND ownership.rowid = orders.ownership_id
  641. ''', (order_id, session_id,))
  642. if cursor.fetchone():
  643. return True
  644. else:
  645. return False
  646. def leaderboard():
  647. connect()
  648. cursor.execute('''
  649. SELECT *
  650. FROM ( -- one score for each user
  651. SELECT
  652. username,
  653. SUM(CASE -- sum score for each of the users ownables
  654. WHEN ownership.ownable_id = ? THEN ownership.amount
  655. ELSE ownership.amount * (SELECT price
  656. FROM transactions
  657. WHERE ownable_id = ownership.ownable_id
  658. ORDER BY dt DESC
  659. LIMIT 1)
  660. END
  661. ) score
  662. FROM users, ownership
  663. WHERE ownership.user_id = users.rowid
  664. AND users.username != 'bank'
  665. GROUP BY users.rowid
  666. ) AS scores
  667. ORDER BY score DESC
  668. LIMIT 50
  669. ''', (currency_id(),))
  670. return cursor.fetchall()
  671. def user_wealth(user_id):
  672. connect()
  673. cursor.execute('''
  674. SELECT SUM(
  675. CASE -- sum score for each of the users ownables
  676. WHEN ownership.ownable_id = ? THEN ownership.amount
  677. ELSE ownership.amount * (SELECT price
  678. FROM transactions
  679. WHERE ownable_id = ownership.ownable_id
  680. ORDER BY dt DESC
  681. LIMIT 1)
  682. END
  683. ) score
  684. FROM ownership
  685. WHERE ownership.user_id = ?
  686. ''', (currency_id(), user_id,))
  687. return cursor.fetchone()[0]
  688. def change_password(session_id, password):
  689. connect()
  690. cursor.execute('''
  691. UPDATE users
  692. SET password = ?
  693. WHERE ? IN (SELECT session_id FROM sessions WHERE sessions.user_id = users.rowid)
  694. ''', (password, session_id,))
  695. def sign_out_user(session_id):
  696. connect()
  697. cursor.execute('''
  698. DELETE FROM sessions
  699. WHERE user_id = (SELECT user_id FROM sessions s2 WHERE s2.session_id = ?)
  700. ''', (session_id,))
  701. def delete_user(user_id):
  702. connect()
  703. cursor.execute('''
  704. DELETE FROM sessions
  705. WHERE user_id = ?
  706. ''', (user_id,))
  707. cursor.execute('''
  708. DELETE FROM orders
  709. WHERE ownership_id IN (
  710. SELECT rowid FROM ownership WHERE user_id = ?)
  711. ''', (user_id,))
  712. cursor.execute('''
  713. DELETE FROM ownership
  714. WHERE user_id = ?
  715. ''', (user_id,))
  716. cursor.execute('''
  717. DELETE FROM keys
  718. WHERE used_by_user_id = ?
  719. ''', (user_id,))
  720. cursor.execute('''
  721. INSERT INTO news(title)
  722. VALUES ((SELECT username FROM users WHERE rowid = ?) || ' retired.')
  723. ''', (user_id,))
  724. cursor.execute('''
  725. DELETE FROM users
  726. WHERE rowid = ?
  727. ''', (user_id,))
  728. def delete_ownable(ownable_id):
  729. connect()
  730. cursor.execute('''
  731. DELETE FROM transactions
  732. WHERE ownable_id = ?
  733. ''', (ownable_id,))
  734. cursor.execute('''
  735. DELETE FROM orders
  736. WHERE ownership_id IN (
  737. SELECT rowid FROM ownership WHERE ownable_id = ?)
  738. ''', (ownable_id,))
  739. # only delete empty ownerships
  740. cursor.execute('''
  741. DELETE FROM ownership
  742. WHERE ownable_id = ?
  743. AND amount = 0
  744. ''', (ownable_id,))
  745. cursor.execute('''
  746. INSERT INTO news(title)
  747. VALUES ((SELECT name FROM ownables WHERE rowid = ?) || ' can not be traded any more.')
  748. ''', (ownable_id,))
  749. cursor.execute('''
  750. DELETE FROM ownables
  751. WHERE rowid = ?
  752. ''', (ownable_id,))