Advertisement
Guest User

Untitled

a guest
Mar 1st, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.11 KB | None | 0 0
  1. # -*- coding: utf8 -*-
  2. # Этот модуль нужен для синхронизации ДВУХ БД с заявками!
  3. # PostgreSQL <==> FireBird
  4. # Не забыть поставить psycopg2 (stand alone installer, через PIP не ставится)
  5.  
  6. import os
  7. import gvar
  8. import psycopg2
  9. import sys
  10. import fdb
  11.  
  12. # Курсоры определяем до начала всей работы
  13.  
  14. postconn = psycopg2.connect( 'host={0} dbname={1} user={2} password={3}'.format(gvar.postdbhost, gvar.postdbname, gvar.postuser, gvar.postpass))
  15. postcursor = postconn.cursor() # Курсор для Firebird
  16.  
  17.  
  18. fireconn = fdb.connect(gvar.dbname, gvar.dbuser, gvar.dbpass)
  19. firecursor = fireconn.cursor()
  20.  
  21.  
  22. # Работаем с CUSTOMER Firebird --> PostgreSQL
  23. # Берем из FireBird и отправляем в PostgreSQL
  24. def SyncCustomer():
  25. print "SyncCustomer"
  26. try:
  27. count_customer = 0
  28. firecursor.execute('SELECT customer_id, customer_name, customer_data, customer_priority, customer_status FROM CUSTOMER WHERE fl_ready=0')
  29. fireselect_result = firecursor.fetchall()
  30.  
  31. if not fireselect_result:
  32. print "[SYSTEM] \t Table CUSTOMER do not contain any flags=0"
  33.  
  34. else:
  35. print "Trying to past in PostgreSQL:"
  36. # Получаем нужные столбцы из PostgreSQL
  37. for customer_id, customer_name, customer_data, customer_priority, customer_status in fireselect_result:
  38.  
  39. SQLInsertPostgreSQL = (("INSERT INTO CUSTOMER (CUSTOMER_NAME, CUSTOMER_DATA, CUSTOMER_PRIORITY, CUSTOMER_STATUS, FL_READY, FIREID) \
  40. VALUES ('{0}', '{1}', {2}, {3},{4},{5})")).format(customer_name, customer_data, customer_priority, customer_status, 1, customer_id) #fl_ready dscnfdkztv d 1
  41. # print "===================="
  42. print SQLInsertPostgreSQL
  43. # print "^^^^^^^^^^^ POST COMMIT ^^^^^^^^"
  44. postcursor.execute(SQLInsertPostgreSQL)
  45. print "===================="
  46. postconn.commit()
  47.  
  48. # Нужно обновить флаг готовности в FireBird (откуда брали)
  49. firecursor.execute("UPDATE CUSTOMER SET FL_READY = 1 WHERE customer_id=%s" % (customer_id))
  50. fireconn.commit()
  51.  
  52. # Берем (тоже что и ниже) работаем, но уже с FIREID
  53. postcursor.execute("SELECT CUSTOMER_ID FROM CUSTOMER WHERE fireid=%s" %(customer_id))
  54. print customer_id
  55. postselect_result = postcursor.fetchone()
  56. # И обновляем FIREID в FireBird
  57. firecursor.execute("UPDATE CUSTOMER SET POSTID = %s WHERE customer_id=%s" % (str(postselect_result[0]), customer_id))
  58. fireconn.commit()
  59. count_customer +=1
  60. return count_customer
  61.  
  62. except SystemError:
  63. print "Error in module SyncCustomer"
  64.  
  65.  
  66.  
  67. # Обратная операция. Берем из PostgreSQL и отправляем в FireBird
  68. # Эта операция пока не требуется. Достаточно одно сторонней синхронизации Firebird --> PostgreSQL
  69. # Код ниже рабочий и, если надо, может быть раскомментирован
  70. postcursor.execute('SELECT customer_id, customer_name, customer_data, customer_priority, customer_status FROM CUSTOMER WHERE fl_ready=0')
  71. postselect_result = postcursor.fetchall()
  72.  
  73. for customer_id, customer_name, customer_data, customer_priority, customer_status in postselect_result:
  74. SQLInsertFirebirdSQL = (("INSERT INTO CUSTOMER (CUSTOMER_NAME, CUSTOMER_DATA, CUSTOMER_PRIORITY, CUSTOMER_STATUS, FL_READY, POSTID) \
  75. VALUES ('{0}', '{1}', {2}, {3},{4},{5})")).format(customer_name, customer_data, customer_priority, customer_status, 1, customer_id) # В FB пишем ID от PostgreSQL
  76. firecursor.execute(SQLInsertFirebirdSQL)
  77. fireconn.commit()
  78.  
  79. postcursor.execute("UPDATE CUSTOMER SET FL_READY = 1 WHERE customer_id=%s" % (customer_id))
  80. postconn.commit()
  81.  
  82. # Берем из FireBird по ID-шнику от Postgres, который выше CUSTOMER_ID
  83. firecursor.execute("SELECT CUSTOMER_ID FROM CUSTOMER WHERE POSTID=%s" %(customer_id))
  84. print customer_id
  85. fireselect_result = firecursor.fetchone()
  86. # И обновляем FIREID в PostgreSQL
  87. postcursor.execute("UPDATE CUSTOMER SET FIREID = %s WHERE customer_id=%s" % (str(fireselect_result[0]), customer_id))
  88. postconn.commit()
  89. count_customer +=1
  90. return count_customer
  91. ####################################################################
  92. ####################################################################
  93. def SyncProdType():
  94. # Работаем с ProdType Firebird --> PostgreSQL
  95. firecursor.execute('SELECT prod_type_id, product_kind FROM prod_type WHERE fl_ready=0')
  96. fireselect_result = firecursor.fetchall()
  97.  
  98. if not fireselect_result:
  99. print "[SYSTEM] \t Table PRODUCT_KIND do not contain any flags=0"
  100.  
  101. count_prod=0
  102. for prod_type_id, product_kind in fireselect_result:
  103.  
  104. print "Try to past in PostgreSQL:"
  105.  
  106. SQLInsertPostgreSQL = (("INSERT INTO prod_type (prod_type_id, product_kind, FL_READY) VALUES ({0},'{1}',{2})")).format(prod_type_id, product_kind, 1) #FL_READY для синхронизированных
  107. print "===================="
  108. print SQLInsertPostgreSQL
  109. print "===================="
  110. count_prod +=1
  111. postcursor.execute(SQLInsertPostgreSQL)
  112.  
  113. postconn.commit()
  114. fireconn.commit()
  115.  
  116. # POSTGRES ^^^^^^^^^
  117. firecursor.execute("""UPDATE prod_type SET FL_READY = 1 WHERE prod_type_id=%s""" % (prod_type_id))
  118. postconn.commit()
  119. fireconn.commit()
  120.  
  121.  
  122. print "======================================================"
  123. # Работаем с REQUEST. Вставляем PostgreSQL <--> FireBird
  124. # 1-2 и 2-й - подключения к базам, 1-й откуда-донор, 2-й - куда качаем
  125. # 3-й и 4-й параметры - имена полей доп.ид-шников postid и fireid
  126. def SyncRequest(connSrc, connDst, NamefieldIDSrc, NamefieldIDDst, ):
  127. print "SyncRequest"
  128. try:
  129. count_request = 0
  130. currSrc = connSrc.cursor()
  131. currDst = connDst.cursor()
  132.  
  133. currSrc.execute("""SELECT request_id, time_beg, time_end, freq, prod_type_id, priority, customer_id, sol_angle_min, sol_angle_max, shape FROM "REQUESTS" WHERE fl_ready=0""")
  134. for request_id, time_beg, time_end, freq, prod_type_id, priority, customer_id, sol_angle_min, sol_angle_max, shape in currSrc.fetchall():
  135. # Проверяем наличие customer_id в принимающей базе
  136. # c = customer, p=prod_type.
  137.  
  138. currDst.execute(("""SELECT customer_id FROM "CUSTOMER" WHERE customer_id=%s""") %customer_id)
  139. c = currDst.fetchone()
  140. print "--------------!"
  141. print "customer_id: ", c
  142. print "========--------------======="
  143. connDst.commit()
  144.  
  145. print((("""SELECT prod_type_id FROM "PROD_TYPE" WHERE prod_type_id=%s""") %prod_type_id))
  146. currDst.execute(("""SELECT prod_type_id FROM "PROD_TYPE" WHERE prod_type_id=%s""") %prod_type_id)
  147. pt = currDst.fetchone()
  148. print "pt: ", pt # упорно возвращает pt: None хотя заспрос
  149. print "prod_type_id: ", prod_type_id
  150.  
  151. connDst.commit()
  152.  
  153. # c = customer, p=prod_type.
  154. if c and pt:
  155. print("""INSERT INTO "REQUESTS" (time_beg, time_end, freq, prod_type_id, priority, customer_id, sol_angle_min, sol_angle_max, shape, FL_READY, {0} )
  156. VALUES ('{1}', '{2}', {3}, {4}, {5}, {6}, {7}, {8}, '{9}', {10}, {11})""".format(NamefieldIDSrc, time_beg, time_end, freq, prod_type_id, priority, customer_id, sol_angle_min, sol_angle_max, shape, 1, request_id))
  157.  
  158.  
  159. currDst.execute("""INSERT INTO "REQUESTS" (time_beg, time_end, freq, prod_type_id, priority, customer_id, sol_angle_min, sol_angle_max, shape, FL_READY, {0} )
  160. VALUES ('{1}', '{2}', {3}, {4}, {5}, {6}, {7}, {8}, '{9}', {10}, {11})""".format(NamefieldIDSrc, time_beg, time_end, freq, prod_type_id, priority, customer_id, sol_angle_min, sol_angle_max, shape, 1, request_id))
  161. connDst.commit()
  162.  
  163. # Вот тут берем ID источника и в приемник его отправляем. В начале делаем его SELECT, а ниже обновляем
  164. currDst.execute("""SELECT "REQUEST_ID" FROM "REQUESTS" WHERE %s=%s""" % (request_id, NamefieldIDSrc))
  165. rid = currDst.fetchone()[0]
  166. if rid:
  167. currSrc.execute("""UPDATE "REQUESTS" SET %s=%d WHERE REQUEST_ID=%d;""" % (NamefieldIDDst, rid, request_id))
  168. connSrc.commit()
  169. connDst.commit()
  170. # Теперь еще и флаг обновляем
  171. currSrc.execute("""UPDATE "REQUESTS" SET FL_READY=1 WHERE REQUEST_ID=%s;""" % (request_id))
  172. connSrc.commit()
  173. count_request += 1
  174.  
  175. connSrc.commit()
  176. connDst.commit()
  177. return count_request
  178.  
  179. except SystemError:
  180. print "Error in module SyncRequest"
  181.  
  182. # Синхронизируем FireBird (Instrument) --> в PostgreSQL (Instrument)
  183. def SyncInstrument():
  184. print "SyncInstrument"
  185. firecursor.execute('SELECT instrument_id, instrument_name, instrument_data, proc_order FROM INSTRUMENT WHERE fl_ready=0')
  186. fireselect_result = firecursor.fetchall()
  187. for i in fireselect_result:
  188. print i
  189.  
  190. if not fireselect_result:
  191. print "[SYSTEM] \t Table INSTRUMENT do not contain any flags=0"
  192.  
  193. for instrument_id, instrument_name, instrument_data, proc_order in fireselect_result:
  194.  
  195. print "Try to past in PostgreSQL:"
  196. # instrument_id, instrument_name, instrument_data, proc_order, fl_ready
  197. SQLInsertPostgreSQL = (("""INSERT INTO "INSTRUMENT" ("instrument_id", "instrument_name", "instrument_data", "proc_order", "fl_ready") VALUES ({0},'{1}','{2}','{3}',{4})""")).format(instrument_id, instrument_name, instrument_data, proc_order, 1) #FL_READY для синхронизированных
  198. print "===================="
  199. print SQLInsertPostgreSQL
  200. print "===================="
  201. # count_prod +=1
  202. postcursor.execute(SQLInsertPostgreSQL)
  203.  
  204. postconn.commit()
  205. fireconn.commit()
  206.  
  207. # POSTGRES ^^^^^^^^^
  208. foo = firecursor.execute("UPDATE INSTRUMENT SET FL_READY = 1 WHERE instrument_id=%s" % (instrument_id))
  209. print "Sync Done"
  210. postconn.commit()
  211. fireconn.commit()
  212.  
  213.  
  214. def main():
  215.  
  216. print "Connected!\n"
  217.  
  218. print('[Requests] PostgreSQL --> FireBird upload records: %d' % SyncRequest(postconn, fireconn, 'POSTID', 'FIREID'))
  219. #print('[Requests] FireBird --> PostgreSQL upload records: %d' % SyncRequest(fireconn, postconn, 'FIREID', 'POSTID'))
  220. # print('[Customers] FireBird --> PostgreSQL upload records:%d' % SyncCustomer())
  221. #SyncInstrument()
  222.  
  223.  
  224. if __name__ == "__main__":
  225. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement