database_test.test 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242
  1. <?php
  2. /**
  3. * Dummy class for fetching into a class.
  4. *
  5. * PDO supports using a new instance of an arbitrary class for records
  6. * rather than just a stdClass or array. This class is for testing that
  7. * functionality. (See testQueryFetchClass() below)
  8. */
  9. class FakeRecord { }
  10. /**
  11. * Base test class for databases.
  12. *
  13. * Because all database tests share the same test data, we can centralize that
  14. * here.
  15. */
  16. class DatabaseTestCase extends DrupalWebTestCase {
  17. protected $profile = 'testing';
  18. function setUp() {
  19. parent::setUp('database_test');
  20. $schema['test'] = drupal_get_schema('test');
  21. $schema['test_people'] = drupal_get_schema('test_people');
  22. $schema['test_people_copy'] = drupal_get_schema('test_people_copy');
  23. $schema['test_one_blob'] = drupal_get_schema('test_one_blob');
  24. $schema['test_two_blobs'] = drupal_get_schema('test_two_blobs');
  25. $schema['test_task'] = drupal_get_schema('test_task');
  26. $this->installTables($schema);
  27. $this->addSampleData();
  28. }
  29. /**
  30. * Set up several tables needed by a certain test.
  31. *
  32. * @param $schema
  33. * An array of table definitions to install.
  34. */
  35. function installTables($schema) {
  36. // This ends up being a test for table drop and create, too, which is nice.
  37. foreach ($schema as $name => $data) {
  38. if (db_table_exists($name)) {
  39. db_drop_table($name);
  40. }
  41. db_create_table($name, $data);
  42. }
  43. foreach ($schema as $name => $data) {
  44. $this->assertTrue(db_table_exists($name), format_string('Table @name created successfully.', array('@name' => $name)));
  45. }
  46. }
  47. /**
  48. * Set up tables for NULL handling.
  49. */
  50. function ensureSampleDataNull() {
  51. $schema['test_null'] = drupal_get_schema('test_null');
  52. $this->installTables($schema);
  53. db_insert('test_null')
  54. ->fields(array('name', 'age'))
  55. ->values(array(
  56. 'name' => 'Kermit',
  57. 'age' => 25,
  58. ))
  59. ->values(array(
  60. 'name' => 'Fozzie',
  61. 'age' => NULL,
  62. ))
  63. ->values(array(
  64. 'name' => 'Gonzo',
  65. 'age' => 27,
  66. ))
  67. ->execute();
  68. }
  69. /**
  70. * Setup our sample data.
  71. *
  72. * These are added using db_query(), since we're not trying to test the
  73. * INSERT operations here, just populate.
  74. */
  75. function addSampleData() {
  76. // We need the IDs, so we can't use a multi-insert here.
  77. $john = db_insert('test')
  78. ->fields(array(
  79. 'name' => 'John',
  80. 'age' => 25,
  81. 'job' => 'Singer',
  82. ))
  83. ->execute();
  84. $george = db_insert('test')
  85. ->fields(array(
  86. 'name' => 'George',
  87. 'age' => 27,
  88. 'job' => 'Singer',
  89. ))
  90. ->execute();
  91. $ringo = db_insert('test')
  92. ->fields(array(
  93. 'name' => 'Ringo',
  94. 'age' => 28,
  95. 'job' => 'Drummer',
  96. ))
  97. ->execute();
  98. $paul = db_insert('test')
  99. ->fields(array(
  100. 'name' => 'Paul',
  101. 'age' => 26,
  102. 'job' => 'Songwriter',
  103. ))
  104. ->execute();
  105. db_insert('test_people')
  106. ->fields(array(
  107. 'name' => 'Meredith',
  108. 'age' => 30,
  109. 'job' => 'Speaker',
  110. ))
  111. ->execute();
  112. db_insert('test_task')
  113. ->fields(array('pid', 'task', 'priority'))
  114. ->values(array(
  115. 'pid' => $john,
  116. 'task' => 'eat',
  117. 'priority' => 3,
  118. ))
  119. ->values(array(
  120. 'pid' => $john,
  121. 'task' => 'sleep',
  122. 'priority' => 4,
  123. ))
  124. ->values(array(
  125. 'pid' => $john,
  126. 'task' => 'code',
  127. 'priority' => 1,
  128. ))
  129. ->values(array(
  130. 'pid' => $george,
  131. 'task' => 'sing',
  132. 'priority' => 2,
  133. ))
  134. ->values(array(
  135. 'pid' => $george,
  136. 'task' => 'sleep',
  137. 'priority' => 2,
  138. ))
  139. ->values(array(
  140. 'pid' => $paul,
  141. 'task' => 'found new band',
  142. 'priority' => 1,
  143. ))
  144. ->values(array(
  145. 'pid' => $paul,
  146. 'task' => 'perform at superbowl',
  147. 'priority' => 3,
  148. ))
  149. ->execute();
  150. }
  151. }
  152. /**
  153. * Test connection management.
  154. */
  155. class DatabaseConnectionTestCase extends DatabaseTestCase {
  156. public static function getInfo() {
  157. return array(
  158. 'name' => 'Connection tests',
  159. 'description' => 'Tests of the core database system.',
  160. 'group' => 'Database',
  161. );
  162. }
  163. /**
  164. * Test that connections return appropriate connection objects.
  165. */
  166. function testConnectionRouting() {
  167. // Clone the master credentials to a slave connection.
  168. // Note this will result in two independent connection objects that happen
  169. // to point to the same place.
  170. $connection_info = Database::getConnectionInfo('default');
  171. Database::addConnectionInfo('default', 'slave', $connection_info['default']);
  172. $db1 = Database::getConnection('default', 'default');
  173. $db2 = Database::getConnection('slave', 'default');
  174. $this->assertNotNull($db1, 'default connection is a real connection object.');
  175. $this->assertNotNull($db2, 'slave connection is a real connection object.');
  176. $this->assertNotIdentical($db1, $db2, 'Each target refers to a different connection.');
  177. // Try to open those targets another time, that should return the same objects.
  178. $db1b = Database::getConnection('default', 'default');
  179. $db2b = Database::getConnection('slave', 'default');
  180. $this->assertIdentical($db1, $db1b, 'A second call to getConnection() returns the same object.');
  181. $this->assertIdentical($db2, $db2b, 'A second call to getConnection() returns the same object.');
  182. // Try to open an unknown target.
  183. $unknown_target = $this->randomName();
  184. $db3 = Database::getConnection($unknown_target, 'default');
  185. $this->assertNotNull($db3, 'Opening an unknown target returns a real connection object.');
  186. $this->assertIdentical($db1, $db3, 'An unknown target opens the default connection.');
  187. // Try to open that unknown target another time, that should return the same object.
  188. $db3b = Database::getConnection($unknown_target, 'default');
  189. $this->assertIdentical($db3, $db3b, 'A second call to getConnection() returns the same object.');
  190. }
  191. /**
  192. * Test that connections return appropriate connection objects.
  193. */
  194. function testConnectionRoutingOverride() {
  195. // Clone the master credentials to a slave connection.
  196. // Note this will result in two independent connection objects that happen
  197. // to point to the same place.
  198. $connection_info = Database::getConnectionInfo('default');
  199. Database::addConnectionInfo('default', 'slave', $connection_info['default']);
  200. Database::ignoreTarget('default', 'slave');
  201. $db1 = Database::getConnection('default', 'default');
  202. $db2 = Database::getConnection('slave', 'default');
  203. $this->assertIdentical($db1, $db2, 'Both targets refer to the same connection.');
  204. }
  205. /**
  206. * Tests the closing of a database connection.
  207. */
  208. function testConnectionClosing() {
  209. // Open the default target so we have an object to compare.
  210. $db1 = Database::getConnection('default', 'default');
  211. // Try to close the default connection, then open a new one.
  212. Database::closeConnection('default', 'default');
  213. $db2 = Database::getConnection('default', 'default');
  214. // Opening a connection after closing it should yield an object different than the original.
  215. $this->assertNotIdentical($db1, $db2, 'Opening the default connection after it is closed returns a new object.');
  216. }
  217. /**
  218. * Tests the connection options of the active database.
  219. */
  220. function testConnectionOptions() {
  221. $connection_info = Database::getConnectionInfo('default');
  222. // Be sure we're connected to the default database.
  223. $db = Database::getConnection('default', 'default');
  224. $connectionOptions = $db->getConnectionOptions();
  225. // In the MySQL driver, the port can be different, so check individual
  226. // options.
  227. $this->assertEqual($connection_info['default']['driver'], $connectionOptions['driver'], 'The default connection info driver matches the current connection options driver.');
  228. $this->assertEqual($connection_info['default']['database'], $connectionOptions['database'], 'The default connection info database matches the current connection options database.');
  229. // Set up identical slave and confirm connection options are identical.
  230. Database::addConnectionInfo('default', 'slave', $connection_info['default']);
  231. $db2 = Database::getConnection('slave', 'default');
  232. $connectionOptions2 = $db2->getConnectionOptions();
  233. // Get a fresh copy of the default connection options.
  234. $connectionOptions = $db->getConnectionOptions();
  235. $this->assertIdentical($connectionOptions, $connectionOptions2, 'The default and slave connection options are identical.');
  236. // Set up a new connection with different connection info.
  237. $test = $connection_info['default'];
  238. $test['database'] .= 'test';
  239. Database::addConnectionInfo('test', 'default', $test);
  240. $connection_info = Database::getConnectionInfo('test');
  241. // Get a fresh copy of the default connection options.
  242. $connectionOptions = $db->getConnectionOptions();
  243. $this->assertNotEqual($connection_info['default']['database'], $connectionOptions['database'], 'The test connection info database does not match the current connection options database.');
  244. }
  245. }
  246. /**
  247. * Test cloning Select queries.
  248. */
  249. class DatabaseSelectCloneTest extends DatabaseTestCase {
  250. public static function getInfo() {
  251. return array(
  252. 'name' => 'Select tests, cloning',
  253. 'description' => 'Test cloning Select queries.',
  254. 'group' => 'Database',
  255. );
  256. }
  257. /**
  258. * Test that subqueries as value within conditions are cloned properly.
  259. */
  260. function testSelectConditionSubQueryCloning() {
  261. $subquery = db_select('test', 't');
  262. $subquery->addField('t', 'id', 'id');
  263. $subquery->condition('age', 28, '<');
  264. $query = db_select('test', 't');
  265. $query->addField('t', 'name', 'name');
  266. $query->condition('id', $subquery, 'IN');
  267. $clone = clone $query;
  268. // Cloned query should not be altered by the following modification
  269. // happening on original query.
  270. $subquery->condition('age', 25, '>');
  271. $clone_result = $clone->countQuery()->execute()->fetchField();
  272. $query_result = $query->countQuery()->execute()->fetchField();
  273. // Make sure the cloned query has not been modified
  274. $this->assertEqual(3, $clone_result, 'The cloned query returns the expected number of rows');
  275. $this->assertEqual(2, $query_result, 'The query returns the expected number of rows');
  276. }
  277. }
  278. /**
  279. * Test fetch actions, part 1.
  280. *
  281. * We get timeout errors if we try to run too many tests at once.
  282. */
  283. class DatabaseFetchTestCase extends DatabaseTestCase {
  284. public static function getInfo() {
  285. return array(
  286. 'name' => 'Fetch tests',
  287. 'description' => 'Test the Database system\'s various fetch capabilities.',
  288. 'group' => 'Database',
  289. );
  290. }
  291. /**
  292. * Confirm that we can fetch a record properly in default object mode.
  293. */
  294. function testQueryFetchDefault() {
  295. $records = array();
  296. $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25));
  297. $this->assertTrue($result instanceof DatabaseStatementInterface, 'Result set is a Drupal statement object.');
  298. foreach ($result as $record) {
  299. $records[] = $record;
  300. $this->assertTrue(is_object($record), 'Record is an object.');
  301. $this->assertIdentical($record->name, 'John', '25 year old is John.');
  302. }
  303. $this->assertIdentical(count($records), 1, 'There is only one record.');
  304. }
  305. /**
  306. * Confirm that we can fetch a record to an object explicitly.
  307. */
  308. function testQueryFetchObject() {
  309. $records = array();
  310. $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_OBJ));
  311. foreach ($result as $record) {
  312. $records[] = $record;
  313. $this->assertTrue(is_object($record), 'Record is an object.');
  314. $this->assertIdentical($record->name, 'John', '25 year old is John.');
  315. }
  316. $this->assertIdentical(count($records), 1, 'There is only one record.');
  317. }
  318. /**
  319. * Confirm that we can fetch a record to an array associative explicitly.
  320. */
  321. function testQueryFetchArray() {
  322. $records = array();
  323. $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_ASSOC));
  324. foreach ($result as $record) {
  325. $records[] = $record;
  326. if ($this->assertTrue(is_array($record), 'Record is an array.')) {
  327. $this->assertIdentical($record['name'], 'John', 'Record can be accessed associatively.');
  328. }
  329. }
  330. $this->assertIdentical(count($records), 1, 'There is only one record.');
  331. }
  332. /**
  333. * Confirm that we can fetch a record into a new instance of a custom class.
  334. *
  335. * @see FakeRecord
  336. */
  337. function testQueryFetchClass() {
  338. $records = array();
  339. $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => 'FakeRecord'));
  340. foreach ($result as $record) {
  341. $records[] = $record;
  342. if ($this->assertTrue($record instanceof FakeRecord, 'Record is an object of class FakeRecord.')) {
  343. $this->assertIdentical($record->name, 'John', '25 year old is John.');
  344. }
  345. }
  346. $this->assertIdentical(count($records), 1, 'There is only one record.');
  347. }
  348. }
  349. /**
  350. * Test fetch actions, part 2.
  351. *
  352. * We get timeout errors if we try to run too many tests at once.
  353. */
  354. class DatabaseFetch2TestCase extends DatabaseTestCase {
  355. public static function getInfo() {
  356. return array(
  357. 'name' => 'Fetch tests, part 2',
  358. 'description' => 'Test the Database system\'s various fetch capabilities.',
  359. 'group' => 'Database',
  360. );
  361. }
  362. function setUp() {
  363. parent::setUp();
  364. }
  365. // Confirm that we can fetch a record into an indexed array explicitly.
  366. function testQueryFetchNum() {
  367. $records = array();
  368. $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_NUM));
  369. foreach ($result as $record) {
  370. $records[] = $record;
  371. if ($this->assertTrue(is_array($record), 'Record is an array.')) {
  372. $this->assertIdentical($record[0], 'John', 'Record can be accessed numerically.');
  373. }
  374. }
  375. $this->assertIdentical(count($records), 1, 'There is only one record');
  376. }
  377. /**
  378. * Confirm that we can fetch a record into a doubly-keyed array explicitly.
  379. */
  380. function testQueryFetchBoth() {
  381. $records = array();
  382. $result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => PDO::FETCH_BOTH));
  383. foreach ($result as $record) {
  384. $records[] = $record;
  385. if ($this->assertTrue(is_array($record), 'Record is an array.')) {
  386. $this->assertIdentical($record[0], 'John', 'Record can be accessed numerically.');
  387. $this->assertIdentical($record['name'], 'John', 'Record can be accessed associatively.');
  388. }
  389. }
  390. $this->assertIdentical(count($records), 1, 'There is only one record.');
  391. }
  392. /**
  393. * Confirm that we can fetch an entire column of a result set at once.
  394. */
  395. function testQueryFetchCol() {
  396. $records = array();
  397. $result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
  398. $column = $result->fetchCol();
  399. $this->assertIdentical(count($column), 3, 'fetchCol() returns the right number of records.');
  400. $result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
  401. $i = 0;
  402. foreach ($result as $record) {
  403. $this->assertIdentical($record->name, $column[$i++], 'Column matches direct accesss.');
  404. }
  405. }
  406. }
  407. /**
  408. * Test the insert builder.
  409. */
  410. class DatabaseInsertTestCase extends DatabaseTestCase {
  411. public static function getInfo() {
  412. return array(
  413. 'name' => 'Insert tests',
  414. 'description' => 'Test the Insert query builder.',
  415. 'group' => 'Database',
  416. );
  417. }
  418. /**
  419. * Test the very basic insert functionality.
  420. */
  421. function testSimpleInsert() {
  422. $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  423. $query = db_insert('test');
  424. $query->fields(array(
  425. 'name' => 'Yoko',
  426. 'age' => '29',
  427. ));
  428. $query->execute();
  429. $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  430. $this->assertIdentical($num_records_before + 1, (int) $num_records_after, 'Record inserts correctly.');
  431. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Yoko'))->fetchField();
  432. $this->assertIdentical($saved_age, '29', 'Can retrieve after inserting.');
  433. }
  434. /**
  435. * Test that we can insert multiple records in one query object.
  436. */
  437. function testMultiInsert() {
  438. $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  439. $query = db_insert('test');
  440. $query->fields(array(
  441. 'name' => 'Larry',
  442. 'age' => '30',
  443. ));
  444. // We should be able to specify values in any order if named.
  445. $query->values(array(
  446. 'age' => '31',
  447. 'name' => 'Curly',
  448. ));
  449. // We should be able to say "use the field order".
  450. // This is not the recommended mechanism for most cases, but it should work.
  451. $query->values(array('Moe', '32'));
  452. $query->execute();
  453. $num_records_after = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  454. $this->assertIdentical($num_records_before + 3, $num_records_after, 'Record inserts correctly.');
  455. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
  456. $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
  457. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
  458. $this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
  459. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
  460. $this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
  461. }
  462. /**
  463. * Test that an insert object can be reused with new data after it executes.
  464. */
  465. function testRepeatedInsert() {
  466. $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  467. $query = db_insert('test');
  468. $query->fields(array(
  469. 'name' => 'Larry',
  470. 'age' => '30',
  471. ));
  472. $query->execute(); // This should run the insert, but leave the fields intact.
  473. // We should be able to specify values in any order if named.
  474. $query->values(array(
  475. 'age' => '31',
  476. 'name' => 'Curly',
  477. ));
  478. $query->execute();
  479. // We should be able to say "use the field order".
  480. $query->values(array('Moe', '32'));
  481. $query->execute();
  482. $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  483. $this->assertIdentical((int) $num_records_before + 3, (int) $num_records_after, 'Record inserts correctly.');
  484. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
  485. $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
  486. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
  487. $this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
  488. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
  489. $this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
  490. }
  491. /**
  492. * Test that we can specify fields without values and specify values later.
  493. */
  494. function testInsertFieldOnlyDefinintion() {
  495. // This is useful for importers, when we want to create a query and define
  496. // its fields once, then loop over a multi-insert execution.
  497. db_insert('test')
  498. ->fields(array('name', 'age'))
  499. ->values(array('Larry', '30'))
  500. ->values(array('Curly', '31'))
  501. ->values(array('Moe', '32'))
  502. ->execute();
  503. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
  504. $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
  505. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
  506. $this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
  507. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
  508. $this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
  509. }
  510. /**
  511. * Test that inserts return the proper auto-increment ID.
  512. */
  513. function testInsertLastInsertID() {
  514. $id = db_insert('test')
  515. ->fields(array(
  516. 'name' => 'Larry',
  517. 'age' => '30',
  518. ))
  519. ->execute();
  520. $this->assertIdentical($id, '5', 'Auto-increment ID returned successfully.');
  521. }
  522. /**
  523. * Test that the INSERT INTO ... SELECT (fields) ... syntax works.
  524. */
  525. function testInsertSelectFields() {
  526. $query = db_select('test_people', 'tp');
  527. // The query builder will always append expressions after fields.
  528. // Add the expression first to test that the insert fields are correctly
  529. // re-ordered.
  530. $query->addExpression('tp.age', 'age');
  531. $query
  532. ->fields('tp', array('name','job'))
  533. ->condition('tp.name', 'Meredith');
  534. // The resulting query should be equivalent to:
  535. // INSERT INTO test (age, name, job)
  536. // SELECT tp.age AS age, tp.name AS name, tp.job AS job
  537. // FROM test_people tp
  538. // WHERE tp.name = 'Meredith'
  539. db_insert('test')
  540. ->from($query)
  541. ->execute();
  542. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
  543. $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
  544. }
  545. /**
  546. * Tests that the INSERT INTO ... SELECT * ... syntax works.
  547. */
  548. function testInsertSelectAll() {
  549. $query = db_select('test_people', 'tp')
  550. ->fields('tp')
  551. ->condition('tp.name', 'Meredith');
  552. // The resulting query should be equivalent to:
  553. // INSERT INTO test_people_copy
  554. // SELECT *
  555. // FROM test_people tp
  556. // WHERE tp.name = 'Meredith'
  557. db_insert('test_people_copy')
  558. ->from($query)
  559. ->execute();
  560. $saved_age = db_query('SELECT age FROM {test_people_copy} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
  561. $this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
  562. }
  563. }
  564. /**
  565. * Insert tests using LOB fields, which are weird on some databases.
  566. */
  567. class DatabaseInsertLOBTestCase extends DatabaseTestCase {
  568. public static function getInfo() {
  569. return array(
  570. 'name' => 'Insert tests, LOB fields',
  571. 'description' => 'Test the Insert query builder with LOB fields.',
  572. 'group' => 'Database',
  573. );
  574. }
  575. /**
  576. * Test that we can insert a single blob field successfully.
  577. */
  578. function testInsertOneBlob() {
  579. $data = "This is\000a test.";
  580. $this->assertTrue(strlen($data) === 15, 'Test data contains a NULL.');
  581. $id = db_insert('test_one_blob')
  582. ->fields(array('blob1' => $data))
  583. ->execute();
  584. $r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', array(':id' => $id))->fetchAssoc();
  585. $this->assertTrue($r['blob1'] === $data, format_string('Can insert a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
  586. }
  587. /**
  588. * Test that we can insert multiple blob fields in the same query.
  589. */
  590. function testInsertMultipleBlob() {
  591. $id = db_insert('test_two_blobs')
  592. ->fields(array(
  593. 'blob1' => 'This is',
  594. 'blob2' => 'a test',
  595. ))
  596. ->execute();
  597. $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
  598. $this->assertTrue($r['blob1'] === 'This is' && $r['blob2'] === 'a test', 'Can insert multiple blobs per row.');
  599. }
  600. }
  601. /**
  602. * Insert tests for "database default" values.
  603. */
  604. class DatabaseInsertDefaultsTestCase extends DatabaseTestCase {
  605. public static function getInfo() {
  606. return array(
  607. 'name' => 'Insert tests, default fields',
  608. 'description' => 'Test the Insert query builder with default values.',
  609. 'group' => 'Database',
  610. );
  611. }
  612. /**
  613. * Test that we can run a query that is "default values for everything".
  614. */
  615. function testDefaultInsert() {
  616. $query = db_insert('test')->useDefaults(array('job'));
  617. $id = $query->execute();
  618. $schema = drupal_get_schema('test');
  619. $job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
  620. $this->assertEqual($job, $schema['fields']['job']['default'], 'Default field value is set.');
  621. }
  622. /**
  623. * Test that no action will be preformed if no fields are specified.
  624. */
  625. function testDefaultEmptyInsert() {
  626. $num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  627. try {
  628. $result = db_insert('test')->execute();
  629. // This is only executed if no exception has been thrown.
  630. $this->fail('Expected exception NoFieldsException has not been thrown.');
  631. } catch (NoFieldsException $e) {
  632. $this->pass('Expected exception NoFieldsException has been thrown.');
  633. }
  634. $num_records_after = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  635. $this->assertIdentical($num_records_before, $num_records_after, 'Do nothing as no fields are specified.');
  636. }
  637. /**
  638. * Test that we can insert fields with values and defaults in the same query.
  639. */
  640. function testDefaultInsertWithFields() {
  641. $query = db_insert('test')
  642. ->fields(array('name' => 'Bob'))
  643. ->useDefaults(array('job'));
  644. $id = $query->execute();
  645. $schema = drupal_get_schema('test');
  646. $job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
  647. $this->assertEqual($job, $schema['fields']['job']['default'], 'Default field value is set.');
  648. }
  649. }
  650. /**
  651. * Update builder tests.
  652. */
  653. class DatabaseUpdateTestCase extends DatabaseTestCase {
  654. public static function getInfo() {
  655. return array(
  656. 'name' => 'Update tests',
  657. 'description' => 'Test the Update query builder.',
  658. 'group' => 'Database',
  659. );
  660. }
  661. /**
  662. * Confirm that we can update a single record successfully.
  663. */
  664. function testSimpleUpdate() {
  665. $num_updated = db_update('test')
  666. ->fields(array('name' => 'Tiffany'))
  667. ->condition('id', 1)
  668. ->execute();
  669. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  670. $saved_name = db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 1))->fetchField();
  671. $this->assertIdentical($saved_name, 'Tiffany', 'Updated name successfully.');
  672. }
  673. /**
  674. * Confirm updating to NULL.
  675. */
  676. function testSimpleNullUpdate() {
  677. $this->ensureSampleDataNull();
  678. $num_updated = db_update('test_null')
  679. ->fields(array('age' => NULL))
  680. ->condition('name', 'Kermit')
  681. ->execute();
  682. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  683. $saved_age = db_query('SELECT age FROM {test_null} WHERE name = :name', array(':name' => 'Kermit'))->fetchField();
  684. $this->assertNull($saved_age, 'Updated name successfully.');
  685. }
  686. /**
  687. * Confirm that we can update a multiple records successfully.
  688. */
  689. function testMultiUpdate() {
  690. $num_updated = db_update('test')
  691. ->fields(array('job' => 'Musician'))
  692. ->condition('job', 'Singer')
  693. ->execute();
  694. $this->assertIdentical($num_updated, 2, 'Updated 2 records.');
  695. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  696. $this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
  697. }
  698. /**
  699. * Confirm that we can update a multiple records with a non-equality condition.
  700. */
  701. function testMultiGTUpdate() {
  702. $num_updated = db_update('test')
  703. ->fields(array('job' => 'Musician'))
  704. ->condition('age', 26, '>')
  705. ->execute();
  706. $this->assertIdentical($num_updated, 2, 'Updated 2 records.');
  707. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  708. $this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
  709. }
  710. /**
  711. * Confirm that we can update a multiple records with a where call.
  712. */
  713. function testWhereUpdate() {
  714. $num_updated = db_update('test')
  715. ->fields(array('job' => 'Musician'))
  716. ->where('age > :age', array(':age' => 26))
  717. ->execute();
  718. $this->assertIdentical($num_updated, 2, 'Updated 2 records.');
  719. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  720. $this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
  721. }
  722. /**
  723. * Confirm that we can stack condition and where calls.
  724. */
  725. function testWhereAndConditionUpdate() {
  726. $update = db_update('test')
  727. ->fields(array('job' => 'Musician'))
  728. ->where('age > :age', array(':age' => 26))
  729. ->condition('name', 'Ringo');
  730. $num_updated = $update->execute();
  731. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  732. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  733. $this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
  734. }
  735. /**
  736. * Test updating with expressions.
  737. */
  738. function testExpressionUpdate() {
  739. // Set age = 1 for a single row for this test to work.
  740. db_update('test')
  741. ->condition('id', 1)
  742. ->fields(array('age' => 1))
  743. ->execute();
  744. // Ensure that expressions are handled properly. This should set every
  745. // record's age to a square of itself, which will change only three of the
  746. // four records in the table since 1*1 = 1. That means only three records
  747. // are modified, so we should get back 3, not 4, from execute().
  748. $num_rows = db_update('test')
  749. ->expression('age', 'age * age')
  750. ->execute();
  751. $this->assertIdentical($num_rows, 3, 'Number of affected rows are returned.');
  752. }
  753. /**
  754. * Confirm that we can update the primary key of a record successfully.
  755. */
  756. function testPrimaryKeyUpdate() {
  757. $num_updated = db_update('test')
  758. ->fields(array('id' => 42, 'name' => 'John'))
  759. ->condition('id', 1)
  760. ->execute();
  761. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  762. $saved_name= db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 42))->fetchField();
  763. $this->assertIdentical($saved_name, 'John', 'Updated primary key successfully.');
  764. }
  765. }
  766. /**
  767. * Tests for more complex update statements.
  768. */
  769. class DatabaseUpdateComplexTestCase extends DatabaseTestCase {
  770. public static function getInfo() {
  771. return array(
  772. 'name' => 'Update tests, Complex',
  773. 'description' => 'Test the Update query builder, complex queries.',
  774. 'group' => 'Database',
  775. );
  776. }
  777. /**
  778. * Test updates with OR conditionals.
  779. */
  780. function testOrConditionUpdate() {
  781. $update = db_update('test')
  782. ->fields(array('job' => 'Musician'))
  783. ->condition(db_or()
  784. ->condition('name', 'John')
  785. ->condition('name', 'Paul')
  786. );
  787. $num_updated = $update->execute();
  788. $this->assertIdentical($num_updated, 2, 'Updated 2 records.');
  789. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  790. $this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
  791. }
  792. /**
  793. * Test WHERE IN clauses.
  794. */
  795. function testInConditionUpdate() {
  796. $num_updated = db_update('test')
  797. ->fields(array('job' => 'Musician'))
  798. ->condition('name', array('John', 'Paul'), 'IN')
  799. ->execute();
  800. $this->assertIdentical($num_updated, 2, 'Updated 2 records.');
  801. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  802. $this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
  803. }
  804. /**
  805. * Test WHERE NOT IN clauses.
  806. */
  807. function testNotInConditionUpdate() {
  808. // The o is lowercase in the 'NoT IN' operator, to make sure the operators
  809. // work in mixed case.
  810. $num_updated = db_update('test')
  811. ->fields(array('job' => 'Musician'))
  812. ->condition('name', array('John', 'Paul', 'George'), 'NoT IN')
  813. ->execute();
  814. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  815. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  816. $this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
  817. }
  818. /**
  819. * Test BETWEEN conditional clauses.
  820. */
  821. function testBetweenConditionUpdate() {
  822. $num_updated = db_update('test')
  823. ->fields(array('job' => 'Musician'))
  824. ->condition('age', array(25, 26), 'BETWEEN')
  825. ->execute();
  826. $this->assertIdentical($num_updated, 2, 'Updated 2 records.');
  827. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  828. $this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
  829. }
  830. /**
  831. * Test LIKE conditionals.
  832. */
  833. function testLikeConditionUpdate() {
  834. $num_updated = db_update('test')
  835. ->fields(array('job' => 'Musician'))
  836. ->condition('name', '%ge%', 'LIKE')
  837. ->execute();
  838. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  839. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  840. $this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
  841. }
  842. /**
  843. * Test update with expression values.
  844. */
  845. function testUpdateExpression() {
  846. $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
  847. $GLOBALS['larry_test'] = 1;
  848. $num_updated = db_update('test')
  849. ->condition('name', 'Ringo')
  850. ->fields(array('job' => 'Musician'))
  851. ->expression('age', 'age + :age', array(':age' => 4))
  852. ->execute();
  853. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  854. $num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
  855. $this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
  856. $person = db_query('SELECT * FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetch();
  857. $this->assertEqual($person->name, 'Ringo', 'Name set correctly.');
  858. $this->assertEqual($person->age, $before_age + 4, 'Age set correctly.');
  859. $this->assertEqual($person->job, 'Musician', 'Job set correctly.');
  860. $GLOBALS['larry_test'] = 0;
  861. }
  862. /**
  863. * Test update with only expression values.
  864. */
  865. function testUpdateOnlyExpression() {
  866. $before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
  867. $num_updated = db_update('test')
  868. ->condition('name', 'Ringo')
  869. ->expression('age', 'age + :age', array(':age' => 4))
  870. ->execute();
  871. $this->assertIdentical($num_updated, 1, 'Updated 1 record.');
  872. $after_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
  873. $this->assertEqual($before_age + 4, $after_age, 'Age updated correctly');
  874. }
  875. }
  876. /**
  877. * Test update queries involving LOB values.
  878. */
  879. class DatabaseUpdateLOBTestCase extends DatabaseTestCase {
  880. public static function getInfo() {
  881. return array(
  882. 'name' => 'Update tests, LOB',
  883. 'description' => 'Test the Update query builder with LOB fields.',
  884. 'group' => 'Database',
  885. );
  886. }
  887. /**
  888. * Confirm that we can update a blob column.
  889. */
  890. function testUpdateOneBlob() {
  891. $data = "This is\000a test.";
  892. $this->assertTrue(strlen($data) === 15, 'Test data contains a NULL.');
  893. $id = db_insert('test_one_blob')
  894. ->fields(array('blob1' => $data))
  895. ->execute();
  896. $data .= $data;
  897. db_update('test_one_blob')
  898. ->condition('id', $id)
  899. ->fields(array('blob1' => $data))
  900. ->execute();
  901. $r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', array(':id' => $id))->fetchAssoc();
  902. $this->assertTrue($r['blob1'] === $data, format_string('Can update a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
  903. }
  904. /**
  905. * Confirm that we can update two blob columns in the same table.
  906. */
  907. function testUpdateMultipleBlob() {
  908. $id = db_insert('test_two_blobs')
  909. ->fields(array(
  910. 'blob1' => 'This is',
  911. 'blob2' => 'a test',
  912. ))
  913. ->execute();
  914. db_update('test_two_blobs')
  915. ->condition('id', $id)
  916. ->fields(array('blob1' => 'and so', 'blob2' => 'is this'))
  917. ->execute();
  918. $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
  919. $this->assertTrue($r['blob1'] === 'and so' && $r['blob2'] === 'is this', 'Can update multiple blobs per row.');
  920. }
  921. }
  922. /**
  923. * Delete/Truncate tests.
  924. *
  925. * The DELETE tests are not as extensive, as all of the interesting code for
  926. * DELETE queries is in the conditional which is identical to the UPDATE and
  927. * SELECT conditional handling.
  928. *
  929. * The TRUNCATE tests are not extensive either, because the behavior of
  930. * TRUNCATE queries is not consistent across database engines. We only test
  931. * that a TRUNCATE query actually deletes all rows from the target table.
  932. */
  933. class DatabaseDeleteTruncateTestCase extends DatabaseTestCase {
  934. public static function getInfo() {
  935. return array(
  936. 'name' => 'Delete/Truncate tests',
  937. 'description' => 'Test the Delete and Truncate query builders.',
  938. 'group' => 'Database',
  939. );
  940. }
  941. /**
  942. * Confirm that we can use a subselect in a delete successfully.
  943. */
  944. function testSubselectDelete() {
  945. $num_records_before = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
  946. $pid_to_delete = db_query("SELECT * FROM {test_task} WHERE task = 'sleep'")->fetchField();
  947. $subquery = db_select('test', 't')
  948. ->fields('t', array('id'))
  949. ->condition('t.id', array($pid_to_delete), 'IN');
  950. $delete = db_delete('test_task')
  951. ->condition('task', 'sleep')
  952. ->condition('pid', $subquery, 'IN');
  953. $num_deleted = $delete->execute();
  954. $this->assertEqual($num_deleted, 1, "Deleted 1 record.");
  955. $num_records_after = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
  956. $this->assertEqual($num_records_before, $num_records_after + $num_deleted, 'Deletion adds up.');
  957. }
  958. /**
  959. * Confirm that we can delete a single record successfully.
  960. */
  961. function testSimpleDelete() {
  962. $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  963. $num_deleted = db_delete('test')
  964. ->condition('id', 1)
  965. ->execute();
  966. $this->assertIdentical($num_deleted, 1, 'Deleted 1 record.');
  967. $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  968. $this->assertEqual($num_records_before, $num_records_after + $num_deleted, 'Deletion adds up.');
  969. }
  970. /**
  971. * Confirm that we can truncate a whole table successfully.
  972. */
  973. function testTruncate() {
  974. $num_records_before = db_query("SELECT COUNT(*) FROM {test}")->fetchField();
  975. db_truncate('test')->execute();
  976. $num_records_after = db_query("SELECT COUNT(*) FROM {test}")->fetchField();
  977. $this->assertEqual(0, $num_records_after, 'Truncate really deletes everything.');
  978. }
  979. }
  980. /**
  981. * Test the MERGE query builder.
  982. */
  983. class DatabaseMergeTestCase extends DatabaseTestCase {
  984. public static function getInfo() {
  985. return array(
  986. 'name' => 'Merge tests',
  987. 'description' => 'Test the Merge query builder.',
  988. 'group' => 'Database',
  989. );
  990. }
  991. /**
  992. * Confirm that we can merge-insert a record successfully.
  993. */
  994. function testMergeInsert() {
  995. $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  996. $result = db_merge('test_people')
  997. ->key(array('job' => 'Presenter'))
  998. ->fields(array(
  999. 'age' => 31,
  1000. 'name' => 'Tiffany',
  1001. ))
  1002. ->execute();
  1003. $this->assertEqual($result, MergeQuery::STATUS_INSERT, 'Insert status returned.');
  1004. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1005. $this->assertEqual($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
  1006. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
  1007. $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
  1008. $this->assertEqual($person->age, 31, 'Age set correctly.');
  1009. $this->assertEqual($person->job, 'Presenter', 'Job set correctly.');
  1010. }
  1011. /**
  1012. * Confirm that we can merge-update a record successfully.
  1013. */
  1014. function testMergeUpdate() {
  1015. $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1016. $result = db_merge('test_people')
  1017. ->key(array('job' => 'Speaker'))
  1018. ->fields(array(
  1019. 'age' => 31,
  1020. 'name' => 'Tiffany',
  1021. ))
  1022. ->execute();
  1023. $this->assertEqual($result, MergeQuery::STATUS_UPDATE, 'Update status returned.');
  1024. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1025. $this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
  1026. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
  1027. $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
  1028. $this->assertEqual($person->age, 31, 'Age set correctly.');
  1029. $this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
  1030. }
  1031. /**
  1032. * Confirm that we can merge-update a record successfully, with different insert and update.
  1033. */
  1034. function testMergeUpdateExcept() {
  1035. $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1036. db_merge('test_people')
  1037. ->key(array('job' => 'Speaker'))
  1038. ->insertFields(array('age' => 31))
  1039. ->updateFields(array('name' => 'Tiffany'))
  1040. ->execute();
  1041. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1042. $this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
  1043. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
  1044. $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
  1045. $this->assertEqual($person->age, 30, 'Age skipped correctly.');
  1046. $this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
  1047. }
  1048. /**
  1049. * Confirm that we can merge-update a record successfully, with alternate replacement.
  1050. */
  1051. function testMergeUpdateExplicit() {
  1052. $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1053. db_merge('test_people')
  1054. ->key(array('job' => 'Speaker'))
  1055. ->insertFields(array(
  1056. 'age' => 31,
  1057. 'name' => 'Tiffany',
  1058. ))
  1059. ->updateFields(array(
  1060. 'name' => 'Joe',
  1061. ))
  1062. ->execute();
  1063. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1064. $this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
  1065. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
  1066. $this->assertEqual($person->name, 'Joe', 'Name set correctly.');
  1067. $this->assertEqual($person->age, 30, 'Age skipped correctly.');
  1068. $this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
  1069. }
  1070. /**
  1071. * Confirm that we can merge-update a record successfully, with expressions.
  1072. */
  1073. function testMergeUpdateExpression() {
  1074. $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1075. $age_before = db_query('SELECT age FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetchField();
  1076. // This is a very contrived example, as I have no idea why you'd want to
  1077. // change age this way, but that's beside the point.
  1078. // Note that we are also double-setting age here, once as a literal and
  1079. // once as an expression. This test will only pass if the expression wins,
  1080. // which is what is supposed to happen.
  1081. db_merge('test_people')
  1082. ->key(array('job' => 'Speaker'))
  1083. ->fields(array('name' => 'Tiffany'))
  1084. ->insertFields(array('age' => 31))
  1085. ->expression('age', 'age + :age', array(':age' => 4))
  1086. ->execute();
  1087. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1088. $this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
  1089. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
  1090. $this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
  1091. $this->assertEqual($person->age, $age_before + 4, 'Age updated correctly.');
  1092. $this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
  1093. }
  1094. /**
  1095. * Test that we can merge-insert without any update fields.
  1096. */
  1097. function testMergeInsertWithoutUpdate() {
  1098. $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1099. db_merge('test_people')
  1100. ->key(array('job' => 'Presenter'))
  1101. ->execute();
  1102. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1103. $this->assertEqual($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
  1104. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
  1105. $this->assertEqual($person->name, '', 'Name set correctly.');
  1106. $this->assertEqual($person->age, 0, 'Age set correctly.');
  1107. $this->assertEqual($person->job, 'Presenter', 'Job set correctly.');
  1108. }
  1109. /**
  1110. * Confirm that we can merge-update without any update fields.
  1111. */
  1112. function testMergeUpdateWithoutUpdate() {
  1113. $num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1114. db_merge('test_people')
  1115. ->key(array('job' => 'Speaker'))
  1116. ->execute();
  1117. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1118. $this->assertEqual($num_records_before, $num_records_after, 'Merge skipped properly.');
  1119. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
  1120. $this->assertEqual($person->name, 'Meredith', 'Name skipped correctly.');
  1121. $this->assertEqual($person->age, 30, 'Age skipped correctly.');
  1122. $this->assertEqual($person->job, 'Speaker', 'Job skipped correctly.');
  1123. db_merge('test_people')
  1124. ->key(array('job' => 'Speaker'))
  1125. ->insertFields(array('age' => 31))
  1126. ->execute();
  1127. $num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
  1128. $this->assertEqual($num_records_before, $num_records_after, 'Merge skipped properly.');
  1129. $person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
  1130. $this->assertEqual($person->name, 'Meredith', 'Name skipped correctly.');
  1131. $this->assertEqual($person->age, 30, 'Age skipped correctly.');
  1132. $this->assertEqual($person->job, 'Speaker', 'Job skipped correctly.');
  1133. }
  1134. /**
  1135. * Test that an invalid merge query throws an exception like it is supposed to.
  1136. */
  1137. function testInvalidMerge() {
  1138. try {
  1139. // This query should die because there is no key field specified.
  1140. db_merge('test_people')
  1141. ->fields(array(
  1142. 'age' => 31,
  1143. 'name' => 'Tiffany',
  1144. ))
  1145. ->execute();
  1146. }
  1147. catch (InvalidMergeQueryException $e) {
  1148. $this->pass('InvalidMergeQueryException thrown for invalid query.');
  1149. return;
  1150. }
  1151. $this->fail('No InvalidMergeQueryException thrown');
  1152. }
  1153. }
  1154. /**
  1155. * Test the SELECT builder.
  1156. */
  1157. class DatabaseSelectTestCase extends DatabaseTestCase {
  1158. public static function getInfo() {
  1159. return array(
  1160. 'name' => 'Select tests',
  1161. 'description' => 'Test the Select query builder.',
  1162. 'group' => 'Database',
  1163. );
  1164. }
  1165. /**
  1166. * Test rudimentary SELECT statements.
  1167. */
  1168. function testSimpleSelect() {
  1169. $query = db_select('test');
  1170. $name_field = $query->addField('test', 'name');
  1171. $age_field = $query->addField('test', 'age', 'age');
  1172. $result = $query->execute();
  1173. $num_records = 0;
  1174. foreach ($result as $record) {
  1175. $num_records++;
  1176. }
  1177. $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
  1178. }
  1179. /**
  1180. * Test rudimentary SELECT statement with a COMMENT.
  1181. */
  1182. function testSimpleComment() {
  1183. $query = db_select('test')->comment('Testing query comments');
  1184. $name_field = $query->addField('test', 'name');
  1185. $age_field = $query->addField('test', 'age', 'age');
  1186. $result = $query->execute();
  1187. $num_records = 0;
  1188. foreach ($result as $record) {
  1189. $num_records++;
  1190. }
  1191. $query = (string)$query;
  1192. $expected = "/* Testing query comments */ SELECT test.name AS name, test.age AS age\nFROM \n{test} test";
  1193. $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
  1194. $this->assertEqual($query, $expected, 'The flattened query contains the comment string.');
  1195. }
  1196. /**
  1197. * Test query COMMENT system against vulnerabilities.
  1198. */
  1199. function testVulnerableComment() {
  1200. $query = db_select('test')->comment('Testing query comments */ SELECT nid FROM {node}; --');
  1201. $name_field = $query->addField('test', 'name');
  1202. $age_field = $query->addField('test', 'age', 'age');
  1203. $result = $query->execute();
  1204. $num_records = 0;
  1205. foreach ($result as $record) {
  1206. $num_records++;
  1207. }
  1208. $query = (string)$query;
  1209. $expected = "/* Testing query comments * / SELECT nid FROM {node}; -- */ SELECT test.name AS name, test.age AS age\nFROM \n{test} test";
  1210. $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
  1211. $this->assertEqual($query, $expected, 'The flattened query contains the sanitised comment string.');
  1212. $connection = Database::getConnection();
  1213. foreach ($this->makeCommentsProvider() as $test_set) {
  1214. list($expected, $comments) = $test_set;
  1215. $this->assertEqual($expected, $connection->makeComment($comments));
  1216. }
  1217. }
  1218. /**
  1219. * Provides expected and input values for testVulnerableComment().
  1220. */
  1221. function makeCommentsProvider() {
  1222. return array(
  1223. array(
  1224. '/* */ ',
  1225. array(''),
  1226. ),
  1227. // Try and close the comment early.
  1228. array(
  1229. '/* Exploit * / DROP TABLE node; -- */ ',
  1230. array('Exploit */ DROP TABLE node; --'),
  1231. ),
  1232. // Variations on comment closing.
  1233. array(
  1234. '/* Exploit * / * / DROP TABLE node; -- */ ',
  1235. array('Exploit */*/ DROP TABLE node; --'),
  1236. ),
  1237. array(
  1238. '/* Exploit * * // DROP TABLE node; -- */ ',
  1239. array('Exploit **// DROP TABLE node; --'),
  1240. ),
  1241. // Try closing the comment in the second string which is appended.
  1242. array(
  1243. '/* Exploit * / DROP TABLE node; --; Another try * / DROP TABLE node; -- */ ',
  1244. array('Exploit */ DROP TABLE node; --', 'Another try */ DROP TABLE node; --'),
  1245. ),
  1246. );
  1247. }
  1248. /**
  1249. * Test basic conditionals on SELECT statements.
  1250. */
  1251. function testSimpleSelectConditional() {
  1252. $query = db_select('test');
  1253. $name_field = $query->addField('test', 'name');
  1254. $age_field = $query->addField('test', 'age', 'age');
  1255. $query->condition('age', 27);
  1256. $result = $query->execute();
  1257. // Check that the aliases are being created the way we want.
  1258. $this->assertEqual($name_field, 'name', 'Name field alias is correct.');
  1259. $this->assertEqual($age_field, 'age', 'Age field alias is correct.');
  1260. // Ensure that we got the right record.
  1261. $record = $result->fetch();
  1262. $this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
  1263. $this->assertEqual($record->$age_field, 27, 'Fetched age is correct.');
  1264. }
  1265. /**
  1266. * Test SELECT statements with expressions.
  1267. */
  1268. function testSimpleSelectExpression() {
  1269. $query = db_select('test');
  1270. $name_field = $query->addField('test', 'name');
  1271. $age_field = $query->addExpression("age*2", 'double_age');
  1272. $query->condition('age', 27);
  1273. $result = $query->execute();
  1274. // Check that the aliases are being created the way we want.
  1275. $this->assertEqual($name_field, 'name', 'Name field alias is correct.');
  1276. $this->assertEqual($age_field, 'double_age', 'Age field alias is correct.');
  1277. // Ensure that we got the right record.
  1278. $record = $result->fetch();
  1279. $this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
  1280. $this->assertEqual($record->$age_field, 27*2, 'Fetched age expression is correct.');
  1281. }
  1282. /**
  1283. * Test SELECT statements with multiple expressions.
  1284. */
  1285. function testSimpleSelectExpressionMultiple() {
  1286. $query = db_select('test');
  1287. $name_field = $query->addField('test', 'name');
  1288. $age_double_field = $query->addExpression("age*2");
  1289. $age_triple_field = $query->addExpression("age*3");
  1290. $query->condition('age', 27);
  1291. $result = $query->execute();
  1292. // Check that the aliases are being created the way we want.
  1293. $this->assertEqual($age_double_field, 'expression', 'Double age field alias is correct.');
  1294. $this->assertEqual($age_triple_field, 'expression_2', 'Triple age field alias is correct.');
  1295. // Ensure that we got the right record.
  1296. $record = $result->fetch();
  1297. $this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
  1298. $this->assertEqual($record->$age_double_field, 27*2, 'Fetched double age expression is correct.');
  1299. $this->assertEqual($record->$age_triple_field, 27*3, 'Fetched triple age expression is correct.');
  1300. }
  1301. /**
  1302. * Test adding multiple fields to a select statement at the same time.
  1303. */
  1304. function testSimpleSelectMultipleFields() {
  1305. $record = db_select('test')
  1306. ->fields('test', array('id', 'name', 'age', 'job'))
  1307. ->condition('age', 27)
  1308. ->execute()->fetchObject();
  1309. // Check that all fields we asked for are present.
  1310. $this->assertNotNull($record->id, 'ID field is present.');
  1311. $this->assertNotNull($record->name, 'Name field is present.');
  1312. $this->assertNotNull($record->age, 'Age field is present.');
  1313. $this->assertNotNull($record->job, 'Job field is present.');
  1314. // Ensure that we got the right record.
  1315. // Check that all fields we asked for are present.
  1316. $this->assertEqual($record->id, 2, 'ID field has the correct value.');
  1317. $this->assertEqual($record->name, 'George', 'Name field has the correct value.');
  1318. $this->assertEqual($record->age, 27, 'Age field has the correct value.');
  1319. $this->assertEqual($record->job, 'Singer', 'Job field has the correct value.');
  1320. }
  1321. /**
  1322. * Test adding all fields from a given table to a select statement.
  1323. */
  1324. function testSimpleSelectAllFields() {
  1325. $record = db_select('test')
  1326. ->fields('test')
  1327. ->condition('age', 27)
  1328. ->execute()->fetchObject();
  1329. // Check that all fields we asked for are present.
  1330. $this->assertNotNull($record->id, 'ID field is present.');
  1331. $this->assertNotNull($record->name, 'Name field is present.');
  1332. $this->assertNotNull($record->age, 'Age field is present.');
  1333. $this->assertNotNull($record->job, 'Job field is present.');
  1334. // Ensure that we got the right record.
  1335. // Check that all fields we asked for are present.
  1336. $this->assertEqual($record->id, 2, 'ID field has the correct value.');
  1337. $this->assertEqual($record->name, 'George', 'Name field has the correct value.');
  1338. $this->assertEqual($record->age, 27, 'Age field has the correct value.');
  1339. $this->assertEqual($record->job, 'Singer', 'Job field has the correct value.');
  1340. }
  1341. /**
  1342. * Test that we can find a record with a NULL value.
  1343. */
  1344. function testNullCondition() {
  1345. $this->ensureSampleDataNull();
  1346. $names = db_select('test_null', 'tn')
  1347. ->fields('tn', array('name'))
  1348. ->isNull('age')
  1349. ->execute()->fetchCol();
  1350. $this->assertEqual(count($names), 1, 'Correct number of records found with NULL age.');
  1351. $this->assertEqual($names[0], 'Fozzie', 'Correct record returned for NULL age.');
  1352. }
  1353. /**
  1354. * Test that we can find a record without a NULL value.
  1355. */
  1356. function testNotNullCondition() {
  1357. $this->ensureSampleDataNull();
  1358. $names = db_select('test_null', 'tn')
  1359. ->fields('tn', array('name'))
  1360. ->isNotNull('tn.age')
  1361. ->orderBy('name')
  1362. ->execute()->fetchCol();
  1363. $this->assertEqual(count($names), 2, 'Correct number of records found withNOT NULL age.');
  1364. $this->assertEqual($names[0], 'Gonzo', 'Correct record returned for NOT NULL age.');
  1365. $this->assertEqual($names[1], 'Kermit', 'Correct record returned for NOT NULL age.');
  1366. }
  1367. /**
  1368. * Test that we can UNION multiple Select queries together. This is
  1369. * semantically equal to UNION DISTINCT, so we don't explicity test that.
  1370. */
  1371. function testUnion() {
  1372. $query_1 = db_select('test', 't')
  1373. ->fields('t', array('name'))
  1374. ->condition('age', array(27, 28), 'IN');
  1375. $query_2 = db_select('test', 't')
  1376. ->fields('t', array('name'))
  1377. ->condition('age', 28);
  1378. $query_1->union($query_2);
  1379. $names = $query_1->execute()->fetchCol();
  1380. // Ensure we only get 2 records.
  1381. $this->assertEqual(count($names), 2, 'UNION correctly discarded duplicates.');
  1382. $this->assertEqual($names[0], 'George', 'First query returned correct name.');
  1383. $this->assertEqual($names[1], 'Ringo', 'Second query returned correct name.');
  1384. }
  1385. /**
  1386. * Test that we can UNION ALL multiple Select queries together.
  1387. */
  1388. function testUnionAll() {
  1389. $query_1 = db_select('test', 't')
  1390. ->fields('t', array('name'))
  1391. ->condition('age', array(27, 28), 'IN');
  1392. $query_2 = db_select('test', 't')
  1393. ->fields('t', array('name'))
  1394. ->condition('age', 28);
  1395. $query_1->union($query_2, 'ALL');
  1396. $names = $query_1->execute()->fetchCol();
  1397. // Ensure we get all 3 records.
  1398. $this->assertEqual(count($names), 3, 'UNION ALL correctly preserved duplicates.');
  1399. $this->assertEqual($names[0], 'George', 'First query returned correct first name.');
  1400. $this->assertEqual($names[1], 'Ringo', 'Second query returned correct second name.');
  1401. $this->assertEqual($names[2], 'Ringo', 'Third query returned correct name.');
  1402. }
  1403. /**
  1404. * Test that random ordering of queries works.
  1405. *
  1406. * We take the approach of testing the Drupal layer only, rather than trying
  1407. * to test that the database's random number generator actually produces
  1408. * random queries (which is very difficult to do without an unacceptable risk
  1409. * of the test failing by accident).
  1410. *
  1411. * Therefore, in this test we simply run the same query twice and assert that
  1412. * the two results are reordered versions of each other (as well as of the
  1413. * same query without the random ordering). It is reasonable to assume that
  1414. * if we run the same select query twice and the results are in a different
  1415. * order each time, the only way this could happen is if we have successfully
  1416. * triggered the database's random ordering functionality.
  1417. */
  1418. function testRandomOrder() {
  1419. // Use 52 items, so the chance that this test fails by accident will be the
  1420. // same as the chance that a deck of cards will come out in the same order
  1421. // after shuffling it (in other words, nearly impossible).
  1422. $number_of_items = 52;
  1423. while (db_query("SELECT MAX(id) FROM {test}")->fetchField() < $number_of_items) {
  1424. db_insert('test')->fields(array('name' => $this->randomName()))->execute();
  1425. }
  1426. // First select the items in order and make sure we get an ordered list.
  1427. $expected_ids = range(1, $number_of_items);
  1428. $ordered_ids = db_select('test', 't')
  1429. ->fields('t', array('id'))
  1430. ->range(0, $number_of_items)
  1431. ->orderBy('id')
  1432. ->execute()
  1433. ->fetchCol();
  1434. $this->assertEqual($ordered_ids, $expected_ids, 'A query without random ordering returns IDs in the correct order.');
  1435. // Now perform the same query, but instead choose a random ordering. We
  1436. // expect this to contain a differently ordered version of the original
  1437. // result.
  1438. $randomized_ids = db_select('test', 't')
  1439. ->fields('t', array('id'))
  1440. ->range(0, $number_of_items)
  1441. ->orderRandom()
  1442. ->execute()
  1443. ->fetchCol();
  1444. $this->assertNotEqual($randomized_ids, $ordered_ids, 'A query with random ordering returns an unordered set of IDs.');
  1445. $sorted_ids = $randomized_ids;
  1446. sort($sorted_ids);
  1447. $this->assertEqual($sorted_ids, $ordered_ids, 'After sorting the random list, the result matches the original query.');
  1448. // Now perform the exact same query again, and make sure the order is
  1449. // different.
  1450. $randomized_ids_second_set = db_select('test', 't')
  1451. ->fields('t', array('id'))
  1452. ->range(0, $number_of_items)
  1453. ->orderRandom()
  1454. ->execute()
  1455. ->fetchCol();
  1456. $this->assertNotEqual($randomized_ids_second_set, $randomized_ids, 'Performing the query with random ordering a second time returns IDs in a different order.');
  1457. $sorted_ids_second_set = $randomized_ids_second_set;
  1458. sort($sorted_ids_second_set);
  1459. $this->assertEqual($sorted_ids_second_set, $sorted_ids, 'After sorting the second random list, the result matches the sorted version of the first random list.');
  1460. }
  1461. /**
  1462. * Test that aliases are renamed when duplicates.
  1463. */
  1464. function testSelectDuplicateAlias() {
  1465. $query = db_select('test', 't');
  1466. $alias1 = $query->addField('t', 'name', 'the_alias');
  1467. $alias2 = $query->addField('t', 'age', 'the_alias');
  1468. $this->assertNotIdentical($alias1, $alias2, 'Duplicate aliases are renamed.');
  1469. }
  1470. }
  1471. /**
  1472. * Test case for subselects in a dynamic SELECT query.
  1473. */
  1474. class DatabaseSelectSubqueryTestCase extends DatabaseTestCase {
  1475. public static function getInfo() {
  1476. return array(
  1477. 'name' => 'Select tests, subqueries',
  1478. 'description' => 'Test the Select query builder.',
  1479. 'group' => 'Database',
  1480. );
  1481. }
  1482. /**
  1483. * Test that we can use a subquery in a FROM clause.
  1484. */
  1485. function testFromSubquerySelect() {
  1486. // Create a subquery, which is just a normal query object.
  1487. $subquery = db_select('test_task', 'tt');
  1488. $subquery->addField('tt', 'pid', 'pid');
  1489. $subquery->addField('tt', 'task', 'task');
  1490. $subquery->condition('priority', 1);
  1491. for ($i = 0; $i < 2; $i++) {
  1492. // Create another query that joins against the virtual table resulting
  1493. // from the subquery.
  1494. $select = db_select($subquery, 'tt2');
  1495. $select->join('test', 't', 't.id=tt2.pid');
  1496. $select->addField('t', 'name');
  1497. if ($i) {
  1498. // Use a different number of conditions here to confuse the subquery
  1499. // placeholder counter, testing http://drupal.org/node/1112854.
  1500. $select->condition('name', 'John');
  1501. }
  1502. $select->condition('task', 'code');
  1503. // The resulting query should be equivalent to:
  1504. // SELECT t.name
  1505. // FROM (SELECT tt.pid AS pid, tt.task AS task FROM test_task tt WHERE priority=1) tt
  1506. // INNER JOIN test t ON t.id=tt.pid
  1507. // WHERE tt.task = 'code'
  1508. $people = $select->execute()->fetchCol();
  1509. $this->assertEqual(count($people), 1, 'Returned the correct number of rows.');
  1510. }
  1511. }
  1512. /**
  1513. * Test that we can use a subquery in a FROM clause with a limit.
  1514. */
  1515. function testFromSubquerySelectWithLimit() {
  1516. // Create a subquery, which is just a normal query object.
  1517. $subquery = db_select('test_task', 'tt');
  1518. $subquery->addField('tt', 'pid', 'pid');
  1519. $subquery->addField('tt', 'task', 'task');
  1520. $subquery->orderBy('priority', 'DESC');
  1521. $subquery->range(0, 1);
  1522. // Create another query that joins against the virtual table resulting
  1523. // from the subquery.
  1524. $select = db_select($subquery, 'tt2');
  1525. $select->join('test', 't', 't.id=tt2.pid');
  1526. $select->addField('t', 'name');
  1527. // The resulting query should be equivalent to:
  1528. // SELECT t.name
  1529. // FROM (SELECT tt.pid AS pid, tt.task AS task FROM test_task tt ORDER BY priority DESC LIMIT 1 OFFSET 0) tt
  1530. // INNER JOIN test t ON t.id=tt.pid
  1531. $people = $select->execute()->fetchCol();
  1532. $this->assertEqual(count($people), 1, 'Returned the correct number of rows.');
  1533. }
  1534. /**
  1535. * Test that we can use a subquery in a WHERE clause.
  1536. */
  1537. function testConditionSubquerySelect() {
  1538. // Create a subquery, which is just a normal query object.
  1539. $subquery = db_select('test_task', 'tt');
  1540. $subquery->addField('tt', 'pid', 'pid');
  1541. $subquery->condition('tt.priority', 1);
  1542. // Create another query that joins against the virtual table resulting
  1543. // from the subquery.
  1544. $select = db_select('test_task', 'tt2');
  1545. $select->addField('tt2', 'task');
  1546. $select->condition('tt2.pid', $subquery, 'IN');
  1547. // The resulting query should be equivalent to:
  1548. // SELECT tt2.name
  1549. // FROM test tt2
  1550. // WHERE tt2.pid IN (SELECT tt.pid AS pid FROM test_task tt WHERE tt.priority=1)
  1551. $people = $select->execute()->fetchCol();
  1552. $this->assertEqual(count($people), 5, 'Returned the correct number of rows.');
  1553. }
  1554. /**
  1555. * Test that we can use a subquery in a JOIN clause.
  1556. */
  1557. function testJoinSubquerySelect() {
  1558. // Create a subquery, which is just a normal query object.
  1559. $subquery = db_select('test_task', 'tt');
  1560. $subquery->addField('tt', 'pid', 'pid');
  1561. $subquery->condition('priority', 1);
  1562. // Create another query that joins against the virtual table resulting
  1563. // from the subquery.
  1564. $select = db_select('test', 't');
  1565. $select->join($subquery, 'tt', 't.id=tt.pid');
  1566. $select->addField('t', 'name');
  1567. // The resulting query should be equivalent to:
  1568. // SELECT t.name
  1569. // FROM test t
  1570. // INNER JOIN (SELECT tt.pid AS pid FROM test_task tt WHERE priority=1) tt ON t.id=tt.pid
  1571. $people = $select->execute()->fetchCol();
  1572. $this->assertEqual(count($people), 2, 'Returned the correct number of rows.');
  1573. }
  1574. /**
  1575. * Test EXISTS subquery conditionals on SELECT statements.
  1576. *
  1577. * We essentially select all rows from the {test} table that have matching
  1578. * rows in the {test_people} table based on the shared name column.
  1579. */
  1580. function testExistsSubquerySelect() {
  1581. // Put George into {test_people}.
  1582. db_insert('test_people')
  1583. ->fields(array(
  1584. 'name' => 'George',
  1585. 'age' => 27,
  1586. 'job' => 'Singer',
  1587. ))
  1588. ->execute();
  1589. // Base query to {test}.
  1590. $query = db_select('test', 't')
  1591. ->fields('t', array('name'));
  1592. // Subquery to {test_people}.
  1593. $subquery = db_select('test_people', 'tp')
  1594. ->fields('tp', array('name'))
  1595. ->where('tp.name = t.name');
  1596. $query->exists($subquery);
  1597. $result = $query->execute();
  1598. // Ensure that we got the right record.
  1599. $record = $result->fetch();
  1600. $this->assertEqual($record->name, 'George', 'Fetched name is correct using EXISTS query.');
  1601. }
  1602. /**
  1603. * Test NOT EXISTS subquery conditionals on SELECT statements.
  1604. *
  1605. * We essentially select all rows from the {test} table that don't have
  1606. * matching rows in the {test_people} table based on the shared name column.
  1607. */
  1608. function testNotExistsSubquerySelect() {
  1609. // Put George into {test_people}.
  1610. db_insert('test_people')
  1611. ->fields(array(
  1612. 'name' => 'George',
  1613. 'age' => 27,
  1614. 'job' => 'Singer',
  1615. ))
  1616. ->execute();
  1617. // Base query to {test}.
  1618. $query = db_select('test', 't')
  1619. ->fields('t', array('name'));
  1620. // Subquery to {test_people}.
  1621. $subquery = db_select('test_people', 'tp')
  1622. ->fields('tp', array('name'))
  1623. ->where('tp.name = t.name');
  1624. $query->notExists($subquery);
  1625. // Ensure that we got the right number of records.
  1626. $people = $query->execute()->fetchCol();
  1627. $this->assertEqual(count($people), 3, 'NOT EXISTS query returned the correct results.');
  1628. }
  1629. }
  1630. /**
  1631. * Test select with order by clauses.
  1632. */
  1633. class DatabaseSelectOrderedTestCase extends DatabaseTestCase {
  1634. public static function getInfo() {
  1635. return array(
  1636. 'name' => 'Select tests, ordered',
  1637. 'description' => 'Test the Select query builder.',
  1638. 'group' => 'Database',
  1639. );
  1640. }
  1641. /**
  1642. * Test basic order by.
  1643. */
  1644. function testSimpleSelectOrdered() {
  1645. $query = db_select('test');
  1646. $name_field = $query->addField('test', 'name');
  1647. $age_field = $query->addField('test', 'age', 'age');
  1648. $query->orderBy($age_field);
  1649. $result = $query->execute();
  1650. $num_records = 0;
  1651. $last_age = 0;
  1652. foreach ($result as $record) {
  1653. $num_records++;
  1654. $this->assertTrue($record->age >= $last_age, 'Results returned in correct order.');
  1655. $last_age = $record->age;
  1656. }
  1657. $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
  1658. }
  1659. /**
  1660. * Test multiple order by.
  1661. */
  1662. function testSimpleSelectMultiOrdered() {
  1663. $query = db_select('test');
  1664. $name_field = $query->addField('test', 'name');
  1665. $age_field = $query->addField('test', 'age', 'age');
  1666. $job_field = $query->addField('test', 'job');
  1667. $query->orderBy($job_field);
  1668. $query->orderBy($age_field);
  1669. $result = $query->execute();
  1670. $num_records = 0;
  1671. $expected = array(
  1672. array('Ringo', 28, 'Drummer'),
  1673. array('John', 25, 'Singer'),
  1674. array('George', 27, 'Singer'),
  1675. array('Paul', 26, 'Songwriter'),
  1676. );
  1677. $results = $result->fetchAll(PDO::FETCH_NUM);
  1678. foreach ($expected as $k => $record) {
  1679. $num_records++;
  1680. foreach ($record as $kk => $col) {
  1681. if ($expected[$k][$kk] != $results[$k][$kk]) {
  1682. $this->assertTrue(FALSE, 'Results returned in correct order.');
  1683. }
  1684. }
  1685. }
  1686. $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
  1687. }
  1688. /**
  1689. * Test order by descending.
  1690. */
  1691. function testSimpleSelectOrderedDesc() {
  1692. $query = db_select('test');
  1693. $name_field = $query->addField('test', 'name');
  1694. $age_field = $query->addField('test', 'age', 'age');
  1695. $query->orderBy($age_field, 'DESC');
  1696. $result = $query->execute();
  1697. $num_records = 0;
  1698. $last_age = 100000000;
  1699. foreach ($result as $record) {
  1700. $num_records++;
  1701. $this->assertTrue($record->age <= $last_age, 'Results returned in correct order.');
  1702. $last_age = $record->age;
  1703. }
  1704. $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
  1705. }
  1706. /**
  1707. * Tests that the sort direction is sanitized properly.
  1708. */
  1709. function testOrderByEscaping() {
  1710. $query = db_select('test')->orderBy('name', 'invalid direction');
  1711. $order_bys = $query->getOrderBy();
  1712. $this->assertEqual($order_bys['name'], 'ASC', 'Invalid order by direction is converted to ASC.');
  1713. }
  1714. }
  1715. /**
  1716. * Test more complex select statements.
  1717. */
  1718. class DatabaseSelectComplexTestCase extends DatabaseTestCase {
  1719. public static function getInfo() {
  1720. return array(
  1721. 'name' => 'Select tests, complex',
  1722. 'description' => 'Test the Select query builder with more complex queries.',
  1723. 'group' => 'Database',
  1724. );
  1725. }
  1726. /**
  1727. * Test simple JOIN statements.
  1728. */
  1729. function testDefaultJoin() {
  1730. $query = db_select('test_task', 't');
  1731. $people_alias = $query->join('test', 'p', 't.pid = p.id');
  1732. $name_field = $query->addField($people_alias, 'name', 'name');
  1733. $task_field = $query->addField('t', 'task', 'task');
  1734. $priority_field = $query->addField('t', 'priority', 'priority');
  1735. $query->orderBy($priority_field);
  1736. $result = $query->execute();
  1737. $num_records = 0;
  1738. $last_priority = 0;
  1739. foreach ($result as $record) {
  1740. $num_records++;
  1741. $this->assertTrue($record->$priority_field >= $last_priority, 'Results returned in correct order.');
  1742. $this->assertNotEqual($record->$name_field, 'Ringo', 'Taskless person not selected.');
  1743. $last_priority = $record->$priority_field;
  1744. }
  1745. $this->assertEqual($num_records, 7, 'Returned the correct number of rows.');
  1746. }
  1747. /**
  1748. * Test LEFT OUTER joins.
  1749. */
  1750. function testLeftOuterJoin() {
  1751. $query = db_select('test', 'p');
  1752. $people_alias = $query->leftJoin('test_task', 't', 't.pid = p.id');
  1753. $name_field = $query->addField('p', 'name', 'name');
  1754. $task_field = $query->addField($people_alias, 'task', 'task');
  1755. $priority_field = $query->addField($people_alias, 'priority', 'priority');
  1756. $query->orderBy($name_field);
  1757. $result = $query->execute();
  1758. $num_records = 0;
  1759. $last_name = 0;
  1760. foreach ($result as $record) {
  1761. $num_records++;
  1762. $this->assertTrue(strcmp($record->$name_field, $last_name) >= 0, 'Results returned in correct order.');
  1763. $last_priority = $record->$name_field;
  1764. }
  1765. $this->assertEqual($num_records, 8, 'Returned the correct number of rows.');
  1766. }
  1767. /**
  1768. * Test GROUP BY clauses.
  1769. */
  1770. function testGroupBy() {
  1771. $query = db_select('test_task', 't');
  1772. $count_field = $query->addExpression('COUNT(task)', 'num');
  1773. $task_field = $query->addField('t', 'task');
  1774. $query->orderBy($count_field);
  1775. $query->groupBy($task_field);
  1776. $result = $query->execute();
  1777. $num_records = 0;
  1778. $last_count = 0;
  1779. $records = array();
  1780. foreach ($result as $record) {
  1781. $num_records++;
  1782. $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
  1783. $last_count = $record->$count_field;
  1784. $records[$record->$task_field] = $record->$count_field;
  1785. }
  1786. $correct_results = array(
  1787. 'eat' => 1,
  1788. 'sleep' => 2,
  1789. 'code' => 1,
  1790. 'found new band' => 1,
  1791. 'perform at superbowl' => 1,
  1792. );
  1793. foreach ($correct_results as $task => $count) {
  1794. $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", array('@task' => $task)));
  1795. }
  1796. $this->assertEqual($num_records, 6, 'Returned the correct number of total rows.');
  1797. }
  1798. /**
  1799. * Test GROUP BY and HAVING clauses together.
  1800. */
  1801. function testGroupByAndHaving() {
  1802. $query = db_select('test_task', 't');
  1803. $count_field = $query->addExpression('COUNT(task)', 'num');
  1804. $task_field = $query->addField('t', 'task');
  1805. $query->orderBy($count_field);
  1806. $query->groupBy($task_field);
  1807. $query->having('COUNT(task) >= 2');
  1808. $result = $query->execute();
  1809. $num_records = 0;
  1810. $last_count = 0;
  1811. $records = array();
  1812. foreach ($result as $record) {
  1813. $num_records++;
  1814. $this->assertTrue($record->$count_field >= 2, 'Record has the minimum count.');
  1815. $this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
  1816. $last_count = $record->$count_field;
  1817. $records[$record->$task_field] = $record->$count_field;
  1818. }
  1819. $correct_results = array(
  1820. 'sleep' => 2,
  1821. );
  1822. foreach ($correct_results as $task => $count) {
  1823. $this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", array('@task' => $task)));
  1824. }
  1825. $this->assertEqual($num_records, 1, 'Returned the correct number of total rows.');
  1826. }
  1827. /**
  1828. * Test range queries. The SQL clause varies with the database.
  1829. */
  1830. function testRange() {
  1831. $query = db_select('test');
  1832. $name_field = $query->addField('test', 'name');
  1833. $age_field = $query->addField('test', 'age', 'age');
  1834. $query->range(0, 2);
  1835. $result = $query->execute();
  1836. $num_records = 0;
  1837. foreach ($result as $record) {
  1838. $num_records++;
  1839. }
  1840. $this->assertEqual($num_records, 2, 'Returned the correct number of rows.');
  1841. }
  1842. /**
  1843. * Test distinct queries.
  1844. */
  1845. function testDistinct() {
  1846. $query = db_select('test_task');
  1847. $task_field = $query->addField('test_task', 'task');
  1848. $query->distinct();
  1849. $result = $query->execute();
  1850. $num_records = 0;
  1851. foreach ($result as $record) {
  1852. $num_records++;
  1853. }
  1854. $this->assertEqual($num_records, 6, 'Returned the correct number of rows.');
  1855. }
  1856. /**
  1857. * Test that we can generate a count query from a built query.
  1858. */
  1859. function testCountQuery() {
  1860. $query = db_select('test');
  1861. $name_field = $query->addField('test', 'name');
  1862. $age_field = $query->addField('test', 'age', 'age');
  1863. $query->orderBy('name');
  1864. $count = $query->countQuery()->execute()->fetchField();
  1865. $this->assertEqual($count, 4, 'Counted the correct number of records.');
  1866. // Now make sure we didn't break the original query! We should still have
  1867. // all of the fields we asked for.
  1868. $record = $query->execute()->fetch();
  1869. $this->assertEqual($record->$name_field, 'George', 'Correct data retrieved.');
  1870. $this->assertEqual($record->$age_field, 27, 'Correct data retrieved.');
  1871. }
  1872. function testHavingCountQuery() {
  1873. $query = db_select('test')
  1874. ->extend('PagerDefault')
  1875. ->groupBy('age')
  1876. ->having('age + 1 > 0');
  1877. $query->addField('test', 'age');
  1878. $query->addExpression('age + 1');
  1879. $count = count($query->execute()->fetchCol());
  1880. $this->assertEqual($count, 4, 'Counted the correct number of records.');
  1881. }
  1882. /**
  1883. * Test that countQuery properly removes 'all_fields' statements and
  1884. * ordering clauses.
  1885. */
  1886. function testCountQueryRemovals() {
  1887. $query = db_select('test');
  1888. $query->fields('test');
  1889. $query->orderBy('name');
  1890. $count = $query->countQuery();
  1891. // Check that the 'all_fields' statement is handled properly.
  1892. $tables = $query->getTables();
  1893. $this->assertEqual($tables['test']['all_fields'], 1, 'Query correctly sets \'all_fields\' statement.');
  1894. $tables = $count->getTables();
  1895. $this->assertFalse(isset($tables['test']['all_fields']), 'Count query correctly unsets \'all_fields\' statement.');
  1896. // Check that the ordering clause is handled properly.
  1897. $orderby = $query->getOrderBy();
  1898. $this->assertEqual($orderby['name'], 'ASC', 'Query correctly sets ordering clause.');
  1899. $orderby = $count->getOrderBy();
  1900. $this->assertFalse(isset($orderby['name']), 'Count query correctly unsets ordering caluse.');
  1901. // Make sure that the count query works.
  1902. $count = $count->execute()->fetchField();
  1903. $this->assertEqual($count, 4, 'Counted the correct number of records.');
  1904. }
  1905. /**
  1906. * Test that countQuery properly removes fields and expressions.
  1907. */
  1908. function testCountQueryFieldRemovals() {
  1909. // countQuery should remove all fields and expressions, so this can be
  1910. // tested by adding a non-existent field and expression: if it ends
  1911. // up in the query, an error will be thrown. If not, it will return the
  1912. // number of records, which in this case happens to be 4 (there are four
  1913. // records in the {test} table).
  1914. $query = db_select('test');
  1915. $query->fields('test', array('fail'));
  1916. $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed fields');
  1917. $query = db_select('test');
  1918. $query->addExpression('fail');
  1919. $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed expressions');
  1920. }
  1921. /**
  1922. * Test that we can generate a count query from a query with distinct.
  1923. */
  1924. function testCountQueryDistinct() {
  1925. $query = db_select('test_task');
  1926. $task_field = $query->addField('test_task', 'task');
  1927. $query->distinct();
  1928. $count = $query->countQuery()->execute()->fetchField();
  1929. $this->assertEqual($count, 6, 'Counted the correct number of records.');
  1930. }
  1931. /**
  1932. * Test that we can generate a count query from a query with GROUP BY.
  1933. */
  1934. function testCountQueryGroupBy() {
  1935. $query = db_select('test_task');
  1936. $pid_field = $query->addField('test_task', 'pid');
  1937. $query->groupBy('pid');
  1938. $count = $query->countQuery()->execute()->fetchField();
  1939. $this->assertEqual($count, 3, 'Counted the correct number of records.');
  1940. // Use a column alias as, without one, the query can succeed for the wrong
  1941. // reason.
  1942. $query = db_select('test_task');
  1943. $pid_field = $query->addField('test_task', 'pid', 'pid_alias');
  1944. $query->addExpression('COUNT(test_task.task)', 'count');
  1945. $query->groupBy('pid_alias');
  1946. $query->orderBy('pid_alias', 'asc');
  1947. $count = $query->countQuery()->execute()->fetchField();
  1948. $this->assertEqual($count, 3, 'Counted the correct number of records.');
  1949. }
  1950. /**
  1951. * Confirm that we can properly nest conditional clauses.
  1952. */
  1953. function testNestedConditions() {
  1954. // This query should translate to:
  1955. // "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)"
  1956. // That should find only one record. Yes it's a non-optimal way of writing
  1957. // that query but that's not the point!
  1958. $query = db_select('test');
  1959. $query->addField('test', 'job');
  1960. $query->condition('name', 'Paul');
  1961. $query->condition(db_or()->condition('age', 26)->condition('age', 27));
  1962. $job = $query->execute()->fetchField();
  1963. $this->assertEqual($job, 'Songwriter', 'Correct data retrieved.');
  1964. }
  1965. /**
  1966. * Confirm we can join on a single table twice with a dynamic alias.
  1967. */
  1968. function testJoinTwice() {
  1969. $query = db_select('test')->fields('test');
  1970. $alias = $query->join('test', 'test', 'test.job = %alias.job');
  1971. $query->addField($alias, 'name', 'othername');
  1972. $query->addField($alias, 'job', 'otherjob');
  1973. $query->where("$alias.name <> test.name");
  1974. $crowded_job = $query->execute()->fetch();
  1975. $this->assertEqual($crowded_job->job, $crowded_job->otherjob, 'Correctly joined same table twice.');
  1976. $this->assertNotEqual($crowded_job->name, $crowded_job->othername, 'Correctly joined same table twice.');
  1977. }
  1978. }
  1979. /**
  1980. * Test more complex select statements, part 2.
  1981. */
  1982. class DatabaseSelectComplexTestCase2 extends DatabaseTestCase {
  1983. public static function getInfo() {
  1984. return array(
  1985. 'name' => 'Select tests, complex 2',
  1986. 'description' => 'Test the Select query builder with even more complex queries.',
  1987. 'group' => 'Database',
  1988. );
  1989. }
  1990. function setUp() {
  1991. DrupalWebTestCase::setUp('database_test', 'node_access_test');
  1992. $schema['test'] = drupal_get_schema('test');
  1993. $schema['test_people'] = drupal_get_schema('test_people');
  1994. $schema['test_one_blob'] = drupal_get_schema('test_one_blob');
  1995. $schema['test_two_blobs'] = drupal_get_schema('test_two_blobs');
  1996. $schema['test_task'] = drupal_get_schema('test_task');
  1997. $this->installTables($schema);
  1998. $this->addSampleData();
  1999. }
  2000. /**
  2001. * Test that we can join on a query.
  2002. */
  2003. function testJoinSubquery() {
  2004. $acct = $this->drupalCreateUser(array('access content'));
  2005. $this->drupalLogin($acct);
  2006. $query = db_select('test_task', 'tt', array('target' => 'slave'));
  2007. $query->addExpression('tt.pid + 1', 'abc');
  2008. $query->condition('priority', 1, '>');
  2009. $query->condition('priority', 100, '<');
  2010. $subquery = db_select('test', 'tp');
  2011. $subquery->join('test_one_blob', 'tpb', 'tp.id = tpb.id');
  2012. $subquery->join('node', 'n', 'tp.id = n.nid');
  2013. $subquery->addTag('node_access');
  2014. $subquery->addMetaData('account', $acct);
  2015. $subquery->addField('tp', 'id');
  2016. $subquery->condition('age', 5, '>');
  2017. $subquery->condition('age', 500, '<');
  2018. $query->leftJoin($subquery, 'sq', 'tt.pid = sq.id');
  2019. $query->join('test_one_blob', 'tb3', 'tt.pid = tb3.id');
  2020. // Construct the query string.
  2021. // This is the same sequence that SelectQuery::execute() goes through.
  2022. $query->preExecute();
  2023. $query->getArguments();
  2024. $str = (string) $query;
  2025. // Verify that the string only has one copy of condition placeholder 0.
  2026. $pos = strpos($str, 'db_condition_placeholder_0', 0);
  2027. $pos2 = strpos($str, 'db_condition_placeholder_0', $pos + 1);
  2028. $this->assertFalse($pos2, 'Condition placeholder is not repeated.');
  2029. }
  2030. }
  2031. class DatabaseSelectPagerDefaultTestCase extends DatabaseTestCase {
  2032. public static function getInfo() {
  2033. return array(
  2034. 'name' => 'Pager query tests',
  2035. 'description' => 'Test the pager query extender.',
  2036. 'group' => 'Database',
  2037. );
  2038. }
  2039. /**
  2040. * Confirm that a pager query returns the correct results.
  2041. *
  2042. * Note that we have to make an HTTP request to a test page handler
  2043. * because the pager depends on GET parameters.
  2044. */
  2045. function testEvenPagerQuery() {
  2046. // To keep the test from being too brittle, we determine up front
  2047. // what the page count should be dynamically, and pass the control
  2048. // information forward to the actual query on the other side of the
  2049. // HTTP request.
  2050. $limit = 2;
  2051. $count = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  2052. $correct_number = $limit;
  2053. $num_pages = floor($count / $limit);
  2054. // If there is no remainder from rounding, subtract 1 since we index from 0.
  2055. if (!($num_pages * $limit < $count)) {
  2056. $num_pages--;
  2057. }
  2058. for ($page = 0; $page <= $num_pages; ++$page) {
  2059. $this->drupalGet('database_test/pager_query_even/' . $limit, array('query' => array('page' => $page)));
  2060. $data = json_decode($this->drupalGetContent());
  2061. if ($page == $num_pages) {
  2062. $correct_number = $count - ($limit * $page);
  2063. }
  2064. $this->assertEqual(count($data->names), $correct_number, format_string('Correct number of records returned by pager: @number', array('@number' => $correct_number)));
  2065. }
  2066. }
  2067. /**
  2068. * Confirm that a pager query returns the correct results.
  2069. *
  2070. * Note that we have to make an HTTP request to a test page handler
  2071. * because the pager depends on GET parameters.
  2072. */
  2073. function testOddPagerQuery() {
  2074. // To keep the test from being too brittle, we determine up front
  2075. // what the page count should be dynamically, and pass the control
  2076. // information forward to the actual query on the other side of the
  2077. // HTTP request.
  2078. $limit = 2;
  2079. $count = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
  2080. $correct_number = $limit;
  2081. $num_pages = floor($count / $limit);
  2082. // If there is no remainder from rounding, subtract 1 since we index from 0.
  2083. if (!($num_pages * $limit < $count)) {
  2084. $num_pages--;
  2085. }
  2086. for ($page = 0; $page <= $num_pages; ++$page) {
  2087. $this->drupalGet('database_test/pager_query_odd/' . $limit, array('query' => array('page' => $page)));
  2088. $data = json_decode($this->drupalGetContent());
  2089. if ($page == $num_pages) {
  2090. $correct_number = $count - ($limit * $page);
  2091. }
  2092. $this->assertEqual(count($data->names), $correct_number, format_string('Correct number of records returned by pager: @number', array('@number' => $correct_number)));
  2093. }
  2094. }
  2095. /**
  2096. * Confirm that a pager query with inner pager query returns valid results.
  2097. *
  2098. * This is a regression test for #467984.
  2099. */
  2100. function testInnerPagerQuery() {
  2101. $query = db_select('test', 't')->extend('PagerDefault');
  2102. $query
  2103. ->fields('t', array('age'))
  2104. ->orderBy('age')
  2105. ->limit(5);
  2106. $outer_query = db_select($query);
  2107. $outer_query->addField('subquery', 'age');
  2108. $ages = $outer_query
  2109. ->execute()
  2110. ->fetchCol();
  2111. $this->assertEqual($ages, array(25, 26, 27, 28), 'Inner pager query returned the correct ages.');
  2112. }
  2113. /**
  2114. * Confirm that a paging query with a having expression returns valid results.
  2115. *
  2116. * This is a regression test for #467984.
  2117. */
  2118. function testHavingPagerQuery() {
  2119. $query = db_select('test', 't')->extend('PagerDefault');
  2120. $query
  2121. ->fields('t', array('name'))
  2122. ->orderBy('name')
  2123. ->groupBy('name')
  2124. ->having('MAX(age) > :count', array(':count' => 26))
  2125. ->limit(5);
  2126. $ages = $query
  2127. ->execute()
  2128. ->fetchCol();
  2129. $this->assertEqual($ages, array('George', 'Ringo'), 'Pager query with having expression returned the correct ages.');
  2130. }
  2131. /**
  2132. * Confirm that every pager gets a valid non-overlaping element ID.
  2133. */
  2134. function testElementNumbers() {
  2135. $_GET['page'] = '3, 2, 1, 0';
  2136. $name = db_select('test', 't')->extend('PagerDefault')
  2137. ->element(2)
  2138. ->fields('t', array('name'))
  2139. ->orderBy('age')
  2140. ->limit(1)
  2141. ->execute()
  2142. ->fetchField();
  2143. $this->assertEqual($name, 'Paul', 'Pager query #1 with a specified element ID returned the correct results.');
  2144. // Setting an element smaller than the previous one
  2145. // should not overwrite the pager $maxElement with a smaller value.
  2146. $name = db_select('test', 't')->extend('PagerDefault')
  2147. ->element(1)
  2148. ->fields('t', array('name'))
  2149. ->orderBy('age')
  2150. ->limit(1)
  2151. ->execute()
  2152. ->fetchField();
  2153. $this->assertEqual($name, 'George', 'Pager query #2 with a specified element ID returned the correct results.');
  2154. $name = db_select('test', 't')->extend('PagerDefault')
  2155. ->fields('t', array('name'))
  2156. ->orderBy('age')
  2157. ->limit(1)
  2158. ->execute()
  2159. ->fetchField();
  2160. $this->assertEqual($name, 'John', 'Pager query #3 with a generated element ID returned the correct results.');
  2161. unset($_GET['page']);
  2162. }
  2163. }
  2164. class DatabaseSelectTableSortDefaultTestCase extends DatabaseTestCase {
  2165. public static function getInfo() {
  2166. return array(
  2167. 'name' => 'Tablesort query tests',
  2168. 'description' => 'Test the tablesort query extender.',
  2169. 'group' => 'Database',
  2170. );
  2171. }
  2172. /**
  2173. * Confirm that a tablesort query returns the correct results.
  2174. *
  2175. * Note that we have to make an HTTP request to a test page handler
  2176. * because the pager depends on GET parameters.
  2177. */
  2178. function testTableSortQuery() {
  2179. $sorts = array(
  2180. array('field' => t('Task ID'), 'sort' => 'desc', 'first' => 'perform at superbowl', 'last' => 'eat'),
  2181. array('field' => t('Task ID'), 'sort' => 'asc', 'first' => 'eat', 'last' => 'perform at superbowl'),
  2182. array('field' => t('Task'), 'sort' => 'asc', 'first' => 'code', 'last' => 'sleep'),
  2183. array('field' => t('Task'), 'sort' => 'desc', 'first' => 'sleep', 'last' => 'code'),
  2184. // more elements here
  2185. );
  2186. foreach ($sorts as $sort) {
  2187. $this->drupalGet('database_test/tablesort/', array('query' => array('order' => $sort['field'], 'sort' => $sort['sort'])));
  2188. $data = json_decode($this->drupalGetContent());
  2189. $first = array_shift($data->tasks);
  2190. $last = array_pop($data->tasks);
  2191. $this->assertEqual($first->task, $sort['first'], 'Items appear in the correct order.');
  2192. $this->assertEqual($last->task, $sort['last'], 'Items appear in the correct order.');
  2193. }
  2194. }
  2195. /**
  2196. * Confirm that if a tablesort's orderByHeader is called before another orderBy, that the header happens first.
  2197. *
  2198. */
  2199. function testTableSortQueryFirst() {
  2200. $sorts = array(
  2201. array('field' => t('Task ID'), 'sort' => 'desc', 'first' => 'perform at superbowl', 'last' => 'eat'),
  2202. array('field' => t('Task ID'), 'sort' => 'asc', 'first' => 'eat', 'last' => 'perform at superbowl'),
  2203. array('field' => t('Task'), 'sort' => 'asc', 'first' => 'code', 'last' => 'sleep'),
  2204. array('field' => t('Task'), 'sort' => 'desc', 'first' => 'sleep', 'last' => 'code'),
  2205. // more elements here
  2206. );
  2207. foreach ($sorts as $sort) {
  2208. $this->drupalGet('database_test/tablesort_first/', array('query' => array('order' => $sort['field'], 'sort' => $sort['sort'])));
  2209. $data = json_decode($this->drupalGetContent());
  2210. $first = array_shift($data->tasks);
  2211. $last = array_pop($data->tasks);
  2212. $this->assertEqual($first->task, $sort['first'], format_string('Items appear in the correct order sorting by @field @sort.', array('@field' => $sort['field'], '@sort' => $sort['sort'])));
  2213. $this->assertEqual($last->task, $sort['last'], format_string('Items appear in the correct order sorting by @field @sort.', array('@field' => $sort['field'], '@sort' => $sort['sort'])));
  2214. }
  2215. }
  2216. /**
  2217. * Confirm that if a sort is not set in a tableselect form there is no error thrown when using the default.
  2218. */
  2219. function testTableSortDefaultSort() {
  2220. $this->drupalGet('database_test/tablesort_default_sort');
  2221. // Any PHP errors or notices thrown would trigger a simpletest exception, so
  2222. // no additional assertions are needed.
  2223. }
  2224. }
  2225. /**
  2226. * Select tagging tests.
  2227. *
  2228. * Tags are a way to flag queries for alter hooks so they know
  2229. * what type of query it is, such as "node_access".
  2230. */
  2231. class DatabaseTaggingTestCase extends DatabaseTestCase {
  2232. public static function getInfo() {
  2233. return array(
  2234. 'name' => 'Query tagging tests',
  2235. 'description' => 'Test the tagging capabilities of the Select builder.',
  2236. 'group' => 'Database',
  2237. );
  2238. }
  2239. /**
  2240. * Confirm that a query has a "tag" added to it.
  2241. */
  2242. function testHasTag() {
  2243. $query = db_select('test');
  2244. $query->addField('test', 'name');
  2245. $query->addField('test', 'age', 'age');
  2246. $query->addTag('test');
  2247. $this->assertTrue($query->hasTag('test'), 'hasTag() returned true.');
  2248. $this->assertFalse($query->hasTag('other'), 'hasTag() returned false.');
  2249. }
  2250. /**
  2251. * Test query tagging "has all of these tags" functionality.
  2252. */
  2253. function testHasAllTags() {
  2254. $query = db_select('test');
  2255. $query->addField('test', 'name');
  2256. $query->addField('test', 'age', 'age');
  2257. $query->addTag('test');
  2258. $query->addTag('other');
  2259. $this->assertTrue($query->hasAllTags('test', 'other'), 'hasAllTags() returned true.');
  2260. $this->assertFalse($query->hasAllTags('test', 'stuff'), 'hasAllTags() returned false.');
  2261. }
  2262. /**
  2263. * Test query tagging "has at least one of these tags" functionality.
  2264. */
  2265. function testHasAnyTag() {
  2266. $query = db_select('test');
  2267. $query->addField('test', 'name');
  2268. $query->addField('test', 'age', 'age');
  2269. $query->addTag('test');
  2270. $this->assertTrue($query->hasAnyTag('test', 'other'), 'hasAnyTag() returned true.');
  2271. $this->assertFalse($query->hasAnyTag('other', 'stuff'), 'hasAnyTag() returned false.');
  2272. }
  2273. /**
  2274. * Confirm that an extended query has a "tag" added to it.
  2275. */
  2276. function testExtenderHasTag() {
  2277. $query = db_select('test')
  2278. ->extend('SelectQueryExtender');
  2279. $query->addField('test', 'name');
  2280. $query->addField('test', 'age', 'age');
  2281. $query->addTag('test');
  2282. $this->assertTrue($query->hasTag('test'), 'hasTag() returned true.');
  2283. $this->assertFalse($query->hasTag('other'), 'hasTag() returned false.');
  2284. }
  2285. /**
  2286. * Test extended query tagging "has all of these tags" functionality.
  2287. */
  2288. function testExtenderHasAllTags() {
  2289. $query = db_select('test')
  2290. ->extend('SelectQueryExtender');
  2291. $query->addField('test', 'name');
  2292. $query->addField('test', 'age', 'age');
  2293. $query->addTag('test');
  2294. $query->addTag('other');
  2295. $this->assertTrue($query->hasAllTags('test', 'other'), 'hasAllTags() returned true.');
  2296. $this->assertFalse($query->hasAllTags('test', 'stuff'), 'hasAllTags() returned false.');
  2297. }
  2298. /**
  2299. * Test extended query tagging "has at least one of these tags" functionality.
  2300. */
  2301. function testExtenderHasAnyTag() {
  2302. $query = db_select('test')
  2303. ->extend('SelectQueryExtender');
  2304. $query->addField('test', 'name');
  2305. $query->addField('test', 'age', 'age');
  2306. $query->addTag('test');
  2307. $this->assertTrue($query->hasAnyTag('test', 'other'), 'hasAnyTag() returned true.');
  2308. $this->assertFalse($query->hasAnyTag('other', 'stuff'), 'hasAnyTag() returned false.');
  2309. }
  2310. /**
  2311. * Test that we can attach meta data to a query object.
  2312. *
  2313. * This is how we pass additional context to alter hooks.
  2314. */
  2315. function testMetaData() {
  2316. $query = db_select('test');
  2317. $query->addField('test', 'name');
  2318. $query->addField('test', 'age', 'age');
  2319. $data = array(
  2320. 'a' => 'A',
  2321. 'b' => 'B',
  2322. );
  2323. $query->addMetaData('test', $data);
  2324. $return = $query->getMetaData('test');
  2325. $this->assertEqual($data, $return, 'Corect metadata returned.');
  2326. $return = $query->getMetaData('nothere');
  2327. $this->assertNull($return, 'Non-existent key returned NULL.');
  2328. }
  2329. }
  2330. /**
  2331. * Select alter tests.
  2332. *
  2333. * @see database_test_query_alter()
  2334. */
  2335. class DatabaseAlterTestCase extends DatabaseTestCase {
  2336. public static function getInfo() {
  2337. return array(
  2338. 'name' => 'Query altering tests',
  2339. 'description' => 'Test the hook_query_alter capabilities of the Select builder.',
  2340. 'group' => 'Database',
  2341. );
  2342. }
  2343. /**
  2344. * Test that we can do basic alters.
  2345. */
  2346. function testSimpleAlter() {
  2347. $query = db_select('test');
  2348. $query->addField('test', 'name');
  2349. $query->addField('test', 'age', 'age');
  2350. $query->addTag('database_test_alter_add_range');
  2351. $result = $query->execute();
  2352. $num_records = 0;
  2353. foreach ($result as $record) {
  2354. $num_records++;
  2355. }
  2356. $this->assertEqual($num_records, 2, 'Returned the correct number of rows.');
  2357. }
  2358. /**
  2359. * Test that we can alter the joins on a query.
  2360. */
  2361. function testAlterWithJoin() {
  2362. $query = db_select('test_task');
  2363. $tid_field = $query->addField('test_task', 'tid');
  2364. $task_field = $query->addField('test_task', 'task');
  2365. $query->orderBy($task_field);
  2366. $query->addTag('database_test_alter_add_join');
  2367. $result = $query->execute();
  2368. $records = $result->fetchAll();
  2369. $this->assertEqual(count($records), 2, 'Returned the correct number of rows.');
  2370. $this->assertEqual($records[0]->name, 'George', 'Correct data retrieved.');
  2371. $this->assertEqual($records[0]->$tid_field, 4, 'Correct data retrieved.');
  2372. $this->assertEqual($records[0]->$task_field, 'sing', 'Correct data retrieved.');
  2373. $this->assertEqual($records[1]->name, 'George', 'Correct data retrieved.');
  2374. $this->assertEqual($records[1]->$tid_field, 5, 'Correct data retrieved.');
  2375. $this->assertEqual($records[1]->$task_field, 'sleep', 'Correct data retrieved.');
  2376. }
  2377. /**
  2378. * Test that we can alter a query's conditionals.
  2379. */
  2380. function testAlterChangeConditional() {
  2381. $query = db_select('test_task');
  2382. $tid_field = $query->addField('test_task', 'tid');
  2383. $pid_field = $query->addField('test_task', 'pid');
  2384. $task_field = $query->addField('test_task', 'task');
  2385. $people_alias = $query->join('test', 'people', "test_task.pid = people.id");
  2386. $name_field = $query->addField($people_alias, 'name', 'name');
  2387. $query->condition('test_task.tid', '1');
  2388. $query->orderBy($tid_field);
  2389. $query->addTag('database_test_alter_change_conditional');
  2390. $result = $query->execute();
  2391. $records = $result->fetchAll();
  2392. $this->assertEqual(count($records), 1, 'Returned the correct number of rows.');
  2393. $this->assertEqual($records[0]->$name_field, 'John', 'Correct data retrieved.');
  2394. $this->assertEqual($records[0]->$tid_field, 2, 'Correct data retrieved.');
  2395. $this->assertEqual($records[0]->$pid_field, 1, 'Correct data retrieved.');
  2396. $this->assertEqual($records[0]->$task_field, 'sleep', 'Correct data retrieved.');
  2397. }
  2398. /**
  2399. * Test that we can alter the fields of a query.
  2400. */
  2401. function testAlterChangeFields() {
  2402. $query = db_select('test');
  2403. $name_field = $query->addField('test', 'name');
  2404. $age_field = $query->addField('test', 'age', 'age');
  2405. $query->orderBy('name');
  2406. $query->addTag('database_test_alter_change_fields');
  2407. $record = $query->execute()->fetch();
  2408. $this->assertEqual($record->$name_field, 'George', 'Correct data retrieved.');
  2409. $this->assertFalse(isset($record->$age_field), 'Age field not found, as intended.');
  2410. }
  2411. /**
  2412. * Test that we can alter expressions in the query.
  2413. */
  2414. function testAlterExpression() {
  2415. $query = db_select('test');
  2416. $name_field = $query->addField('test', 'name');
  2417. $age_field = $query->addExpression("age*2", 'double_age');
  2418. $query->condition('age', 27);
  2419. $query->addTag('database_test_alter_change_expressions');
  2420. $result = $query->execute();
  2421. // Ensure that we got the right record.
  2422. $record = $result->fetch();
  2423. $this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
  2424. $this->assertEqual($record->$age_field, 27*3, 'Fetched age expression is correct.');
  2425. }
  2426. /**
  2427. * Test that we can remove a range() value from a query. This also tests hook_query_TAG_alter().
  2428. */
  2429. function testAlterRemoveRange() {
  2430. $query = db_select('test');
  2431. $query->addField('test', 'name');
  2432. $query->addField('test', 'age', 'age');
  2433. $query->range(0, 2);
  2434. $query->addTag('database_test_alter_remove_range');
  2435. $num_records = count($query->execute()->fetchAll());
  2436. $this->assertEqual($num_records, 4, 'Returned the correct number of rows.');
  2437. }
  2438. /**
  2439. * Test that we can do basic alters on subqueries.
  2440. */
  2441. function testSimpleAlterSubquery() {
  2442. // Create a sub-query with an alter tag.
  2443. $subquery = db_select('test', 'p');
  2444. $subquery->addField('p', 'name');
  2445. $subquery->addField('p', 'id');
  2446. // Pick out George.
  2447. $subquery->condition('age', 27);
  2448. $subquery->addExpression("age*2", 'double_age');
  2449. // This query alter should change it to age * 3.
  2450. $subquery->addTag('database_test_alter_change_expressions');
  2451. // Create a main query and join to sub-query.
  2452. $query = db_select('test_task', 'tt');
  2453. $query->join($subquery, 'pq', 'pq.id = tt.pid');
  2454. $age_field = $query->addField('pq', 'double_age');
  2455. $name_field = $query->addField('pq', 'name');
  2456. $record = $query->execute()->fetch();
  2457. $this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
  2458. $this->assertEqual($record->$age_field, 27*3, 'Fetched age expression is correct.');
  2459. }
  2460. }
  2461. /**
  2462. * Regression tests.
  2463. */
  2464. class DatabaseRegressionTestCase extends DatabaseTestCase {
  2465. public static function getInfo() {
  2466. return array(
  2467. 'name' => 'Regression tests',
  2468. 'description' => 'Regression tests cases for the database layer.',
  2469. 'group' => 'Database',
  2470. );
  2471. }
  2472. /**
  2473. * Regression test for #310447.
  2474. *
  2475. * Tries to insert non-ascii UTF-8 data in a database column and checks
  2476. * if its stored properly.
  2477. */
  2478. function testRegression_310447() {
  2479. // That's a 255 character UTF-8 string.
  2480. $name = str_repeat("é", 255);
  2481. db_insert('test')
  2482. ->fields(array(
  2483. 'name' => $name,
  2484. 'age' => 20,
  2485. 'job' => 'Dancer',
  2486. ))->execute();
  2487. $from_database = db_query('SELECT name FROM {test} WHERE name = :name', array(':name' => $name))->fetchField();
  2488. $this->assertIdentical($name, $from_database, "The database handles UTF-8 characters cleanly.");
  2489. }
  2490. /**
  2491. * Test the db_table_exists() function.
  2492. */
  2493. function testDBTableExists() {
  2494. $this->assertIdentical(TRUE, db_table_exists('node'), 'Returns true for existent table.');
  2495. $this->assertIdentical(FALSE, db_table_exists('nosuchtable'), 'Returns false for nonexistent table.');
  2496. }
  2497. /**
  2498. * Test the db_field_exists() function.
  2499. */
  2500. function testDBFieldExists() {
  2501. $this->assertIdentical(TRUE, db_field_exists('node', 'nid'), 'Returns true for existent column.');
  2502. $this->assertIdentical(FALSE, db_field_exists('node', 'nosuchcolumn'), 'Returns false for nonexistent column.');
  2503. }
  2504. /**
  2505. * Test the db_index_exists() function.
  2506. */
  2507. function testDBIndexExists() {
  2508. $this->assertIdentical(TRUE, db_index_exists('node', 'node_created'), 'Returns true for existent index.');
  2509. $this->assertIdentical(FALSE, db_index_exists('node', 'nosuchindex'), 'Returns false for nonexistent index.');
  2510. }
  2511. }
  2512. /**
  2513. * Query logging tests.
  2514. */
  2515. class DatabaseLoggingTestCase extends DatabaseTestCase {
  2516. public static function getInfo() {
  2517. return array(
  2518. 'name' => 'Query logging',
  2519. 'description' => 'Test the query logging facility.',
  2520. 'group' => 'Database',
  2521. );
  2522. }
  2523. /**
  2524. * Test that we can log the existence of a query.
  2525. */
  2526. function testEnableLogging() {
  2527. $log = Database::startLog('testing');
  2528. db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
  2529. db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchCol();
  2530. // Trigger a call that does not have file in the backtrace.
  2531. call_user_func_array('db_query', array('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo')))->fetchCol();
  2532. $queries = Database::getLog('testing', 'default');
  2533. $this->assertEqual(count($queries), 3, 'Correct number of queries recorded.');
  2534. foreach ($queries as $query) {
  2535. $this->assertEqual($query['caller']['function'], __FUNCTION__, 'Correct function in query log.');
  2536. }
  2537. }
  2538. /**
  2539. * Test that we can run two logs in parallel.
  2540. */
  2541. function testEnableMultiLogging() {
  2542. Database::startLog('testing1');
  2543. db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
  2544. Database::startLog('testing2');
  2545. db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchCol();
  2546. $queries1 = Database::getLog('testing1');
  2547. $queries2 = Database::getLog('testing2');
  2548. $this->assertEqual(count($queries1), 2, 'Correct number of queries recorded for log 1.');
  2549. $this->assertEqual(count($queries2), 1, 'Correct number of queries recorded for log 2.');
  2550. }
  2551. /**
  2552. * Test that we can log queries against multiple targets on the same connection.
  2553. */
  2554. function testEnableTargetLogging() {
  2555. // Clone the master credentials to a slave connection and to another fake
  2556. // connection.
  2557. $connection_info = Database::getConnectionInfo('default');
  2558. Database::addConnectionInfo('default', 'slave', $connection_info['default']);
  2559. Database::startLog('testing1');
  2560. db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
  2561. db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'slave'));//->fetchCol();
  2562. $queries1 = Database::getLog('testing1');
  2563. $this->assertEqual(count($queries1), 2, 'Recorded queries from all targets.');
  2564. $this->assertEqual($queries1[0]['target'], 'default', 'First query used default target.');
  2565. $this->assertEqual($queries1[1]['target'], 'slave', 'Second query used slave target.');
  2566. }
  2567. /**
  2568. * Test that logs to separate targets collapse to the same connection properly.
  2569. *
  2570. * This test is identical to the one above, except that it doesn't create
  2571. * a fake target so the query should fall back to running on the default
  2572. * target.
  2573. */
  2574. function testEnableTargetLoggingNoTarget() {
  2575. Database::startLog('testing1');
  2576. db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
  2577. // We use "fake" here as a target because any non-existent target will do.
  2578. // However, because all of the tests in this class share a single page
  2579. // request there is likely to be a target of "slave" from one of the other
  2580. // unit tests, so we use a target here that we know with absolute certainty
  2581. // does not exist.
  2582. db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'fake'))->fetchCol();
  2583. $queries1 = Database::getLog('testing1');
  2584. $this->assertEqual(count($queries1), 2, 'Recorded queries from all targets.');
  2585. $this->assertEqual($queries1[0]['target'], 'default', 'First query used default target.');
  2586. $this->assertEqual($queries1[1]['target'], 'default', 'Second query used default target as fallback.');
  2587. }
  2588. /**
  2589. * Test that we can log queries separately on different connections.
  2590. */
  2591. function testEnableMultiConnectionLogging() {
  2592. // Clone the master credentials to a fake connection.
  2593. // That both connections point to the same physical database is irrelevant.
  2594. $connection_info = Database::getConnectionInfo('default');
  2595. Database::addConnectionInfo('test2', 'default', $connection_info['default']);
  2596. Database::startLog('testing1');
  2597. Database::startLog('testing1', 'test2');
  2598. db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
  2599. $old_key = db_set_active('test2');
  2600. db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'slave'))->fetchCol();
  2601. db_set_active($old_key);
  2602. $queries1 = Database::getLog('testing1');
  2603. $queries2 = Database::getLog('testing1', 'test2');
  2604. $this->assertEqual(count($queries1), 1, 'Correct number of queries recorded for first connection.');
  2605. $this->assertEqual(count($queries2), 1, 'Correct number of queries recorded for second connection.');
  2606. }
  2607. }
  2608. /**
  2609. * Query serialization tests.
  2610. */
  2611. class DatabaseSerializeQueryTestCase extends DatabaseTestCase {
  2612. public static function getInfo() {
  2613. return array(
  2614. 'name' => 'Serialize query',
  2615. 'description' => 'Test serializing and unserializing a query.',
  2616. 'group' => 'Database',
  2617. );
  2618. }
  2619. /**
  2620. * Confirm that a query can be serialized and unserialized.
  2621. */
  2622. function testSerializeQuery() {
  2623. $query = db_select('test');
  2624. $query->addField('test', 'age');
  2625. $query->condition('name', 'Ringo');
  2626. // If this doesn't work, it will throw an exception, so no need for an
  2627. // assertion.
  2628. $query = unserialize(serialize($query));
  2629. $results = $query->execute()->fetchCol();
  2630. $this->assertEqual($results[0], 28, 'Query properly executed after unserialization.');
  2631. }
  2632. }
  2633. /**
  2634. * Range query tests.
  2635. */
  2636. class DatabaseRangeQueryTestCase extends DrupalWebTestCase {
  2637. public static function getInfo() {
  2638. return array(
  2639. 'name' => 'Range query test',
  2640. 'description' => 'Test the Range query functionality.',
  2641. 'group' => 'Database',
  2642. );
  2643. }
  2644. function setUp() {
  2645. parent::setUp('database_test');
  2646. }
  2647. /**
  2648. * Confirm that range query work and return correct result.
  2649. */
  2650. function testRangeQuery() {
  2651. // Test if return correct number of rows.
  2652. $range_rows = db_query_range("SELECT name FROM {system} ORDER BY name", 2, 3)->fetchAll();
  2653. $this->assertEqual(count($range_rows), 3, 'Range query work and return correct number of rows.');
  2654. // Test if return target data.
  2655. $raw_rows = db_query('SELECT name FROM {system} ORDER BY name')->fetchAll();
  2656. $raw_rows = array_slice($raw_rows, 2, 3);
  2657. $this->assertEqual($range_rows, $raw_rows, 'Range query work and return target data.');
  2658. }
  2659. }
  2660. /**
  2661. * Temporary query tests.
  2662. */
  2663. class DatabaseTemporaryQueryTestCase extends DrupalWebTestCase {
  2664. public static function getInfo() {
  2665. return array(
  2666. 'name' => 'Temporary query test',
  2667. 'description' => 'Test the temporary query functionality.',
  2668. 'group' => 'Database',
  2669. );
  2670. }
  2671. function setUp() {
  2672. parent::setUp('database_test');
  2673. }
  2674. /**
  2675. * Return the number of rows of a table.
  2676. */
  2677. function countTableRows($table_name) {
  2678. return db_select($table_name)->countQuery()->execute()->fetchField();
  2679. }
  2680. /**
  2681. * Confirm that temporary tables work and are limited to one request.
  2682. */
  2683. function testTemporaryQuery() {
  2684. $this->drupalGet('database_test/db_query_temporary');
  2685. $data = json_decode($this->drupalGetContent());
  2686. if ($data) {
  2687. $this->assertEqual($this->countTableRows("system"), $data->row_count, 'The temporary table contains the correct amount of rows.');
  2688. $this->assertFalse(db_table_exists($data->table_name), 'The temporary table is, indeed, temporary.');
  2689. }
  2690. else {
  2691. $this->fail("The creation of the temporary table failed.");
  2692. }
  2693. // Now try to run two db_query_temporary() in the same request.
  2694. $table_name_system = db_query_temporary('SELECT status FROM {system}', array());
  2695. $table_name_users = db_query_temporary('SELECT uid FROM {users}', array());
  2696. $this->assertEqual($this->countTableRows($table_name_system), $this->countTableRows("system"), 'A temporary table was created successfully in this request.');
  2697. $this->assertEqual($this->countTableRows($table_name_users), $this->countTableRows("users"), 'A second temporary table was created successfully in this request.');
  2698. // Check that leading whitespace and comments do not cause problems
  2699. // in the modified query.
  2700. $sql = "
  2701. -- Let's select some rows into a temporary table
  2702. SELECT name FROM {test}
  2703. ";
  2704. $table_name_test = db_query_temporary($sql, array());
  2705. $this->assertEqual($this->countTableRows($table_name_test), $this->countTableRows('test'), 'Leading white space and comments do not interfere with temporary table creation.');
  2706. }
  2707. }
  2708. /**
  2709. * Test how the current database driver interprets the SQL syntax.
  2710. *
  2711. * In order to ensure consistent SQL handling throughout Drupal
  2712. * across multiple kinds of database systems, we test that the
  2713. * database system interprets SQL syntax in an expected fashion.
  2714. */
  2715. class DatabaseBasicSyntaxTestCase extends DatabaseTestCase {
  2716. public static function getInfo() {
  2717. return array(
  2718. 'name' => 'Basic SQL syntax tests',
  2719. 'description' => 'Test SQL syntax interpretation.',
  2720. 'group' => 'Database',
  2721. );
  2722. }
  2723. function setUp() {
  2724. parent::setUp('database_test');
  2725. }
  2726. /**
  2727. * Test for string concatenation.
  2728. */
  2729. function testBasicConcat() {
  2730. $result = db_query('SELECT CONCAT(:a1, CONCAT(:a2, CONCAT(:a3, CONCAT(:a4, :a5))))', array(
  2731. ':a1' => 'This',
  2732. ':a2' => ' ',
  2733. ':a3' => 'is',
  2734. ':a4' => ' a ',
  2735. ':a5' => 'test.',
  2736. ));
  2737. $this->assertIdentical($result->fetchField(), 'This is a test.', 'Basic CONCAT works.');
  2738. }
  2739. /**
  2740. * Test for string concatenation with field values.
  2741. */
  2742. function testFieldConcat() {
  2743. $result = db_query('SELECT CONCAT(:a1, CONCAT(name, CONCAT(:a2, CONCAT(age, :a3)))) FROM {test} WHERE age = :age', array(
  2744. ':a1' => 'The age of ',
  2745. ':a2' => ' is ',
  2746. ':a3' => '.',
  2747. ':age' => 25,
  2748. ));
  2749. $this->assertIdentical($result->fetchField(), 'The age of John is 25.', 'Field CONCAT works.');
  2750. }
  2751. /**
  2752. * Test escaping of LIKE wildcards.
  2753. */
  2754. function testLikeEscape() {
  2755. db_insert('test')
  2756. ->fields(array(
  2757. 'name' => 'Ring_',
  2758. ))
  2759. ->execute();
  2760. // Match both "Ringo" and "Ring_".
  2761. $num_matches = db_select('test', 't')
  2762. ->condition('name', 'Ring_', 'LIKE')
  2763. ->countQuery()
  2764. ->execute()
  2765. ->fetchField();
  2766. $this->assertIdentical($num_matches, '2', 'Found 2 records.');
  2767. // Match only "Ring_" using a LIKE expression with no wildcards.
  2768. $num_matches = db_select('test', 't')
  2769. ->condition('name', db_like('Ring_'), 'LIKE')
  2770. ->countQuery()
  2771. ->execute()
  2772. ->fetchField();
  2773. $this->assertIdentical($num_matches, '1', 'Found 1 record.');
  2774. }
  2775. /**
  2776. * Test LIKE query containing a backslash.
  2777. */
  2778. function testLikeBackslash() {
  2779. db_insert('test')
  2780. ->fields(array('name'))
  2781. ->values(array(
  2782. 'name' => 'abcde\f',
  2783. ))
  2784. ->values(array(
  2785. 'name' => 'abc%\_',
  2786. ))
  2787. ->execute();
  2788. // Match both rows using a LIKE expression with two wildcards and a verbatim
  2789. // backslash.
  2790. $num_matches = db_select('test', 't')
  2791. ->condition('name', 'abc%\\\\_', 'LIKE')
  2792. ->countQuery()
  2793. ->execute()
  2794. ->fetchField();
  2795. $this->assertIdentical($num_matches, '2', 'Found 2 records.');
  2796. // Match only the former using a LIKE expression with no wildcards.
  2797. $num_matches = db_select('test', 't')
  2798. ->condition('name', db_like('abc%\_'), 'LIKE')
  2799. ->countQuery()
  2800. ->execute()
  2801. ->fetchField();
  2802. $this->assertIdentical($num_matches, '1', 'Found 1 record.');
  2803. }
  2804. }
  2805. /**
  2806. * Test case sensitivity handling.
  2807. */
  2808. class DatabaseCaseSensitivityTestCase extends DatabaseTestCase {
  2809. public static function getInfo() {
  2810. return array(
  2811. 'name' => 'Case sensitivity',
  2812. 'description' => 'Test handling case sensitive collation.',
  2813. 'group' => 'Database',
  2814. );
  2815. }
  2816. /**
  2817. * Test BINARY collation in MySQL.
  2818. */
  2819. function testCaseSensitiveInsert() {
  2820. $num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  2821. $john = db_insert('test')
  2822. ->fields(array(
  2823. 'name' => 'john', // <- A record already exists with name 'John'.
  2824. 'age' => 2,
  2825. 'job' => 'Baby',
  2826. ))
  2827. ->execute();
  2828. $num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
  2829. $this->assertIdentical($num_records_before + 1, (int) $num_records_after, 'Record inserts correctly.');
  2830. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'john'))->fetchField();
  2831. $this->assertIdentical($saved_age, '2', 'Can retrieve after inserting.');
  2832. }
  2833. }
  2834. /**
  2835. * Test invalid data handling.
  2836. */
  2837. class DatabaseInvalidDataTestCase extends DatabaseTestCase {
  2838. public static function getInfo() {
  2839. return array(
  2840. 'name' => 'Invalid data',
  2841. 'description' => 'Test handling of some invalid data.',
  2842. 'group' => 'Database',
  2843. );
  2844. }
  2845. function setUp() {
  2846. parent::setUp('database_test');
  2847. }
  2848. /**
  2849. * Traditional SQL database systems abort inserts when invalid data is encountered.
  2850. */
  2851. function testInsertDuplicateData() {
  2852. // Try to insert multiple records where at least one has bad data.
  2853. try {
  2854. db_insert('test')
  2855. ->fields(array('name', 'age', 'job'))
  2856. ->values(array(
  2857. 'name' => 'Elvis',
  2858. 'age' => 63,
  2859. 'job' => 'Singer',
  2860. ))->values(array(
  2861. 'name' => 'John', // <-- Duplicate value on unique field.
  2862. 'age' => 17,
  2863. 'job' => 'Consultant',
  2864. ))
  2865. ->values(array(
  2866. 'name' => 'Frank',
  2867. 'age' => 75,
  2868. 'job' => 'Singer',
  2869. ))
  2870. ->execute();
  2871. $this->fail('Insert succeedded when it should not have.');
  2872. }
  2873. catch (Exception $e) {
  2874. // Check if the first record was inserted.
  2875. $name = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 63))->fetchField();
  2876. if ($name == 'Elvis') {
  2877. if (!Database::getConnection()->supportsTransactions()) {
  2878. // This is an expected fail.
  2879. // Database engines that don't support transactions can leave partial
  2880. // inserts in place when an error occurs. This is the case for MySQL
  2881. // when running on a MyISAM table.
  2882. $this->pass("The whole transaction has not been rolled-back when a duplicate key insert occurs, this is expected because the database doesn't support transactions");
  2883. }
  2884. else {
  2885. $this->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
  2886. }
  2887. }
  2888. else {
  2889. $this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
  2890. }
  2891. // Ensure the other values were not inserted.
  2892. $record = db_select('test')
  2893. ->fields('test', array('name', 'age'))
  2894. ->condition('age', array(17, 75), 'IN')
  2895. ->execute()->fetchObject();
  2896. $this->assertFalse($record, 'The rest of the insert aborted as expected.');
  2897. }
  2898. }
  2899. }
  2900. /**
  2901. * Drupal-specific SQL syntax tests.
  2902. */
  2903. class DatabaseQueryTestCase extends DatabaseTestCase {
  2904. public static function getInfo() {
  2905. return array(
  2906. 'name' => 'Custom query syntax tests',
  2907. 'description' => 'Test Drupal\'s extended prepared statement syntax..',
  2908. 'group' => 'Database',
  2909. );
  2910. }
  2911. function setUp() {
  2912. parent::setUp('database_test');
  2913. }
  2914. /**
  2915. * Test that we can specify an array of values in the query by simply passing in an array.
  2916. */
  2917. function testArraySubstitution() {
  2918. $names = db_query('SELECT name FROM {test} WHERE age IN (:ages) ORDER BY age', array(':ages' => array(25, 26, 27)))->fetchAll();
  2919. $this->assertEqual(count($names), 3, 'Correct number of names returned');
  2920. }
  2921. /**
  2922. * Test SQL injection via database query array arguments.
  2923. */
  2924. public function testArrayArgumentsSQLInjection() {
  2925. // Attempt SQL injection and verify that it does not work.
  2926. $condition = array(
  2927. "1 ;INSERT INTO {test} (name) VALUES ('test12345678'); -- " => '',
  2928. '1' => '',
  2929. );
  2930. try {
  2931. db_query("SELECT * FROM {test} WHERE name = :name", array(':name' => $condition))->fetchObject();
  2932. $this->fail('SQL injection attempt via array arguments should result in a PDOException.');
  2933. }
  2934. catch (PDOException $e) {
  2935. $this->pass('SQL injection attempt via array arguments should result in a PDOException.');
  2936. }
  2937. // Test that the insert query that was used in the SQL injection attempt did
  2938. // not result in a row being inserted in the database.
  2939. $result = db_select('test')
  2940. ->condition('name', 'test12345678')
  2941. ->countQuery()
  2942. ->execute()
  2943. ->fetchField();
  2944. $this->assertFalse($result, 'SQL injection attempt did not result in a row being inserted in the database table.');
  2945. }
  2946. }
  2947. /**
  2948. * Test transaction support, particularly nesting.
  2949. *
  2950. * We test nesting by having two transaction layers, an outer and inner. The
  2951. * outer layer encapsulates the inner layer. Our transaction nesting abstraction
  2952. * should allow the outer layer function to call any function it wants,
  2953. * especially the inner layer that starts its own transaction, and be
  2954. * confident that, when the function it calls returns, its own transaction
  2955. * is still "alive."
  2956. *
  2957. * Call structure:
  2958. * transactionOuterLayer()
  2959. * Start transaction
  2960. * transactionInnerLayer()
  2961. * Start transaction (does nothing in database)
  2962. * [Maybe decide to roll back]
  2963. * Do more stuff
  2964. * Should still be in transaction A
  2965. *
  2966. */
  2967. class DatabaseTransactionTestCase extends DatabaseTestCase {
  2968. public static function getInfo() {
  2969. return array(
  2970. 'name' => 'Transaction tests',
  2971. 'description' => 'Test the transaction abstraction system.',
  2972. 'group' => 'Database',
  2973. );
  2974. }
  2975. /**
  2976. * Helper method for transaction unit test.
  2977. *
  2978. * This "outer layer" transaction starts and then encapsulates the
  2979. * "inner layer" transaction. This nesting is used to evaluate whether the
  2980. * database transaction API properly supports nesting. By "properly supports,"
  2981. * we mean the outer transaction continues to exist regardless of what
  2982. * functions are called and whether those functions start their own
  2983. * transactions.
  2984. *
  2985. * In contrast, a typical database would commit the outer transaction, start
  2986. * a new transaction for the inner layer, commit the inner layer transaction,
  2987. * and then be confused when the outer layer transaction tries to commit its
  2988. * transaction (which was already committed when the inner transaction
  2989. * started).
  2990. *
  2991. * @param $suffix
  2992. * Suffix to add to field values to differentiate tests.
  2993. * @param $rollback
  2994. * Whether or not to try rolling back the transaction when we're done.
  2995. * @param $ddl_statement
  2996. * Whether to execute a DDL statement during the inner transaction.
  2997. */
  2998. protected function transactionOuterLayer($suffix, $rollback = FALSE, $ddl_statement = FALSE) {
  2999. $connection = Database::getConnection();
  3000. $depth = $connection->transactionDepth();
  3001. $txn = db_transaction();
  3002. // Insert a single row into the testing table.
  3003. db_insert('test')
  3004. ->fields(array(
  3005. 'name' => 'David' . $suffix,
  3006. 'age' => '24',
  3007. ))
  3008. ->execute();
  3009. $this->assertTrue($connection->inTransaction(), 'In transaction before calling nested transaction.');
  3010. // We're already in a transaction, but we call ->transactionInnerLayer
  3011. // to nest another transaction inside the current one.
  3012. $this->transactionInnerLayer($suffix, $rollback, $ddl_statement);
  3013. $this->assertTrue($connection->inTransaction(), 'In transaction after calling nested transaction.');
  3014. if ($rollback) {
  3015. // Roll back the transaction, if requested.
  3016. // This rollback should propagate to the last savepoint.
  3017. $txn->rollback();
  3018. $this->assertTrue(($connection->transactionDepth() == $depth), 'Transaction has rolled back to the last savepoint after calling rollback().');
  3019. }
  3020. }
  3021. /**
  3022. * Helper method for transaction unit tests. This "inner layer" transaction
  3023. * is either used alone or nested inside of the "outer layer" transaction.
  3024. *
  3025. * @param $suffix
  3026. * Suffix to add to field values to differentiate tests.
  3027. * @param $rollback
  3028. * Whether or not to try rolling back the transaction when we're done.
  3029. * @param $ddl_statement
  3030. * Whether to execute a DDL statement during the transaction.
  3031. */
  3032. protected function transactionInnerLayer($suffix, $rollback = FALSE, $ddl_statement = FALSE) {
  3033. $connection = Database::getConnection();
  3034. $depth = $connection->transactionDepth();
  3035. // Start a transaction. If we're being called from ->transactionOuterLayer,
  3036. // then we're already in a transaction. Normally, that would make starting
  3037. // a transaction here dangerous, but the database API handles this problem
  3038. // for us by tracking the nesting and avoiding the danger.
  3039. $txn = db_transaction();
  3040. $depth2 = $connection->transactionDepth();
  3041. $this->assertTrue($depth < $depth2, 'Transaction depth is has increased with new transaction.');
  3042. // Insert a single row into the testing table.
  3043. db_insert('test')
  3044. ->fields(array(
  3045. 'name' => 'Daniel' . $suffix,
  3046. 'age' => '19',
  3047. ))
  3048. ->execute();
  3049. $this->assertTrue($connection->inTransaction(), 'In transaction inside nested transaction.');
  3050. if ($ddl_statement) {
  3051. $table = array(
  3052. 'fields' => array(
  3053. 'id' => array(
  3054. 'type' => 'serial',
  3055. 'unsigned' => TRUE,
  3056. 'not null' => TRUE,
  3057. ),
  3058. ),
  3059. 'primary key' => array('id'),
  3060. );
  3061. db_create_table('database_test_1', $table);
  3062. $this->assertTrue($connection->inTransaction(), 'In transaction inside nested transaction.');
  3063. }
  3064. if ($rollback) {
  3065. // Roll back the transaction, if requested.
  3066. // This rollback should propagate to the last savepoint.
  3067. $txn->rollback();
  3068. $this->assertTrue(($connection->transactionDepth() == $depth), 'Transaction has rolled back to the last savepoint after calling rollback().');
  3069. }
  3070. }
  3071. /**
  3072. * Test transaction rollback on a database that supports transactions.
  3073. *
  3074. * If the active connection does not support transactions, this test does nothing.
  3075. */
  3076. function testTransactionRollBackSupported() {
  3077. // This test won't work right if transactions are not supported.
  3078. if (!Database::getConnection()->supportsTransactions()) {
  3079. return;
  3080. }
  3081. try {
  3082. // Create two nested transactions. Roll back from the inner one.
  3083. $this->transactionOuterLayer('B', TRUE);
  3084. // Neither of the rows we inserted in the two transaction layers
  3085. // should be present in the tables post-rollback.
  3086. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DavidB'))->fetchField();
  3087. $this->assertNotIdentical($saved_age, '24', 'Cannot retrieve DavidB row after commit.');
  3088. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DanielB'))->fetchField();
  3089. $this->assertNotIdentical($saved_age, '19', 'Cannot retrieve DanielB row after commit.');
  3090. }
  3091. catch (Exception $e) {
  3092. $this->fail($e->getMessage());
  3093. }
  3094. }
  3095. /**
  3096. * Test transaction rollback on a database that does not support transactions.
  3097. *
  3098. * If the active driver supports transactions, this test does nothing.
  3099. */
  3100. function testTransactionRollBackNotSupported() {
  3101. // This test won't work right if transactions are supported.
  3102. if (Database::getConnection()->supportsTransactions()) {
  3103. return;
  3104. }
  3105. try {
  3106. // Create two nested transactions. Attempt to roll back from the inner one.
  3107. $this->transactionOuterLayer('B', TRUE);
  3108. // Because our current database claims to not support transactions,
  3109. // the inserted rows should be present despite the attempt to roll back.
  3110. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DavidB'))->fetchField();
  3111. $this->assertIdentical($saved_age, '24', 'DavidB not rolled back, since transactions are not supported.');
  3112. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DanielB'))->fetchField();
  3113. $this->assertIdentical($saved_age, '19', 'DanielB not rolled back, since transactions are not supported.');
  3114. }
  3115. catch (Exception $e) {
  3116. $this->fail($e->getMessage());
  3117. }
  3118. }
  3119. /**
  3120. * Test committed transaction.
  3121. *
  3122. * The behavior of this test should be identical for connections that support
  3123. * transactions and those that do not.
  3124. */
  3125. function testCommittedTransaction() {
  3126. try {
  3127. // Create two nested transactions. The changes should be committed.
  3128. $this->transactionOuterLayer('A');
  3129. // Because we committed, both of the inserted rows should be present.
  3130. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DavidA'))->fetchField();
  3131. $this->assertIdentical($saved_age, '24', 'Can retrieve DavidA row after commit.');
  3132. $saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DanielA'))->fetchField();
  3133. $this->assertIdentical($saved_age, '19', 'Can retrieve DanielA row after commit.');
  3134. }
  3135. catch (Exception $e) {
  3136. $this->fail($e->getMessage());
  3137. }
  3138. }
  3139. /**
  3140. * Test the compatibility of transactions with DDL statements.
  3141. */
  3142. function testTransactionWithDdlStatement() {
  3143. // First, test that a commit works normally, even with DDL statements.
  3144. $transaction = db_transaction();
  3145. $this->insertRow('row');
  3146. $this->executeDDLStatement();
  3147. unset($transaction);
  3148. $this->assertRowPresent('row');
  3149. // Even in different order.
  3150. $this->cleanUp();
  3151. $transaction = db_transaction();
  3152. $this->executeDDLStatement();
  3153. $this->insertRow('row');
  3154. unset($transaction);
  3155. $this->assertRowPresent('row');
  3156. // Even with stacking.
  3157. $this->cleanUp();
  3158. $transaction = db_transaction();
  3159. $transaction2 = db_transaction();
  3160. $this->executeDDLStatement();
  3161. unset($transaction2);
  3162. $transaction3 = db_transaction();
  3163. $this->insertRow('row');
  3164. unset($transaction3);
  3165. unset($transaction);
  3166. $this->assertRowPresent('row');
  3167. // A transaction after a DDL statement should still work the same.
  3168. $this->cleanUp();
  3169. $transaction = db_transaction();
  3170. $transaction2 = db_transaction();
  3171. $this->executeDDLStatement();
  3172. unset($transaction2);
  3173. $transaction3 = db_transaction();
  3174. $this->insertRow('row');
  3175. $transaction3->rollback();
  3176. unset($transaction3);
  3177. unset($transaction);
  3178. $this->assertRowAbsent('row');
  3179. // The behavior of a rollback depends on the type of database server.
  3180. if (Database::getConnection()->supportsTransactionalDDL()) {
  3181. // For database servers that support transactional DDL, a rollback
  3182. // of a transaction including DDL statements should be possible.
  3183. $this->cleanUp();
  3184. $transaction = db_transaction();
  3185. $this->insertRow('row');
  3186. $this->executeDDLStatement();
  3187. $transaction->rollback();
  3188. unset($transaction);
  3189. $this->assertRowAbsent('row');
  3190. // Including with stacking.
  3191. $this->cleanUp();
  3192. $transaction = db_transaction();
  3193. $transaction2 = db_transaction();
  3194. $this->executeDDLStatement();
  3195. unset($transaction2);
  3196. $transaction3 = db_transaction();
  3197. $this->insertRow('row');
  3198. unset($transaction3);
  3199. $transaction->rollback();
  3200. unset($transaction);
  3201. $this->assertRowAbsent('row');
  3202. }
  3203. else {
  3204. // For database servers that do not support transactional DDL,
  3205. // the DDL statement should commit the transaction stack.
  3206. $this->cleanUp();
  3207. $transaction = db_transaction();
  3208. $this->insertRow('row');
  3209. $this->executeDDLStatement();
  3210. // Rollback the outer transaction.
  3211. try {
  3212. $transaction->rollback();
  3213. unset($transaction);
  3214. // @TODO: an exception should be triggered here, but is not, because
  3215. // "ROLLBACK" fails silently in MySQL if there is no transaction active.
  3216. // $this->fail(t('Rolling back a transaction containing DDL should fail.'));
  3217. }
  3218. catch (DatabaseTransactionNoActiveException $e) {
  3219. $this->pass('Rolling back a transaction containing DDL should fail.');
  3220. }
  3221. $this->assertRowPresent('row');
  3222. }
  3223. }
  3224. /**
  3225. * Insert a single row into the testing table.
  3226. */
  3227. protected function insertRow($name) {
  3228. db_insert('test')
  3229. ->fields(array(
  3230. 'name' => $name,
  3231. ))
  3232. ->execute();
  3233. }
  3234. /**
  3235. * Execute a DDL statement.
  3236. */
  3237. protected function executeDDLStatement() {
  3238. static $count = 0;
  3239. $table = array(
  3240. 'fields' => array(
  3241. 'id' => array(
  3242. 'type' => 'serial',
  3243. 'unsigned' => TRUE,
  3244. 'not null' => TRUE,
  3245. ),
  3246. ),
  3247. 'primary key' => array('id'),
  3248. );
  3249. db_create_table('database_test_' . ++$count, $table);
  3250. }
  3251. /**
  3252. * Start over for a new test.
  3253. */
  3254. protected function cleanUp() {
  3255. db_truncate('test')
  3256. ->execute();
  3257. }
  3258. /**
  3259. * Assert that a given row is present in the test table.
  3260. *
  3261. * @param $name
  3262. * The name of the row.
  3263. * @param $message
  3264. * The message to log for the assertion.
  3265. */
  3266. function assertRowPresent($name, $message = NULL) {
  3267. if (!isset($message)) {
  3268. $message = format_string('Row %name is present.', array('%name' => $name));
  3269. }
  3270. $present = (boolean) db_query('SELECT 1 FROM {test} WHERE name = :name', array(':name' => $name))->fetchField();
  3271. return $this->assertTrue($present, $message);
  3272. }
  3273. /**
  3274. * Assert that a given row is absent from the test table.
  3275. *
  3276. * @param $name
  3277. * The name of the row.
  3278. * @param $message
  3279. * The message to log for the assertion.
  3280. */
  3281. function assertRowAbsent($name, $message = NULL) {
  3282. if (!isset($message)) {
  3283. $message = format_string('Row %name is absent.', array('%name' => $name));
  3284. }
  3285. $present = (boolean) db_query('SELECT 1 FROM {test} WHERE name = :name', array(':name' => $name))->fetchField();
  3286. return $this->assertFalse($present, $message);
  3287. }
  3288. /**
  3289. * Test transaction stacking and commit / rollback.
  3290. */
  3291. function testTransactionStacking() {
  3292. // This test won't work right if transactions are not supported.
  3293. if (!Database::getConnection()->supportsTransactions()) {
  3294. return;
  3295. }
  3296. $database = Database::getConnection();
  3297. // Standard case: pop the inner transaction before the outer transaction.
  3298. $transaction = db_transaction();
  3299. $this->insertRow('outer');
  3300. $transaction2 = db_transaction();
  3301. $this->insertRow('inner');
  3302. // Pop the inner transaction.
  3303. unset($transaction2);
  3304. $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the inner transaction');
  3305. // Pop the outer transaction.
  3306. unset($transaction);
  3307. $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the outer transaction');
  3308. $this->assertRowPresent('outer');
  3309. $this->assertRowPresent('inner');
  3310. // Pop the transaction in a different order they have been pushed.
  3311. $this->cleanUp();
  3312. $transaction = db_transaction();
  3313. $this->insertRow('outer');
  3314. $transaction2 = db_transaction();
  3315. $this->insertRow('inner');
  3316. // Pop the outer transaction, nothing should happen.
  3317. unset($transaction);
  3318. $this->insertRow('inner-after-outer-commit');
  3319. $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction');
  3320. // Pop the inner transaction, the whole transaction should commit.
  3321. unset($transaction2);
  3322. $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the inner transaction');
  3323. $this->assertRowPresent('outer');
  3324. $this->assertRowPresent('inner');
  3325. $this->assertRowPresent('inner-after-outer-commit');
  3326. // Rollback the inner transaction.
  3327. $this->cleanUp();
  3328. $transaction = db_transaction();
  3329. $this->insertRow('outer');
  3330. $transaction2 = db_transaction();
  3331. $this->insertRow('inner');
  3332. // Now rollback the inner transaction.
  3333. $transaction2->rollback();
  3334. unset($transaction2);
  3335. $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction');
  3336. // Pop the outer transaction, it should commit.
  3337. $this->insertRow('outer-after-inner-rollback');
  3338. unset($transaction);
  3339. $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the inner transaction');
  3340. $this->assertRowPresent('outer');
  3341. $this->assertRowAbsent('inner');
  3342. $this->assertRowPresent('outer-after-inner-rollback');
  3343. // Rollback the inner transaction after committing the outer one.
  3344. $this->cleanUp();
  3345. $transaction = db_transaction();
  3346. $this->insertRow('outer');
  3347. $transaction2 = db_transaction();
  3348. $this->insertRow('inner');
  3349. // Pop the outer transaction, nothing should happen.
  3350. unset($transaction);
  3351. $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction');
  3352. // Now rollback the inner transaction, it should rollback.
  3353. $transaction2->rollback();
  3354. unset($transaction2);
  3355. $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the inner transaction');
  3356. $this->assertRowPresent('outer');
  3357. $this->assertRowAbsent('inner');
  3358. // Rollback the outer transaction while the inner transaction is active.
  3359. // In that case, an exception will be triggered because we cannot
  3360. // ensure that the final result will have any meaning.
  3361. $this->cleanUp();
  3362. $transaction = db_transaction();
  3363. $this->insertRow('outer');
  3364. $transaction2 = db_transaction();
  3365. $this->insertRow('inner');
  3366. $transaction3 = db_transaction();
  3367. $this->insertRow('inner2');
  3368. // Rollback the outer transaction.
  3369. try {
  3370. $transaction->rollback();
  3371. unset($transaction);
  3372. $this->fail('Rolling back the outer transaction while the inner transaction is active resulted in an exception.');
  3373. }
  3374. catch (DatabaseTransactionOutOfOrderException $e) {
  3375. $this->pass('Rolling back the outer transaction while the inner transaction is active resulted in an exception.');
  3376. }
  3377. $this->assertFalse($database->inTransaction(), 'No more in a transaction after rolling back the outer transaction');
  3378. // Try to commit one inner transaction.
  3379. unset($transaction3);
  3380. $this->pass('Trying to commit an inner transaction resulted in an exception.');
  3381. // Try to rollback one inner transaction.
  3382. try {
  3383. $transaction->rollback();
  3384. unset($transaction2);
  3385. $this->fail('Trying to commit an inner transaction resulted in an exception.');
  3386. }
  3387. catch (DatabaseTransactionNoActiveException $e) {
  3388. $this->pass('Trying to commit an inner transaction resulted in an exception.');
  3389. }
  3390. $this->assertRowAbsent('outer');
  3391. $this->assertRowAbsent('inner');
  3392. $this->assertRowAbsent('inner2');
  3393. }
  3394. }
  3395. /**
  3396. * Check the sequences API.
  3397. */
  3398. class DatabaseNextIdCase extends DrupalWebTestCase {
  3399. public static function getInfo() {
  3400. return array(
  3401. 'name' => 'Sequences API',
  3402. 'description' => 'Test the secondary sequences API.',
  3403. 'group' => 'Database',
  3404. );
  3405. }
  3406. /**
  3407. * Test that the sequences API work.
  3408. */
  3409. function testDbNextId() {
  3410. $first = db_next_id();
  3411. $second = db_next_id();
  3412. // We can test for exact increase in here because we know there is no
  3413. // other process operating on these tables -- normally we could only
  3414. // expect $second > $first.
  3415. $this->assertEqual($first + 1, $second, 'The second call from a sequence provides a number increased by one.');
  3416. $result = db_next_id(1000);
  3417. $this->assertEqual($result, 1001, 'Sequence provides a larger number than the existing ID.');
  3418. }
  3419. }
  3420. /**
  3421. * Tests the empty pseudo-statement class.
  3422. */
  3423. class DatabaseEmptyStatementTestCase extends DrupalWebTestCase {
  3424. public static function getInfo() {
  3425. return array(
  3426. 'name' => 'Empty statement',
  3427. 'description' => 'Test the empty pseudo-statement class.',
  3428. 'group' => 'Database',
  3429. );
  3430. }
  3431. /**
  3432. * Test that the empty result set behaves as empty.
  3433. */
  3434. function testEmpty() {
  3435. $result = new DatabaseStatementEmpty();
  3436. $this->assertTrue($result instanceof DatabaseStatementInterface, 'Class implements expected interface');
  3437. $this->assertNull($result->fetchObject(), 'Null result returned.');
  3438. }
  3439. /**
  3440. * Test that the empty result set iterates safely.
  3441. */
  3442. function testEmptyIteration() {
  3443. $result = new DatabaseStatementEmpty();
  3444. foreach ($result as $record) {
  3445. $this->fail('Iterating empty result set should not iterate.');
  3446. return;
  3447. }
  3448. $this->pass('Iterating empty result set skipped iteration.');
  3449. }
  3450. /**
  3451. * Test that the empty result set mass-fetches in an expected way.
  3452. */
  3453. function testEmptyFetchAll() {
  3454. $result = new DatabaseStatementEmpty();
  3455. $this->assertEqual($result->fetchAll(), array(), 'Empty array returned from empty result set.');
  3456. }
  3457. }
  3458. /**
  3459. * Tests management of database connections.
  3460. */
  3461. class ConnectionUnitTest extends DrupalUnitTestCase {
  3462. protected $key;
  3463. protected $target;
  3464. protected $monitor;
  3465. protected $originalCount;
  3466. public static function getInfo() {
  3467. return array(
  3468. 'name' => 'Connection unit tests',
  3469. 'description' => 'Tests management of database connections.',
  3470. 'group' => 'Database',
  3471. );
  3472. }
  3473. function setUp() {
  3474. parent::setUp();
  3475. $this->key = 'default';
  3476. $this->originalTarget = 'default';
  3477. $this->target = 'DatabaseConnectionUnitTest';
  3478. // Determine whether the database driver is MySQL. If it is not, the test
  3479. // methods will not be executed.
  3480. // @todo Make this test driver-agnostic, or find a proper way to skip it.
  3481. // @see http://drupal.org/node/1273478
  3482. $connection_info = Database::getConnectionInfo('default');
  3483. $this->skipTest = (bool) $connection_info['default']['driver'] != 'mysql';
  3484. if ($this->skipTest) {
  3485. // Insert an assertion to prevent Simpletest from interpreting the test
  3486. // as failure.
  3487. $this->pass('This test is only compatible with MySQL.');
  3488. }
  3489. // Create an additional connection to monitor the connections being opened
  3490. // and closed in this test.
  3491. // @see TestBase::changeDatabasePrefix()
  3492. $connection_info = Database::getConnectionInfo('default');
  3493. Database::addConnectionInfo('default', 'monitor', $connection_info['default']);
  3494. global $databases;
  3495. $databases['default']['monitor'] = $connection_info['default'];
  3496. $this->monitor = Database::getConnection('monitor');
  3497. }
  3498. /**
  3499. * Adds a new database connection info to Database.
  3500. */
  3501. protected function addConnection() {
  3502. // Add a new target to the connection, by cloning the current connection.
  3503. $connection_info = Database::getConnectionInfo($this->key);
  3504. Database::addConnectionInfo($this->key, $this->target, $connection_info[$this->originalTarget]);
  3505. // Verify that the new target exists.
  3506. $info = Database::getConnectionInfo($this->key);
  3507. // Note: Custom assertion message to not expose database credentials.
  3508. $this->assertIdentical($info[$this->target], $connection_info[$this->key], 'New connection info found.');
  3509. }
  3510. /**
  3511. * Returns the connection ID of the current test connection.
  3512. *
  3513. * @return integer
  3514. */
  3515. protected function getConnectionID() {
  3516. return (int) Database::getConnection($this->target, $this->key)->query('SELECT CONNECTION_ID()')->fetchField();
  3517. }
  3518. /**
  3519. * Asserts that a connection ID exists.
  3520. *
  3521. * @param integer $id
  3522. * The connection ID to verify.
  3523. */
  3524. protected function assertConnection($id) {
  3525. $list = $this->monitor->query('SHOW PROCESSLIST')->fetchAllKeyed(0, 0);
  3526. return $this->assertTrue(isset($list[$id]), format_string('Connection ID @id found.', array('@id' => $id)));
  3527. }
  3528. /**
  3529. * Asserts that a connection ID does not exist.
  3530. *
  3531. * @param integer $id
  3532. * The connection ID to verify.
  3533. */
  3534. protected function assertNoConnection($id) {
  3535. $list = $this->monitor->query('SHOW PROCESSLIST')->fetchAllKeyed(0, 0);
  3536. return $this->assertFalse(isset($list[$id]), format_string('Connection ID @id not found.', array('@id' => $id)));
  3537. }
  3538. /**
  3539. * Tests Database::closeConnection() without query.
  3540. *
  3541. * @todo getConnectionID() executes a query.
  3542. */
  3543. function testOpenClose() {
  3544. if ($this->skipTest) {
  3545. return;
  3546. }
  3547. // Add and open a new connection.
  3548. $this->addConnection();
  3549. $id = $this->getConnectionID();
  3550. Database::getConnection($this->target, $this->key);
  3551. // Verify that there is a new connection.
  3552. $this->assertConnection($id);
  3553. // Close the connection.
  3554. Database::closeConnection($this->target, $this->key);
  3555. // Wait 20ms to give the database engine sufficient time to react.
  3556. usleep(20000);
  3557. // Verify that we are back to the original connection count.
  3558. $this->assertNoConnection($id);
  3559. }
  3560. /**
  3561. * Tests Database::closeConnection() with a query.
  3562. */
  3563. function testOpenQueryClose() {
  3564. if ($this->skipTest) {
  3565. return;
  3566. }
  3567. // Add and open a new connection.
  3568. $this->addConnection();
  3569. $id = $this->getConnectionID();
  3570. Database::getConnection($this->target, $this->key);
  3571. // Verify that there is a new connection.
  3572. $this->assertConnection($id);
  3573. // Execute a query.
  3574. Database::getConnection($this->target, $this->key)->query('SHOW TABLES');
  3575. // Close the connection.
  3576. Database::closeConnection($this->target, $this->key);
  3577. // Wait 20ms to give the database engine sufficient time to react.
  3578. usleep(20000);
  3579. // Verify that we are back to the original connection count.
  3580. $this->assertNoConnection($id);
  3581. }
  3582. /**
  3583. * Tests Database::closeConnection() with a query and custom prefetch method.
  3584. */
  3585. function testOpenQueryPrefetchClose() {
  3586. if ($this->skipTest) {
  3587. return;
  3588. }
  3589. // Add and open a new connection.
  3590. $this->addConnection();
  3591. $id = $this->getConnectionID();
  3592. Database::getConnection($this->target, $this->key);
  3593. // Verify that there is a new connection.
  3594. $this->assertConnection($id);
  3595. // Execute a query.
  3596. Database::getConnection($this->target, $this->key)->query('SHOW TABLES')->fetchCol();
  3597. // Close the connection.
  3598. Database::closeConnection($this->target, $this->key);
  3599. // Wait 20ms to give the database engine sufficient time to react.
  3600. usleep(20000);
  3601. // Verify that we are back to the original connection count.
  3602. $this->assertNoConnection($id);
  3603. }
  3604. /**
  3605. * Tests Database::closeConnection() with a select query.
  3606. */
  3607. function testOpenSelectQueryClose() {
  3608. if ($this->skipTest) {
  3609. return;
  3610. }
  3611. // Add and open a new connection.
  3612. $this->addConnection();
  3613. $id = $this->getConnectionID();
  3614. Database::getConnection($this->target, $this->key);
  3615. // Verify that there is a new connection.
  3616. $this->assertConnection($id);
  3617. // Create a table.
  3618. $name = 'foo';
  3619. Database::getConnection($this->target, $this->key)->schema()->createTable($name, array(
  3620. 'fields' => array(
  3621. 'name' => array(
  3622. 'type' => 'varchar',
  3623. 'length' => 255,
  3624. ),
  3625. ),
  3626. ));
  3627. // Execute a query.
  3628. Database::getConnection($this->target, $this->key)->select('foo', 'f')
  3629. ->fields('f', array('name'))
  3630. ->execute()
  3631. ->fetchAll();
  3632. // Drop the table.
  3633. Database::getConnection($this->target, $this->key)->schema()->dropTable($name);
  3634. // Close the connection.
  3635. Database::closeConnection($this->target, $this->key);
  3636. // Wait 20ms to give the database engine sufficient time to react.
  3637. usleep(20000);
  3638. // Verify that we are back to the original connection count.
  3639. $this->assertNoConnection($id);
  3640. }
  3641. }