copy_tabs.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <grass/gis.h>
  2. #include <grass/vector.h>
  3. #include <grass/dbmi.h>
  4. #include <grass/glocale.h>
  5. #include "proto.h"
  6. void copy_tabs(struct Map_info *In, struct Map_info *Out,
  7. int nfields, int *fields, int *ncats, int **cats)
  8. {
  9. int i, ttype, ntabs;
  10. struct field_info *IFi, *OFi;
  11. ntabs = 0;
  12. G_message(_("Writing attributes..."));
  13. /* Number of output tabs */
  14. for (i = 0; i < Vect_get_num_dblinks(In); i++) {
  15. int j, f=0;
  16. IFi = Vect_get_dblink(In, i);
  17. for (j = 0; j < nfields; j++) { /* find field */
  18. if (fields[j] == IFi->number) {
  19. f = j;
  20. break;
  21. }
  22. }
  23. if (ncats[f] > 0)
  24. ntabs++;
  25. }
  26. if (ntabs > 1)
  27. ttype = GV_MTABLE;
  28. else
  29. ttype = GV_1TABLE;
  30. for (i = 0; i < nfields; i++) {
  31. int ret;
  32. dbDriver *Driver;
  33. if (fields[i] == 0)
  34. continue;
  35. /* Make a list of categories */
  36. IFi = Vect_get_field(In, fields[i]);
  37. if (!IFi) { /* no table */
  38. G_warning(_("No table for layer %d"), fields[i]);
  39. continue;
  40. }
  41. OFi =
  42. Vect_default_field_info(Out, IFi->number, IFi->name, ttype);
  43. if (ncats[i] > 0)
  44. ret = db_copy_table_by_ints(IFi->driver, IFi->database, IFi->table,
  45. OFi->driver,
  46. Vect_subst_var(OFi->database, Out),
  47. OFi->table, IFi->key, cats[i],
  48. ncats[i]);
  49. else
  50. ret = db_copy_table_where(IFi->driver, IFi->database, IFi->table,
  51. OFi->driver,
  52. Vect_subst_var(OFi->database, Out),
  53. OFi->table, "0 = 1");
  54. if (ret == DB_FAILED) {
  55. G_warning(_("Unable to copy table for layer %d"), fields[i]);
  56. }
  57. else {
  58. Vect_map_add_dblink(Out, OFi->number, OFi->name, OFi->table,
  59. IFi->key, OFi->database, OFi->driver);
  60. }
  61. /* create index on key column */
  62. Driver = db_start_driver_open_database(OFi->driver,
  63. Vect_subst_var(OFi->database, Out));
  64. if (Driver == NULL)
  65. G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
  66. OFi->database, OFi->driver);
  67. db_set_error_handler_driver(Driver);
  68. if (db_create_index2(Driver, OFi->table, IFi->key) != DB_OK)
  69. G_warning(_("Unable to create index"));
  70. if (db_grant_on_table
  71. (Driver, OFi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK)
  72. G_fatal_error(_("Unable to grant privileges on table <%s>"),
  73. OFi->table);
  74. db_close_database_shutdown_driver(Driver);
  75. }
  76. }