Guest User

Untitled

a guest
Feb 10th, 2018
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.57 KB | None | 0 0
  1. ------------------presentation 01
  2. --------------------------------------------
  3. +-----------------------------------------------------------------------------------+
  4. | *** Exercises *** |
  5. +-----------------------------------------------------------------------------------+
  6. | Assuming this table: |
  7. | |
  8. | CREATE TABLE employee ( |
  9. | emp_id INTEGER PRIMARY KEY, |
  10. | emp_name VARCHAR(30) |
  11. | } |
  12. | |
  13. | And using the "engine.execute()" method to invoke a statement: |
  14. | |
  15. | 1. Execute an INSERT statement that will insert the row with emp_name='dilbert'. |
  16. | The primary key column can be omitted so that it is generated automatically. |
  17. | |
  18. | 2. SELECT all rows from the employee table. |
  19. +---------------------------------------------------------------------- (13 / 13) --+
  20.  
  21.  
  22. ---------------------1
  23. >>> engine.execute("insert into employee(emp_name) values(:emp_name)",emp_name='dilbert')[SQL]: insert into employee(emp_name) values(:emp_name)
  24. [SQL]: {'emp_name': 'dilbert'}
  25. [SQL]: COMMIT
  26. ---------------------2
  27. >>> print(engine.execute("select * from employee").fetchall())
  28. [SQL]: select * from employee
  29. [SQL]: ()
  30. [(1, u'ed'), (2, u'jack'), (3, u'fred'), (4, u'wendy'), (5, u'mary'), (6, u'dilbert')]
  31.  
  32.  
  33. -------------------presentation 02
  34. --------------------------------------------
  35. +------------------------------------------------------------------+
  36. | *** Exercises *** |
  37. +------------------------------------------------------------------+
  38. | 1. Write a Table construct corresponding to this CREATE TABLE |
  39. | statement. |
  40. | |
  41. | CREATE TABLE network ( |
  42. | network_id INTEGER PRIMARY KEY, |
  43. | name VARCHAR(100) NOT NULL, |
  44. | created_at DATETIME NOT NULL, |
  45. | owner_id INTEGER, |
  46. | FOREIGN KEY owner_id REFERENCES user(id) |
  47. | ) |
  48. | |
  49. | 2. Then emit metadata.create_all(), which will |
  50. | emit CREATE TABLE for this table (it will skip |
  51. | those that already exist). |
  52. | |
  53. | The necessary types are imported here: |
  54. +----------------------------------------------------- (13 / 20) --+
  55.  
  56. >>> from sqlalchemy import Integer, String, DateTime
  57.  
  58. >>> network_table = Table('network', metadata, Column('network_id', Integer, primary_key=True), Column('name', String(100), nullable=False), Column('created_at', DateTime, nullable=False), Column('owner_id', Integer, ForeignKey('user.id')))
  59. >>> metadata.create_all(engine)
  60. [SQL]: PRAGMA table_info("user")
  61. [SQL]: ()
  62. [SQL]: PRAGMA table_info("fancy")
  63. [SQL]: ()
  64. [SQL]: PRAGMA table_info("story")
  65. [SQL]: ()
  66. [SQL]: PRAGMA table_info("address")
  67. [SQL]: ()
  68. [SQL]: PRAGMA table_info("published")
  69. [SQL]: ()
  70. [SQL]: PRAGMA table_info("network")
  71. [SQL]: ()
  72. [SQL]:
  73. CREATE TABLE network (
  74. network_id INTEGER NOT NULL,
  75. name VARCHAR(100) NOT NULL,
  76. created_at DATETIME NOT NULL,
  77. owner_id INTEGER,
  78. PRIMARY KEY (network_id),
  79. FOREIGN KEY(owner_id) REFERENCES user (id)
  80. )
  81.  
  82.  
  83. [SQL]: ()
  84. [SQL]: COMMIT
  85.  
  86.  
  87.  
  88.  
  89. +---------------------------------------------------------------------+
  90. | *** Exercises *** |
  91. +---------------------------------------------------------------------+
  92. | |
  93. | 1. Using 'metadata2', reflect the "network" table in the same way |
  94. | we just did 'user', then display the columns (or bonus, display |
  95. | just the column names) |
  96. | |
  97. | 2. Using "inspector", print a list of all table names that |
  98. | include a column called "story_id" |
  99. +-------------------------------------------------------- (20 / 20) --+
  100.  
  101. --------------------1
  102. >>> network_reflected=Table('network', metadata2, autoload=True, autoload_with=engine)
  103. [SQL]: PRAGMA table_info("network")
  104. [SQL]: ()
  105. [SQL]: PRAGMA foreign_key_list("network")
  106. [SQL]: ()
  107. [SQL]: PRAGMA index_list("network")
  108. [SQL]: ()
  109. >>> print(network_reflected.c)
  110. ['network.network_id', 'network.name', 'network.created_at', 'network.owner_id']
  111. >>> print(inspector.get_columns('network'))
  112. [SQL]: PRAGMA table_info("network")
  113. [SQL]: ()
  114. [{'primary_key': 1, 'nullable': False, 'default': None, 'autoincrement': True, 'type': INTEGER(), 'name': u'network_id'}, {'primary_key': 0, 'nullable': False, 'default': None, 'autoincrement': True, 'type': VARCHAR(length=100), 'name': u'name'}, {'primary_key': 0, 'nullable': False, 'default': None, 'autoincrement': True, 'type': DATETIME(), 'name': u'created_at'}, {'primary_key': 0, 'nullable': True, 'default': None, 'autoincrement': True, 'type': INTEGER(), 'name': u'owner_id'}]
  115.  
  116. ---------------------------2
  117. >>> columns_n=[name for name in inspector.get_table_names() for col in inspector.get_columns(name) if 'story_id'== col['name']]
  118. >>> print(columns_n)
  119. [u'published', u'story']
  120.  
  121.  
  122.  
  123.  
  124.  
  125. ----------------------presentation 3
  126. ----------------------------------------
  127. +------------------------------------------------------------------------+
  128. | *** Exercises *** |
  129. +------------------------------------------------------------------------+
  130. | Produce these expressions using "user_table.c.fullname", |
  131. | "user_table.c.id", and "user_table.c.username": |
  132. | |
  133. | 1. user.fullname = 'ed' |
  134. | |
  135. | 2. user.fullname = 'ed' AND user.id > 5 |
  136. | |
  137. | 3. user.username = 'edward' OR (user.fullname = 'ed' AND user.id > 5) |
  138. +----------------------------------------------------------- (18 / 46) --+
  139.  
  140.  
  141. >>> engine.execute(user_table.select().where(user_table.c.fullname == "ed"))
  142. [SQL]: SELECT user.id, user.username, user.fullname
  143. FROM user
  144. WHERE user.fullname = ?
  145. [SQL]: ('ed',)
  146. <sqlalchemy.engine.result.ResultProxy object at 0x7f6f2dc964d0>
  147. >>> engine.execute(user_table.select().where(and_(user_table.c.fullname == "ed", user_table.c.id > 5)))
  148. [SQL]: SELECT user.id, user.username, user.fullname
  149. FROM user
  150. WHERE user.fullname = ? AND user.id > ?
  151. [SQL]: ('ed', 5)
  152. <sqlalchemy.engine.result.ResultProxy object at 0x7f6f2dc96990>
  153. >>> engine.execute(user_table.select().where(or_(user_table.c.username == "edward",and_(user_table.c.fullname=='ed',user_table.c.id > 5))))
  154. [SQL]: SELECT user.id, user.username, user.fullname
  155. FROM user
  156. WHERE user.username = ? OR user.fullname = ? AND user.id > ?
  157. [SQL]: ('edward', 'ed', 5)
  158. <sqlalchemy.engine.result.ResultProxy object at 0x7f6f2dc96cd0>
  159.  
  160.  
  161.  
  162. +----------------------------------------------------------------------------+
  163. | *** Exercises *** |
  164. +----------------------------------------------------------------------------+
  165. | 1. use user_table.insert() and "r = conn.execute()" to emit this |
  166. | statement: |
  167. | |
  168. | INSERT INTO user (username, fullname) VALUES ('dilbert', 'Dilbert Jones') |
  169. | |
  170. | 2. What is the value of 'user.id' for the above INSERT statement? |
  171. | |
  172. | 3. Using "select([user_table])", execute this SELECT: |
  173. | |
  174. | SELECT id, username, fullname FROM user WHERE username = 'wendy' OR |
  175. | username = 'dilbert' ORDER BY fullname |
  176. +--------------------------------------------------------------- (27 / 46) --+
  177.  
  178.  
  179. >>> result = conn.execute(user_table.insert().values(username='dilbert', fullname='Dilbert Jones'))
  180. [SQL]: INSERT INTO user (username, fullname) VALUES (?, ?)
  181. [SQL]: ('dilbert', 'Dilbert Jones')
  182. [SQL]: COMMIT
  183. >>> result.inserted_primary_key
  184. [4]
  185. >>>> result = conn.execute(select([user_table]).where(or_(user_table.c.username == 'wendy', user_table.c.username == 'dilbert')).order_by(user_table.c.fullname))
  186. [SQL]: SELECT user.id, user.username, user.fullname
  187. FROM user
  188. WHERE user.username = ? OR user.username = ? ORDER BY user.fullname
  189. [SQL]: ('wendy', 'dilbert')
  190. >>> print([r for r in result])
  191. (4, 'dilbert', 'Dilbert Jones')
  192. (3, 'wendy', 'Wendy Weathersmith')
  193.  
  194.  
  195. +------------------------------------------------------------------+
  196. | *** Exercises *** |
  197. +------------------------------------------------------------------+
  198. | Produce this SELECT: |
  199. | |
  200. | SELECT fullname, email_address FROM user JOIN address |
  201. | ON user.id = address.user_id WHERE username='ed' |
  202. | ORDER BY email_address |
  203. +----------------------------------------------------- (38 / 46) --+
  204.  
  205.  
  206. >>> result = conn.execute(select([user_table.c.fullname, address_table.c.email_address]).select_from(user_table.join(address_table, user_table.c.id == address_table.c.user_id)). where(user_table.c.username == 'ed').order_by(address_table.c.email_address))
  207. [SQL]: SELECT user.fullname, address.email_address
  208. FROM user JOIN address ON user.id = address.user_id
  209. WHERE user.username = ? ORDER BY address.email_address
  210. [SQL]: ('ed',)
  211. >>> for row in result:
  212. ... print(row)
  213. ...
  214. ('Ed Jones', 'ed@ed.com')
  215. ('Ed Jones', 'ed@gmail.com')
  216.  
  217.  
  218.  
  219.  
  220. +---------------------------------------------------------------------+
  221. | *** Exercises *** |
  222. +---------------------------------------------------------------------+
  223. | 1. Execute this UPDATE - keep the "result" that's returned |
  224. | |
  225. | UPDATE user SET fullname='Ed Jones' where username='ed' |
  226. | |
  227. | 2. how many rows did the above statement update? |
  228. | |
  229. | 3. Tricky bonus! Combine update() along with select().as_scalar() |
  230. | to execute this UPDATE: |
  231. | |
  232. | UPDATE user SET fullname=fullname || |
  233. | (select email_address FROM address WHERE user_id=user.id) |
  234. | WHERE username IN ('jack', 'wendy') |
  235. +-------------------------------------------------------- (46 / 46) --+
  236.  
  237.  
  238. >>> result = conn.execute(user_table.update().values(fullname='Ed Jones').where(user_table.c.username=='ed'))
  239. [SQL]: UPDATE user SET fullname=? WHERE user.username = ?
  240. [SQL]: ('Ed Jones', 'ed')
  241. [SQL]: COMMIT
  242. >>> result.rowcount
  243. 1
  244. >>> result = conn.execute(user_table.update().values(fullname=user_table.c.fullname + select([address_table.c.email_address]).where(address_table.c.user_id == user_table.c.id)).where(or_(user_table.c.username == 'jack', user_table.c.username == 'wendy')))
  245. [SQL]: UPDATE user SET fullname=(user.fullname || (SELECT address.email_address
  246. FROM address
  247. WHERE address.user_id = user.id)) WHERE user.username = ? OR user.username = ?
  248. [SQL]: ('jack', 'wendy')
  249. [SQL]: COMMIT
  250.  
  251.  
  252.  
  253.  
  254. ---------------------------------presentation 4
  255. ---------------------------------------------------
  256. +-------------------------------------------------------------------+
  257. | *** Exercises - Basic Mapping *** |
  258. +-------------------------------------------------------------------+
  259. | |
  260. | 1. Create a class/mapping for this table, call the class Network |
  261. | |
  262. | CREATE TABLE network ( |
  263. | network_id INTEGER PRIMARY KEY, |
  264. | name VARCHAR(100) NOT NULL, |
  265. | ) |
  266. | |
  267. | 2. emit Base.metadata.create_all(engine) to create the table |
  268. | |
  269. | 3. commit a few Network objects to the database: |
  270. | |
  271. | Network(name='net1'), Network(name='net2') |
  272. +------------------------------------------------------ (25 / 72) --+
  273.  
  274.  
  275. >>> class Network(Base):
  276. ... __tablename__ = 'network'
  277. ... network_id = Column(Integer, primary_key = True)
  278. ... name = Column(String(100), nullable = False)
  279. ... def __repr__(self):
  280. ... return "Network(%r, %r)" % (self.network_id, self.name)
  281. ...
  282. >>> Base.metadata.create_all(engine)
  283. [SQL]: PRAGMA table_info("network")
  284. [SQL]: ()
  285. [SQL]: PRAGMA table_info("user")
  286. [SQL]: ()
  287. [SQL]:
  288. CREATE TABLE network (
  289. network_id INTEGER NOT NULL,
  290. name VARCHAR(100) NOT NULL,
  291. PRIMARY KEY (network_id)
  292. )
  293.  
  294.  
  295. [SQL]: ()
  296. [SQL]: COMMIT
  297. >>> session.add_all([Network(name = 'net1'), Network(name = 'net2')])
  298. >>> session.commit()
  299. [SQL]: INSERT INTO network (name) VALUES (?)
  300. [SQL]: ('net1',)
  301. [SQL]: INSERT INTO network (name) VALUES (?)
  302. [SQL]: ('net2',)
  303. [SQL]: COMMIT
  304.  
  305.  
  306. +---------------------------------------------------------------------------+
  307. | *** Exercises - ORM Querying *** |
  308. +---------------------------------------------------------------------------+
  309. | 1. Produce a Query object representing the list of "fullname" values for |
  310. | all User objects in alphabetical order. |
  311. | |
  312. | 2. call .all() on the query to make sure it works! |
  313. | |
  314. | 3. build a second Query object from the first that also selects |
  315. | only User rows with the name "mary" or "ed". |
  316. | |
  317. | 4. return only the second row of the Query from #3. |
  318. +-------------------------------------------------------------- (43 / 72) --+
  319.  
  320.  
  321. >>> query = session.query(User.fullname).order_by(User.fullname)
  322. >>> query.all()
  323. [SQL]: SELECT user.fullname AS user_fullname
  324. FROM user ORDER BY user.fullname
  325. [SQL]: ()
  326. [('Ed Jones',), ('Fred Flinstone',), ('Mary Contrary',), ('Wendy Weathersmith',)]
  327. >>> query = session.query(User.fullname).filter(or_(User.name == 'mary', User.name == 'ed')).order_by(User.fullname)
  328. >>> print(query[1])
  329. [SQL]: SELECT user.fullname AS user_fullname
  330. FROM user
  331. WHERE user.name = ? OR user.name = ? ORDER BY user.fullname
  332. LIMIT ? OFFSET ?
  333. [SQL]: ('mary', 'ed', 1, 1)
  334. ('Mary Contrary',)
  335.  
  336.  
  337. +------------------------------------------------------------------+
  338. | *** Exercises *** |
  339. +------------------------------------------------------------------+
  340. | 1. Run this SQL JOIN: |
  341. | |
  342. | SELECT user.name, address.email_address FROM user |
  343. | JOIN address ON user.id=address.user_id WHERE |
  344. | address.email_address='j25@yahoo.com' |
  345. | |
  346. | 2. Tricky Bonus! Select all pairs of distinct user names. |
  347. | Hint: "... ON user_alias1.name < user_alias2.name" |
  348. +----------------------------------------------------- (62 / 72) --+
  349.  
  350.  
  351. >>> query = session.query(User.name, Address.email_address).join(Address, User.id == Address.user_id).filter(Address.email_address == 'j25@yahoo.com')
  352. >>> query.all()
  353. [SQL]: SELECT user.name AS user_name, address.email_address AS address_email_address
  354. FROM user JOIN address ON user.id = address.user_id
  355. WHERE address.email_address = ?
  356. [SQL]: ('j25@yahoo.com',)
  357. [('fred', 'j25@yahoo.com')]
  358. >>> p1, p2 = aliased(User), aliased(User)
  359. >>> query = session.query(p1.name, p2.name).join(p2, p1.name < p2.name)
  360. >>> for q in query:
  361. ... print(q)
  362. ...
  363. [SQL]: SELECT user_1.name AS user_1_name, user_2.name AS user_2_name
  364. FROM user AS user_1 JOIN user AS user_2 ON user_1.name < user_2.name
  365. [SQL]: ()
  366. ('ed', 'wendy')
  367. ('ed', 'mary')
  368. ('ed', 'fred')
  369. ('ed', 'jack')
  370. ('mary', 'wendy')
  371. ('fred', 'wendy')
  372. ('fred', 'mary')
  373. ('fred', 'jack')
  374. ('jack', 'wendy')
  375. ('jack', 'mary')
  376.  
  377.  
  378.  
  379. +----------------------------------------------------------------------------+
  380. | *** Exercises - Final Exam ! *** |
  381. +----------------------------------------------------------------------------+
  382. | 1. Create a class called 'Account', with table "account": |
  383. | |
  384. | id = Column(Integer, primary_key=True) |
  385. | owner = Column(String(50), nullable=False) |
  386. | balance = Column(Numeric, default=0) |
  387. | |
  388. | 2. Create a class "Transaction", with table "transaction": |
  389. | * Integer primary key |
  390. | * numeric "amount" column |
  391. | * Integer "account_id" column with ForeignKey('account.id') |
  392. | |
  393. | 3. Add a relationship() on Transaction named "account", which refers |
  394. | to "Account", and has a backref called "transactions". |
  395. | |
  396. | 4. Create a database, create tables, then insert these objects: |
  397. | |
  398. | a1 = Account(owner='Jack Jones', balance=5000) |
  399. | a2 = Account(owner='Ed Rendell', balance=10000) |
  400. | Transaction(amount=500, account=a1) |
  401. | Transaction(amount=4500, account=a1) |
  402. | Transaction(amount=6000, account=a2) |
  403. | Transaction(amount=4000, account=a2) |
  404. | |
  405. | 5. Produce a report that shows: |
  406. | * account owner |
  407. | * account balance |
  408. | * summation of transaction amounts per account (should match balance) |
  409. | A column can be summed using func.sum(Transaction.amount) |
  410. +--------------------------------------------------------------- (72 / 72) --+
  411.  
  412. >>> from sqlalchemy import Integer, String, Numeric
  413. >>> class Account(Base):
  414. ... __tablename__ = 'account'
  415. ... id = Column(Integer, primary_key=True)
  416. ... owner = Column(String(50), nullable=False)
  417. ... balance = Column(Numeric, default=0)
  418. ... def __repr__(self):
  419. ... return "Account(%r, %r)" % (self.owner, self.balance)
  420. >>> class Transaction(Base):
  421. ... __tablename__ = 'transaction'
  422. ... id = Column(Integer, primary_key=True)
  423. ... amount = Column(Numeric)
  424. ... account_id = Column(Integer, ForeignKey('account.id'))
  425. ... account = relationship('Account', backref='transatcions')
  426. ... def __repr__(self):
  427. ... return 'Transaction(%r, %r)' % (self.account_id, self.amount)
  428. >>> Base.metadata.create_all(engine)
  429. [SQL]: PRAGMA table_info("account")
  430. [SQL]: ()
  431. [SQL]: PRAGMA table_info("network")
  432. [SQL]: ()
  433. [SQL]: PRAGMA table_info("user")
  434. [SQL]: ()
  435. [SQL]: PRAGMA table_info("transaction")
  436. [SQL]: ()
  437. [SQL]: PRAGMA table_info("address")
  438. [SQL]: ()
  439. [SQL]:
  440. CREATE TABLE account (
  441. id INTEGER NOT NULL,
  442. owner VARCHAR(50) NOT NULL,
  443. balance NUMERIC,
  444. PRIMARY KEY (id)
  445. )
  446. [SQL]: ()
  447. [SQL]: COMMIT
  448. [SQL]:
  449. CREATE TABLE "transaction" (
  450. id INTEGER NOT NULL,
  451. amount NUMERIC,
  452. account_id INTEGER,
  453. PRIMARY KEY (id),
  454. FOREIGN KEY(account_id) REFERENCES account (id)
  455. )
  456. [SQL]: ()
  457. [SQL]: COMMIT
  458. >>> a1 = Account(owner='Jack Jones', balance=5000)
  459. >>> a2 = Account(owner='Ed Rendell', balance=10000)
  460. >>> session.add_all([a1, a2, Transaction(amount=500, account=a1), Transaction(amount=4500, account=a1), Transaction(amount=6000, account=a2), Transaction(amount=4000, account=a2),])
  461. >>> session.commit()
  462. [SQL]: BEGIN (implicit)
  463. [SQL]: INSERT INTO account (owner, balance) VALUES (?, ?)
  464. [SQL]: ('Jack Jones', 5000.0)
  465. [SQL]: INSERT INTO account (owner, balance) VALUES (?, ?)
  466. [SQL]: ('Ed Rendell', 10000.0)
  467. [SQL]: INSERT INTO "transaction" (amount, account_id) VALUES (?, ?)
  468. [SQL]: (500.0, 1)
  469. [SQL]: INSERT INTO "transaction" (amount, account_id) VALUES (?, ?)
  470. [SQL]: (4500.0, 1)
  471. [SQL]: INSERT INTO "transaction" (amount, account_id) VALUES (?, ?)
  472. [SQL]: (6000.0, 2)
  473. [SQL]: INSERT INTO "transaction" (amount, account_id) VALUES (?, ?)
  474. [SQL]: (4000.0, 2)
  475. [SQL]: COMMIT
  476. >>> query = session.query(Account.owner, Account.balance, func.sum(Transaction.amount)).join(Transaction).group_by(Transaction.account_id)
  477. >>>print([q for q in query])
  478. [SQL]: BEGIN (implicit)
  479. [SQL]: SELECT account.owner AS account_owner, account.balance AS account_balance, sum("transaction".amount) AS sum_1
  480. FROM account JOIN "transaction" ON account.id = "transaction".account_id GROUP BY "transaction".account_id
  481. [SQL]: ()
  482. /home/ubuntu/pycon2013_student_package/venv/local/lib/python2.7/site-packages/sqlalchemy/types.py:307: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.
  483. d[coltype] = rp = d['impl'].result_processor(dialect, coltype)
  484. ('Jack Jones', Decimal('5000.0000000000'), Decimal('5000.0000000000'))
  485. ('Ed Rendell', Decimal('10000.0000000000'), Decimal('10000.0000000000'))
Add Comment
Please, Sign In to add comment