tripal_chado.install.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. <?php
  2. /**
  3. * @file
  4. * Functions to install chado schema through Drupal
  5. */
  6. /**
  7. * Load Chado Schema Form
  8. *
  9. * @ingroup tripal_chado
  10. */
  11. function tripal_chado_load_form($form, $form_state) {
  12. // we want to force the version of Chado to be set properly
  13. $real_version = chado_get_version(TRUE);
  14. // get the effective version. Pass true as second argument
  15. // to warn the user if the current version is not compatible
  16. $version = chado_get_version(FALSE, TRUE);
  17. if (array_key_exists('values', $form_state)) {
  18. if ($form_state['values']['action_to_do'] == "Upgrade Chado v1.2 to v1.3") {
  19. $tables_list = implode(', ', array('analysis_cvterm', 'analysis_dbxref', 'analysis_pub',
  20. 'analysis_relationship', 'contactprop', 'dbprop', 'feature_contact',
  21. 'featuremap_contact', 'featuremap_dbxref', 'featuremap_organism', 'featuremapprop',
  22. 'featureposprop', 'library_contact', 'library_expression', 'library_expressionprop',
  23. 'library_featureprop', 'library_relationship', 'library_relationship_pub', 'nd_experiment_analysis',
  24. 'organism_cvterm', 'organism_cvtermprop', 'organism_pub', 'organism_relationship',
  25. 'organismprop_pub', 'phenotypeprop', 'phylotreeprop', 'project_analysis',
  26. 'project_dbxref', 'project_feature', 'project_stock', 'pubauthor_contact',
  27. 'stock_feature', 'stock_featuremap', 'stock_library', 'stockcollection_db'));
  28. $items = array(
  29. 'PostgreSQL version 9.1 is required to perform this upgrade. If your Tripal
  30. site uses an older version please upgrade before proceeding.',
  31. 'A major change between Chado v1.2 and v1.3 is that primary and foreign
  32. keys were upgraded from integers to big integers. If your site has custom
  33. materialized views that will hold data derived from fields changed to
  34. big integers then you may need to alter the views to change the fields
  35. from integers to big integers and repopulate those views. If you have not
  36. added any materialized views you can ignore this issue.',
  37. 'Custom PL/pgSQL functions that expect primary and
  38. foreign key fields to be integers will not work after the upgrade.
  39. Those functions will need to be altered to accept big integers. If you
  40. do not have any custom PL/pgSQL functions you can ignore this issue.',
  41. 'PostgreSQL Views that use fields that are converted to big
  42. integers will cause this upgrade to fail. You must first remove
  43. those views, perform the upgrade and then recreate them with the
  44. appropriate fields change to big integers. If you do not have custom
  45. PostgreSQL Views you can ignore this issue.',
  46. 'Several new tables were added to Chado v1.3. However, some groups have
  47. added these tables to their Chado v1.2 installation. The Tripal upgrader
  48. will alter the primary and foreign keys of those tables to be "bigints"
  49. if they already exist but will otherwise leave them the same. You should
  50. verify that any tables with Chado v1.3 names correctly match the v1.3 schema.
  51. Otherwise you may have problems using Tripal. If you have not added any
  52. Chado v1.3 tables to your Chado v1.2 database you can ignore this issue.
  53. These are the newly added tables: ' .
  54. $tables_list . '.'
  55. );
  56. $list = theme_item_list(array(
  57. 'items' => $items,
  58. 'title' => '',
  59. 'type' => 'ul',
  60. 'attributes' => array(),
  61. ));
  62. drupal_set_message('Please note: the upgrade of Chado from v1.2 to v1.3 may
  63. require several fixes to your database. Please review the following
  64. list to ensure a safe upgrade. The Tripal upgrader is
  65. not able to fix these problems automatically: ' . $list, 'warning');
  66. }
  67. if ($form_state['values']['action_to_do'] == "Install Chado v1.3" or
  68. $form_state['values']['action_to_do'] == "Install Chado v1.2" or
  69. $form_state['values']['action_to_do'] == "Install Chado v1.11") {
  70. drupal_set_message('Please note: if Chado is already installed it will
  71. be removed and recreated and all data will be lost. If this is
  72. desired or if this is the first time Chado has been installed
  73. you can ignore this issue.', 'warning');
  74. }
  75. }
  76. $form['current_version'] = array(
  77. '#type' => 'item',
  78. '#title' => t("Current installed version of Chado:"),
  79. '#description' => $real_version,
  80. );
  81. $form['action_to_do'] = array(
  82. '#type' => 'select',
  83. '#title' => 'Installation/Upgrade Action',
  84. '#options' => array(
  85. 'Install Chado v1.3' => t('New Install of Chado v1.3 (erases all existing Chado data if Chado already exists)'),
  86. 'Upgrade Chado v1.2 to v1.3' => t('Upgrade existing Chado v1.2 to v1.3 (no data is lost)'),
  87. 'Install Chado v1.2' => t('New Install of Chado v1.2 (erases all existing Chado data if Chado already exists)'),
  88. 'Upgrade Chado v1.11 to v1.2' => t('Upgrade existing Chado v1.11 to v1.2 (no data is lost)'),
  89. 'Install Chado v1.11' => t('New Install of Chado v1.11 (erases all existing Chado data if Chado already exists)'),
  90. ),
  91. '#description' => t('Select an action to perform.'),
  92. '#required' => TRUE,
  93. '#ajax' => array(
  94. 'callback' => "tripal_chado_load_form_ajax_callback",
  95. 'wrapper' => 'tripal_chado_load_form',
  96. 'effect' => 'fade',
  97. 'method' => 'replace',
  98. ),
  99. );
  100. $form['button'] = array(
  101. '#type' => 'submit',
  102. '#value' => t('Install/Upgrade Chado'),
  103. );
  104. $form['#prefix'] = '<div id="tripal_chado_load_form">';
  105. $form['#suffix'] = '</div>';
  106. return $form;
  107. }
  108. /**
  109. * Ajax callback function for the gensas_job_view_panel_form.
  110. *
  111. * @param $form
  112. * @param $form_state
  113. */
  114. function tripal_chado_load_form_ajax_callback($form, $form_state) {
  115. return $form;
  116. }
  117. function tripal_chado_load_form_validate($form, &$form_state) {
  118. // We do not want to allow re-installation of Chado if other
  119. // Tripal modules are installed. This is because the install files
  120. // of those modules may add content to Chado and reinstalling Chado
  121. // removes that content which may break the modules.
  122. if ($form_state['values']['action_to_do'] == "Install Chado v1.3" or
  123. $form_state['values']['action_to_do'] == "Install Chado v1.2" or
  124. $form_state['values']['action_to_do'] == "Install Chado v1.11") {
  125. $modules = system_get_info('module');
  126. // The tripal_chado_views module should not be included as it's a required
  127. // dependency of tripal_chado
  128. unset($modules['tripal_chado_views']);
  129. $list = array();
  130. foreach ($modules as $mname => $module) {
  131. if (array_key_exists('dependencies', $module) and in_array('tripal_chado', $module['dependencies'])) {
  132. $list[] = $module['name'] . " ($mname)";
  133. }
  134. }
  135. if (count($list) > 0) {
  136. form_set_error("action_to_do", "Chado cannot be installed while other Tripal modules
  137. are enabled. You must fully uninstall the following modules if you
  138. would like to install or re-install chado.<br>" .
  139. implode("<br>", $list));
  140. }
  141. }
  142. if ($form_state['values']['action_to_do'] == "Upgrade Chado v1.11 to v1.2") {
  143. // Make sure we are already not at v1.2
  144. $real_version = chado_get_version(TRUE);
  145. if ($real_version == "1.2") {
  146. form_set_error("action_to_do", "You are already at v1.2. There is no need to upgrade.");
  147. }
  148. }
  149. if ($form_state['values']['action_to_do'] == "Upgrade Chado v1.2 to v1.3") {
  150. // Make sure we are already not at v1.3
  151. $real_version = chado_get_version(TRUE);
  152. if ($real_version == "1.3") {
  153. form_set_error("action_to_do", "You are already at v1.3. There is no need to upgrade.");
  154. }
  155. }
  156. }
  157. /**
  158. * Submit Load Chado Schema Form
  159. *
  160. * @ingroup tripal_chado
  161. */
  162. function tripal_chado_load_form_submit($form, &$form_state) {
  163. global $user;
  164. $action_to_do = trim($form_state['values']['action_to_do']);
  165. $args = array($action_to_do);
  166. $includes = array(module_load_include('inc', 'tripal_chado', 'includes/tripal_chado.install'));
  167. tripal_add_job($action_to_do, 'tripal_chado',
  168. 'tripal_chado_install_chado', $args, $user->uid, 10, $includes);
  169. }
  170. /**
  171. * Submit Load Chado Schema Form
  172. *
  173. * @ingroup tripal_chado
  174. */
  175. function tripal_chado_load_drush_submit($version) {
  176. $args = array($version);
  177. $includes = array(module_load_include('inc', 'tripal_chado', 'includes/tripal_chado.install'));
  178. tripal_add_job($version, 'tripal_chado',
  179. 'tripal_chado_install_chado', $args, 1, 10, $includes);
  180. }
  181. /**
  182. * Install Chado Schema
  183. *
  184. * @ingroup tripal_chado
  185. */
  186. function tripal_chado_install_chado($action, TripalJob $job = NULL) {
  187. $vsql = "
  188. INSERT INTO {chadoprop} (type_id, value)
  189. VALUES (
  190. (SELECT cvterm_id
  191. FROM {cvterm} CVT
  192. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  193. WHERE CV.name = 'chado_properties' AND CVT.name = 'version'),
  194. :version)
  195. ";
  196. $vusql = "
  197. UPDATE {chadoprop}
  198. SET value = :version
  199. WHERE type_id = (SELECT cvterm_id
  200. FROM {cvterm} CVT
  201. INNER JOIN {cv} CV on CVT.cv_id = CV.cv_id
  202. WHERE CV.name = 'chado_properties' AND CVT.name = 'version')
  203. ";
  204. $transaction = db_transaction();
  205. try {
  206. if ($action == 'Install Chado v1.3') {
  207. tripal_chado_install_chado_1_3();
  208. chado_query($vsql, array(':version' => '1.3'));
  209. }
  210. elseif ($action == 'Upgrade Chado v1.2 to v1.3') {
  211. tripal_chado_upgrade_chado_1_2_to_1_3();
  212. chado_query($vusql, array(':version' => '1.3'));
  213. }
  214. elseif ($action == 'Install Chado v1.2') {
  215. tripal_chado_install_chado_1_2();
  216. chado_query($vsql, array(':version' => '1.2'));
  217. }
  218. elseif ($action == 'Upgrade Chado v1.11 to v1.2') {
  219. tripal_chado_upgrade_chado_1_11_to_1_2();
  220. chado_query($vsql, array(':version' => '1.2'));
  221. }
  222. elseif ($action == 'Install Chado v1.11') {
  223. tripal_chado_install_chado_1_11();
  224. }
  225. }
  226. catch (Exception $e) {
  227. $transaction->rollback();
  228. tripal_chado_install_done();
  229. tripal_report_error('tripal_chado', TRIPAL_ERROR, $e->getMessage(), array('print' => TRUE));
  230. return FALSE;
  231. }
  232. return TRUE;
  233. }
  234. /**
  235. * Installs Chado v1.3.
  236. */
  237. function tripal_chado_install_chado_1_3(TripalJob $job = NULL) {
  238. // Get the path to the schema and init SQL files.
  239. $schema_file = drupal_get_path('module', 'tripal_chado') .
  240. '/chado_schema/default_schema-1.3.sql';
  241. $init_file = drupal_get_path('module', 'tripal_chado') .
  242. '/chado_schema/initialize-1.3.sql';
  243. // Erase the Chado schema if it exists and perform the install.
  244. if (tripal_chado_reset_chado_schema()) {
  245. $success = tripal_chado_install_sql($schema_file);
  246. if ($success) {
  247. print "Install of Chado v1.3 (Step 1 of 2) Successful!\n";
  248. }
  249. else {
  250. throw new Exception("Installation (Step 1 of 2) Problems! Please check output above for errors.");
  251. }
  252. $success = tripal_chado_install_sql($init_file);
  253. if ($success) {
  254. print "Install of Chado v1.3 (Step 2 of 2) Successful.\nInstallation Complete\n";
  255. }
  256. else {
  257. throw new Exception("Installation (Step 2 of 2) Problems! Please check output above for errors.");
  258. }
  259. }
  260. else {
  261. throw new Exception("ERROR: cannot install chado. Please check database permissions");
  262. }
  263. }
  264. /**
  265. * Installs Chado v1.2.
  266. */
  267. function tripal_chado_install_chado_1_2() {
  268. // Get the path to the schema and init SQL files.
  269. $schema_file = drupal_get_path('module', 'tripal_chado') .
  270. '/chado_schema/default_schema-1.2.sql';
  271. $init_file = drupal_get_path('module', 'tripal_chado') .
  272. '/chado_schema/initialize-1.2.sql';
  273. // Erase the Chado schema if it exists and perform the install.
  274. if (tripal_chado_reset_chado_schema()) {
  275. $success = tripal_chado_install_sql($schema_file);
  276. if ($success) {
  277. print "Install of Chado v1.2 (Step 1 of 2) Successful!\n";
  278. }
  279. else {
  280. throw new Exception("Installation (Step 1 of 2) Problems! Please check output above for errors.");
  281. }
  282. $success = tripal_chado_install_sql($init_file);
  283. if ($success) {
  284. print "Install of Chado v1.2 (Step 2 of 2) Successful.\nInstallation Complete\n";
  285. }
  286. else {
  287. throw new Exception("Installation (Step 2 of 2) Problems! Please check output above for errors.");
  288. }
  289. }
  290. else {
  291. throw new Exception("ERROR: cannot install chado. Please check database permissions");
  292. }
  293. }
  294. /**
  295. *
  296. */
  297. function tripal_chado_install_chado_1_11() {
  298. // Get the path to the schema and init SQL files.
  299. $schema_file = drupal_get_path('module', 'tripal_chado') .
  300. '/chado_schema/default_schema-1.11.sql';
  301. $init_file = drupal_get_path('module', 'tripal_chado') .
  302. '/chado_schema/initialize-1.11.sql';
  303. // Erase the Chado schema if it exists and perform the install.
  304. if (tripal_chado_reset_chado_schema()) {
  305. $success = tripal_chado_install_sql($schema_file);
  306. if ($success) {
  307. print "Install of Chado v1.11 (Step 1 of 2) Successful!\n";
  308. }
  309. else {
  310. throw new Exception("Installation (Step 1 of 2) Problems! Please check output above for errors.");
  311. }
  312. $success = tripal_chado_install_sql($init_file);
  313. if ($success) {
  314. print "Install of Chado v1.11 (Step 2 of 2) Successful.\nInstallation Complete!\n";
  315. }
  316. else {
  317. throw new Exception("Installation (Step 2 of 2) Problems! Please check output above for errors.");
  318. }
  319. }
  320. else {
  321. throw new Exception("ERROR: cannot install chado. Please check database permissions");
  322. }
  323. }
  324. /**
  325. * Upgrades Chado from v1.2 to v1.3
  326. */
  327. function tripal_chado_upgrade_chado_1_2_to_1_3() {
  328. // Upgrade some of the custom tables that Tripal created that are now in
  329. // Chado v1.3. We'll do this ahead of time because the upgrade script won't
  330. // upgrade tables if they already exist.
  331. print "Checking for existing v1.3 tables in v1.2 and fixing bigints...\n";
  332. tripal_chado_upgrade_chado_1_2_to_1_3_pre_alter();
  333. // Get the path to the diff schema and upgrade SQL files.
  334. print "Incorporating additional changes...\n";
  335. $diff_file = drupal_get_path('module', 'tripal_chado') .
  336. '/chado_schema/default_schema-1.2-1.3-diff.sql';
  337. $success = tripal_chado_install_sql($diff_file);
  338. if ($success) {
  339. print "Upgrade from v1.2 to v1.3 Successful!\n";
  340. }
  341. else {
  342. throw new Exception("Upgrade problems! Please check output above for errors.");
  343. }
  344. }
  345. /**
  346. * Upgrade custom tables that may match the tables now in Chado v1.3.
  347. *
  348. * There were many new tables that were added to Chado v1.3 that were
  349. * suggested by the Chado user community. Some of those were Tripal users.
  350. * Therefore, to help these Tripal users upgrade more seemlessly this function
  351. * checks if those custom tables already exists, and if so updates them as
  352. * best it can to match. At a minimum it will create the table if it doesn't
  353. * exist and if it does it will change the primary keys and foreign keys to
  354. * be big ints.
  355. */
  356. function tripal_chado_upgrade_chado_1_2_to_1_3_pre_alter() {
  357. // Include the Chado v1.3 schema definitions.
  358. module_load_include('inc', 'tripal_chado', '/api/tripal_chado.schema_v1.3.api');
  359. // The list of new tables in Chado v1.3
  360. $new_tables = array('analysis_cvterm', 'analysis_dbxref', 'analysis_pub', 'analysis_relationship',
  361. 'contactprop', 'dbprop', 'feature_contact', 'featuremap_contact', 'featuremap_dbxref',
  362. 'featuremap_organism', 'featuremapprop', 'featureposprop', 'library_contact',
  363. 'library_expression', 'library_expressionprop', 'library_featureprop',
  364. 'library_relationship', 'library_relationship_pub', 'nd_experiment_analysis',
  365. 'organism_cvterm', 'organism_cvtermprop', 'organism_pub', 'organism_relationship',
  366. 'organismprop_pub', 'phenotypeprop', 'phylotreeprop', 'project_analysis',
  367. 'project_dbxref', 'project_feature', 'project_stock', 'pubauthor_contact',
  368. 'stock_feature', 'stock_featuremap', 'stock_library', 'stockcollection_db',
  369. );
  370. // Get the name of the chado schema.
  371. $chado_schema = chado_get_schema_name('chado');
  372. // Iterate through the new Chado tables and create them or if they already
  373. // exist then update them.
  374. foreach ($new_tables as $table) {
  375. // Get the schema for this table.
  376. $function = 'tripal_chado_chado_schema_v1_3_' . $table;
  377. $schema = $function();
  378. // If the table exists then fix the pkeys and fkeys.
  379. if (chado_table_exists($table)) {
  380. // Update the primary key fields to be bigints.
  381. $fields = $schema['fields'];
  382. foreach ($fields as $field_name => $field) {
  383. if ($field['type'] == 'serial') {
  384. if (chado_column_exists($table, $field_name)) {
  385. $sql = 'ALTER TABLE {' . $table . '} ALTER COLUMN ' . $field_name . ' TYPE bigint';
  386. chado_query($sql);
  387. }
  388. else {
  389. throw new Exception('Could not alter primary key to bigint: ' . $table . '.' . $field_name);
  390. }
  391. }
  392. }
  393. // Update the foreign key fields to be bigints.
  394. $fkeys = $schema['foreign keys'];
  395. foreach ($fkeys as $fktable => $details) {
  396. foreach ($details['columns'] as $leftkey => $rightkey) {
  397. if (chado_column_exists($table, $leftkey)) {
  398. $sql = 'ALTER TABLE {' . $table . '} ALTER COLUMN ' . $leftkey . ' TYPE bigint';
  399. chado_query($sql);
  400. }
  401. else {
  402. throw new Exception('Could not alter foreign key to bigint: ' . $table . '.' . $leftkey);
  403. }
  404. }
  405. }
  406. }
  407. }
  408. // Now create the sequences if they don't already exist.
  409. $sequences = array(
  410. 'analysis_cvterm_analysis_cvterm_id_seq',
  411. 'analysis_dbxref_analysis_dbxref_id_seq',
  412. 'analysis_pub_analysis_pub_id_seq',
  413. 'analysis_relationship_analysis_relationship_id_seq',
  414. 'contactprop_contactprop_id_seq',
  415. 'dbprop_dbprop_id_seq',
  416. 'feature_contact_feature_contact_id_seq',
  417. 'featuremap_contact_featuremap_contact_id_seq',
  418. 'featuremap_dbxref_featuremap_dbxref_id_seq',
  419. 'featuremap_organism_featuremap_organism_id_seq',
  420. 'featuremapprop_featuremapprop_id_seq',
  421. 'featureposprop_featureposprop_id_seq',
  422. 'library_contact_library_contact_id_seq',
  423. 'library_expression_library_expression_id_seq',
  424. 'library_expressionprop_library_expressionprop_id_seq',
  425. 'library_featureprop_library_featureprop_id_seq',
  426. 'library_relationship_library_relationship_id_seq',
  427. 'library_relationship_pub_library_relationship_pub_id_seq',
  428. 'nd_experiment_analysis_nd_experiment_analysis_id_seq',
  429. 'organism_cvterm_organism_cvterm_id_seq',
  430. 'organism_cvtermprop_organism_cvtermprop_id_seq',
  431. 'organism_pub_organism_pub_id_seq',
  432. 'organism_relationship_organism_relationship_id_seq',
  433. 'organismprop_pub_organismprop_pub_id_seq',
  434. 'phenotypeprop_phenotypeprop_id_seq',
  435. 'phylotreeprop_phylotreeprop_id_seq',
  436. 'project_analysis_project_analysis_id_seq',
  437. 'project_dbxref_project_dbxref_id_seq',
  438. 'project_feature_project_feature_id_seq',
  439. 'project_stock_project_stock_id_seq',
  440. 'pubauthor_contact_pubauthor_contact_id_seq',
  441. 'stock_feature_stock_feature_id_seq',
  442. 'stock_featuremap_stock_featuremap_id_seq',
  443. 'stock_library_stock_library_id_seq',
  444. 'stockcollection_db_stockcollection_db_id_seq'
  445. );
  446. foreach ($sequences as $sequence) {
  447. // Now add in the sequences if they don't already exist. There is no
  448. // PostgreSQL 'CREATE SEQUENCE IF NOT EXIST' so we're forced to do it here
  449. // and these create statements were removed from the diff upgrade file.
  450. if (!chado_sequence_exists($sequence)) {
  451. $sql = "CREATE SEQUENCE {" . $sequence . "} START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1";
  452. chado_query($sql);
  453. }
  454. }
  455. }
  456. /**
  457. * Upgrades Chado from v1.11 to v1.2
  458. */
  459. function tripal_chado_upgrade_chado_1_11_to_1_2() {
  460. // Get the path to the schema diff and upgarde SQL files.
  461. $schema_file = drupal_get_path('module', 'tripal_chado') . '/chado_schema/default_schema-1.11-1.2-diff.sql';
  462. $init_file = drupal_get_path('module', 'tripal_chado') . '/chado_schema/upgrade-1.11-1.2.sql';
  463. $success = tripal_chado_install_sql($schema_file);
  464. if ($success) {
  465. print "Upgrade from v1.11 to v1.2 (Step 1 of 2) Successful!\n";
  466. }
  467. else {
  468. throw new Exception("Upgrade (Step 1 of 2) problems! Please check output above for errors.");
  469. }
  470. $success = tripal_chado_install_sql($init_file);
  471. if ($success) {
  472. print "Upgrade from v1.11 to v1.2 (Step 2 of 2) Successful.\nUpgrade Complete!\n";
  473. }
  474. else {
  475. throw new Exception("Upgrade (Step 2 of 2) problems! Please check output above for errors.");
  476. }
  477. }
  478. /**
  479. * Reset the Chado Schema
  480. * This drops the current chado and chado-related schema and re-creates it
  481. *
  482. * @ingroup tripal_chado
  483. */
  484. function tripal_chado_reset_chado_schema() {
  485. // determine the schema name.
  486. $chado_schema = chado_get_schema_name('chado');
  487. $chado_dot = $chado_schema . '.';
  488. // drop current chado and chado-related schema
  489. if (chado_dbschema_exists('genetic_code')) {
  490. print "Dropping existing 'genetic_code' schema\n";
  491. db_query("drop schema genetic_code cascade");
  492. }
  493. if (chado_dbschema_exists('so')) {
  494. print "Dropping existing 'so' schema\n";
  495. db_query("drop schema so cascade");
  496. }
  497. if (chado_dbschema_exists('frange')) {
  498. print "Dropping existing 'frange' schema\n";
  499. db_query("drop schema frange cascade");
  500. }
  501. if (chado_dbschema_exists($chado_schema)) {
  502. if ($chado_schema != 'chado') {
  503. print "Dropping existing Chado ('$chado_schema') schema\n";
  504. }
  505. else {
  506. print "Dropping existing 'chado' schema\n";
  507. }
  508. db_query("drop schema $chado_schema cascade");
  509. }
  510. // create the new chado schema
  511. print "Creating 'chado' schema\n";
  512. db_query("create schema $chado_schema");
  513. if (chado_dbschema_exists('chado')) {
  514. // before creating the plpgsql language let's check to make sure
  515. // it doesn't already exists
  516. $sql = "SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql'";
  517. $results = db_query($sql);
  518. $count = $results->fetchObject();
  519. if (!$count or $count->count == 0) {
  520. db_query("create language plpgsql");
  521. }
  522. return TRUE;
  523. }
  524. return FALSE;
  525. }
  526. /**
  527. * Execute the provided SQL
  528. *
  529. * @param $sql_file
  530. * Contains SQL statements to be executed
  531. *
  532. * @ingroup tripal_chado
  533. */
  534. function tripal_chado_install_sql($sql_file) {
  535. $chado_local = chado_dbschema_exists('chado');
  536. // determine the schema name.
  537. $chado_schema = chado_get_schema_name('chado');
  538. $chado_dot = $chado_schema . '.';
  539. if ($chado_local) {
  540. db_query("set search_path to $chado_schema");
  541. }
  542. print "Loading $sql_file...\n";
  543. $lines = file($sql_file, FILE_SKIP_EMPTY_LINES);
  544. if (!$lines) {
  545. return 'Cannot open $schema_file';
  546. }
  547. $stack = array();
  548. $in_string = 0;
  549. $in_function = FALSE;
  550. $query = '';
  551. $i = 0;
  552. $success = 1;
  553. foreach ($lines as $line_num => $line) {
  554. $i++;
  555. $type = '';
  556. // find and remove comments except when inside of strings
  557. if (preg_match('/--/', $line) and !$in_string and !preg_match("/'.*?--.*?'/", $line)) {
  558. $line = preg_replace('/--.*$/', '', $line); // remove comments
  559. }
  560. if (preg_match('/\/\*.*?\*\//', $line)) {
  561. $line = preg_replace('/\/\*.*?\*\//', '', $line); // remove comments
  562. }
  563. // skip empty lines
  564. if (preg_match('/^\s*$/', $line) or strcmp($line, '')==0) {
  565. continue;
  566. }
  567. // Find SQL for new objects
  568. if (preg_match('/^\s*CREATE\s+TABLE/i', $line) and !$in_string and !$in_function) {
  569. $stack[] = 'table';
  570. $line = preg_replace("/public\./", $chado_dot, $line);
  571. }
  572. if (preg_match('/^\s*ALTER\s+TABLE\s+/i', $line) and !$in_string and !$in_function) {
  573. $stack[] = 'alter_table';
  574. $line = preg_replace("/public\./", $chado_dot, $line);
  575. }
  576. if (preg_match('/^\s*SET/i', $line) and !$in_string and !$in_function) {
  577. $stack[] = 'set';
  578. }
  579. if (preg_match('/^\s*CREATE\s+SCHEMA/i', $line) and !$in_string and !$in_function) {
  580. $stack[] = 'schema';
  581. }
  582. if (preg_match('/^\s*CREATE\s+SEQUENCE/i', $line) and !$in_string and !$in_function) {
  583. $stack[] = 'sequence';
  584. $line = preg_replace("/public\./", $chado_dot, $line);
  585. }
  586. if (preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*VIEW/i', $line) and !$in_string and !$in_function) {
  587. $stack[] = 'view';
  588. $line = preg_replace("/public\./", $chado_dot, $line);
  589. }
  590. if (preg_match('/^\s*COMMENT/i', $line) and !$in_string and sizeof($stack)==0 and !$in_function) {
  591. $stack[] = 'comment';
  592. $line = preg_replace("/public\./", $chado_dot, $line);
  593. }
  594. if (preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*FUNCTION/i', $line) and !$in_string and !$in_function) {
  595. $in_function = TRUE;
  596. $stack[] = 'function';
  597. $line = preg_replace("/public\./", $chado_dot, $line);
  598. }
  599. if (preg_match('/^\s*CREATE\s+INDEX/i', $line) and !$in_string and !$in_function) {
  600. $stack[] = 'index';
  601. }
  602. if (preg_match('/^\s*INSERT\s+INTO/i', $line) and !$in_string and !$in_function) {
  603. $stack[] = 'insert';
  604. $line = preg_replace("/public\./", $chado_dot, $line);
  605. }
  606. if (preg_match('/^\s*CREATE\s+TYPE/i', $line) and !$in_string and !$in_function) {
  607. $stack[] = 'type';
  608. }
  609. if (preg_match('/^\s*GRANT/i', $line) and !$in_string and !$in_function) {
  610. $stack[] = 'grant';
  611. }
  612. if (preg_match('/^\s*CREATE\s+AGGREGATE/i', $line) and !$in_string and !$in_function) {
  613. $stack[] = 'aggregate';
  614. }
  615. if (preg_match('/^\s*DROP\s+FUNCTION/i', $line) and !$in_string and !$in_function) {
  616. $stack[] = 'drop_function';
  617. }
  618. if (preg_match('/^\s*DROP\s+VIEW/i', $line) and !$in_string and !$in_function) {
  619. $stack[] = 'drop_view';
  620. }
  621. if (preg_match('/^\s*DROP\s+INDEX/i', $line) and !$in_string and !$in_function) {
  622. $stack[] = 'drop_index';
  623. }
  624. if (preg_match('/^\s*DROP\s+SEQUENCE/i', $line) and !$in_string and !$in_function) {
  625. $stack[] = 'drop_seq';
  626. }
  627. if (preg_match('/^\s*ALTER\s+TYPE\s+/i', $line) and !$in_string and !$in_function) {
  628. $stack[] = 'alter_type';
  629. }
  630. if (preg_match('/^\s*ALTER\s+SEQUENCE\s+/i', $line) and !$in_string and !$in_function) {
  631. $stack[] = 'alter_seq';
  632. }
  633. // determine if we are in a string that spans a line
  634. $matches = preg_match_all("/[']/i", $line, $temp);
  635. $in_string = $in_string - ($matches % 2);
  636. $in_string = abs($in_string);
  637. // if we've reached the end of an object then pop the stack
  638. if (strcmp($stack[sizeof($stack)-1], 'table') == 0 and preg_match('/\);\s*$/', $line)) {
  639. $type = array_pop($stack);
  640. }
  641. elseif (strcmp($stack[sizeof($stack)-1], 'alter_table') == 0 and preg_match('/;\s*$/', $line)) {
  642. $type = array_pop($stack);
  643. }
  644. elseif (strcmp($stack[sizeof($stack)-1], 'set') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
  645. $type = array_pop($stack);
  646. }
  647. elseif (strcmp($stack[sizeof($stack)-1], 'schema') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
  648. $type = array_pop($stack);
  649. }
  650. elseif (strcmp($stack[sizeof($stack)-1], 'sequence') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
  651. $type = array_pop($stack);
  652. }
  653. elseif (strcmp($stack[sizeof($stack)-1], 'view') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
  654. $type = array_pop($stack);
  655. }
  656. elseif (strcmp($stack[sizeof($stack)-1], 'comment') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
  657. $type = array_pop($stack);
  658. }
  659. elseif (strcmp($stack[sizeof($stack)-1], 'function') == 0) {
  660. if(preg_match('/LANGUAGE.*?;\s*$/i', $line)) {
  661. $type = array_pop($stack);
  662. $in_function = FALSE;
  663. //print "FUNCTION DONE ($i): $line";
  664. }
  665. else if(preg_match('/\$_\$;\s*$/i', $line)) {
  666. $type = array_pop($stack);
  667. $in_function = FALSE;
  668. //print "FUNCTION DONE ($i): $line";
  669. }
  670. else if(preg_match('/\$\$;\s*$/i', $line)) {
  671. $type = array_pop($stack);
  672. $in_function = FALSE;
  673. // print "FUNCTION DONE ($i): $line";
  674. }
  675. else {
  676. // print "FUNCTION ($i): $line";
  677. }
  678. }
  679. elseif (strcmp($stack[sizeof($stack)-1], 'index') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
  680. $type = array_pop($stack);
  681. }
  682. elseif (strcmp($stack[sizeof($stack)-1], 'insert') == 0 and preg_match('/\);\s*$/', $line)) {
  683. $type = array_pop($stack);
  684. }
  685. elseif (strcmp($stack[sizeof($stack)-1], 'type') == 0 and preg_match('/\);\s*$/', $line)) {
  686. $type = array_pop($stack);
  687. }
  688. elseif (strcmp($stack[sizeof($stack)-1], 'grant') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
  689. $type = array_pop($stack);
  690. }
  691. elseif (strcmp($stack[sizeof($stack)-1], 'aggregate') == 0 and preg_match('/\);\s*$/', $line)) {
  692. $type = array_pop($stack);
  693. }
  694. elseif (strcmp($stack[sizeof($stack)-1], 'drop_function') == 0 and preg_match('/;\s*$/i', $line)) {
  695. $type = array_pop($stack);
  696. }
  697. elseif (strcmp($stack[sizeof($stack)-1], 'drop_view') == 0 and preg_match('/;\s*$/i', $line)) {
  698. $type = array_pop($stack);
  699. }
  700. elseif (strcmp($stack[sizeof($stack)-1], 'drop_index') == 0 and preg_match("/;\s*$/i", $line)) {
  701. $type = array_pop($stack);
  702. }
  703. elseif (strcmp($stack[sizeof($stack)-1], 'drop_seq') == 0 and preg_match("/;\s*$/i", $line)) {
  704. $type = array_pop($stack);
  705. }
  706. elseif (strcmp($stack[sizeof($stack)-1], 'alter_type') == 0 and preg_match('/;\s*$/i', $line)) {
  707. $type = array_pop($stack);
  708. }
  709. elseif (strcmp($stack[sizeof($stack)-1], 'alter_seq') == 0 and preg_match('/;\s*$/i', $line)) {
  710. $type = array_pop($stack);
  711. }
  712. // if we're in a recognized SQL statement then let's keep track of lines
  713. if ($type or sizeof($stack) > 0) {
  714. $query .= "$line";
  715. }
  716. else {
  717. throw new Exception("UNHANDLED $i, $in_string: $line");
  718. }
  719. if (preg_match_all("/\n/", $query, $temp) > 1000) {
  720. throw new Exception("SQL query is too long. Terminating:\n$query\n");
  721. }
  722. if ($type and sizeof($stack) == 0) {
  723. //print "Adding $type: line $i\n";
  724. // rewrite the set search_path to make 'public' be 'chado', but only if the
  725. // chado schema exists
  726. if (strcmp($type, 'set') == 0 and $chado_local) {
  727. $query = preg_replace("/public/m", $chado_schema, $query);
  728. }
  729. // execute the statement
  730. try {
  731. $result = db_query($query);
  732. }
  733. catch (Exception $e) {
  734. $error = $e->getMessage();
  735. throw new Exception("FAILED. Line $i, $in_string\n$error:\n$query\n\n");
  736. }
  737. if (!$result) {
  738. $error = pg_last_error();
  739. throw new Exception("FAILED. Line $i, $in_string\n$error:\n$query\n\n");
  740. }
  741. $query = '';
  742. }
  743. }
  744. tripal_chado_install_done();
  745. return $success;
  746. }
  747. /**
  748. * Finish the Chado Schema Installation
  749. *
  750. * @ingroup tripal_chado
  751. */
  752. function tripal_chado_install_done() {
  753. $drupal_schema = chado_get_schema_name('drupal');
  754. db_query("set search_path to $drupal_schema");
  755. }