baseten / Sources / BaseTen.h

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 // // BaseTen.h // BaseTen // // Copyright (C) 2006-2008 Marko Karppinen & Co. LLC. // // Before using this software, please review the available licensing options // by visiting http://basetenframework.org/licensing/ or by contacting // us at sales@karppinen.fi. Without an additional license, this software // may be distributed only in compliance with the GNU General Public License. // // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License, version 2.0, // as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // $Id$ // #import #import #import #import #import #import #import #import #import #import #import #import #import /* * Helpful breakpoints: * * BXHandleError2 * bx_error_during_rollback * bx_error_during_clear_notification * bx_test_failed * pgts_unrecognized_selector */ /** * \defgroup baseten BaseTen * BaseTen is linked to Foundation, CoreData, Security, IOKit and SystemConfiguration frameworks and * libcrypto, libssl and libstdc++ dynamic libraries. In addition, it is weakly linked to AppKit framework. * Therefore it can be used to develop applications that don't require the graphical user interface. */ /** * \defgroup descriptions Descriptions * \ingroup baseten * Database introspection. */ /** * \defgroup auto_containers Self-updating collections * \ingroup baseten * Collections updated by the database context. * The context will change the collection's contents according to its filter predicate * after each relevant modification to the database. */ /** * \mainpage Introduction * * BaseTen is an open source Cocoa database framework for working with PostgreSQL databases. BaseTen * has been designed with familiar, Core Data -like semantics and APIs. * * The BaseTen feature highlights include: * \li BaseTen Assistant imports Core Data / Xcode data models. * \li Discovers the database schema automatically at runtime, including 1-1, 1-many and many-many relationships. * \li Database changes are propagated to clients automatically, without polling. * \li In-memory database objects are uniqued, and objects fetched via relationships are faults by default. * \li Support for RDBMS features like database-driven data validation, multi-column primary keys and updateable views. * \li Autocommit and manual save/rollback modes, both with NSUndoManager integration. * \li A BaseTen-aware NSArrayController subclass automates locking and change propagation. * \li Fetches are specified with NSPredicates (the relevant portions of which are evaluated on the database). */ /** * \page general_usage Using BaseTen framework * * \latexonly \section*{Topics} \endlatexonly * \li \subpage overview * \li \subpage baseten_assistant * \li \subpage getting_started * \li \subpage accessing_values * \li \subpage sql_views * \li \subpage database_types * \li \subpage relationships * \li \subpage predicates * \li \subpage tracking_changes * \li \subpage using_appkit_classes * \li \subpage autocommit_manual_commit * \li \subpage thread_safety * \li \subpage multiple_contexts * \li \subpage linking_to_baseten * \li \subpage building_baseten */ /** * \page overview Overview of BaseTen * * BaseTen aims to provide a Core Data -like API for handling a database. A database connection is managed * by an instance of BXDatabaseContext, which also fetches rows from the database. Rows are represented * by instances of BXDatabaseObject. Objects are identified by * \link BXDatabaseObjectID BXDatabaseObjectIDs\endlink, that are created using * tables' primary keys. Foreign keys are interpreted as relationships between objects. * * Like some other object-relational mappers, BaseTen fetches the data model from the database. * There are classes available for database introspection: BXEntityDescription, BXAttributeDescription, * BXRelationshipDescription and its subclasses. * * Database objects are retrieved using an instance of BXDatabaseContext. The rows are specified using * instances of BXEntityDescription and NSPredicate. This pattern should match most use cases. It is also * possible to fetch rows as NSDictionaries by specifying an SQL query. * * Unlike the typical use case of Core Data, multiple users might be connected to the database being * accessed using BaseTen. Thus, data manipulated with database objects could change at any time. BaseTen * copes with this situation by updating objects' contents as soon as other database clients commit their * changes. The other clients needn't use BaseTen. * * Instead of constantly polling the database for changes, BaseTen listens for PostgreSQL notifications. * It then queries the database about the notification type and faults the relevant objects. For this to * work, certain tables, views and functions need to be created in the database. The easiest way to do this * is to connect to the database with BaseTen Assistant. Using it, relations may be enabled for use with * the framework. Everything will be installed or will reference to a database schema called baseten, so * removal, if needed, will be an easy process. BaseTen can connect to databases without the schema, but * in this case functionality will be limited. * * Since BaseTen relies on database introspection, SQL may be used to define the database schema. * Another option is to create a data model using Xcode's data modeler and import it using BaseTen Assistant. * * \image html object-relationships.png "Relationships between BaseTen's objects" * \image html class-hierarchy.png "BaseTen class hierarchy" * \image latex object-relationships.pdf "Relationships between BaseTen's objects" width=\textwidth * \image latex class-hierarchy.pdf "BaseTen class hierarchy" width=\textwidth */ /** * \page baseten_assistant BaseTen Assistant * * BaseTen Assistant is a simple database management application distributed with BaseTen framework. It has its own help that is available from within the application. * In short, it has the following features: * \li It can be used to enable or disable tables and views for use with BaseTen. * \li It can refresh the tables that BaseTen uses to determine relationships between entities. * \li It can list entities' attributes and relationships as they are available when using the framework. * \li It can create a database schema from an Xcode data model. * \li It can create a chart of the database schema that can be displayed using Graphviz or OmniGraffle. */ /** * \page getting_started Getting started * * Typically accessing a database consists roughly of the following steps: *
*
• \ref creating_a_database_context "Creating an instance of BXDatabaseContext"
• *
• \ref connecting_to_a_database "Connecting to a database"
• *
• \ref getting_an_entity_and_a_predicate "Getting an entity description from the context and possibly creating an NSPredicate for reducing the number of fetched objects"
• *
• \ref performing_a_fetch "Performing a fetch using the entity and the predicate"
• *
• \ref handling_the_results "Handling the results"
• *
• \ref creating_objects "Creating new objects"
• *
* Here is a small walkthrough with sample code. More examples are available in the BaseTen Subversion repository and at http://basetenframework.org. * * \latexonly * \lstset{language=[Objective]C, backgroundcolor=\color[rgb]{0.84,0.87,0.90}, rulecolor=\color[gray]{0.53}, frame=single, framesep=0pt, framextopmargin=2pt, framexbottommargin=2pt, fontadjust, columns=fullflexible, captionpos=b} * \begin{lstlisting}[caption=A simple command line tool that uses BaseTen] * #import * #import * * int main (int argc, char** argv) * { * NSURL* databaseURI = [NSURL URLWithString: @"pgsql://username@localhost/database"]; * BXDatabaseContext* ctx = [[BXDatabaseContext alloc] initWithDatabaseURI: databaseURI]; * * [ctx connectSync: NULL]; * BXEntityDescription* entity = [[ctx databaseObjectModel] entityForTable: @"table"]; * NSArray* result = [ctx executeFetchForEntity: entity withPredicate: nil error: NULL]; * * for (BXDatabaseObject* object in result) * { * NSLog (@"Object ID: %@ column: %@", * [[object objectID] URIRepresentation], [object valueForKey: @"column"]); * } * * NSDictionary* values = [NSDictionary dictionaryWithObject: @"newValue" forKey: @"column"]; * BXDatabaseObject* newObject = [ctx createObjectForEntity: entity * withFieldValues: values error: NULL]; * NSLog (@"new object: %@", newObject); * * return 0; * } * \end{lstlisting} * \endlatexonly * \htmlonly * #import <Foundation/Foundation.h> * #import <BaseTen/BaseTen.h> * * int main (int argc, char** argv) * { * NSURL* databaseURI = [NSURL URLWithString: @"pgsql://username@localhost/database"]; * BXDatabaseContext* ctx = [[BXDatabaseContext alloc] initWithDatabaseURI: databaseURI]; * * [ctx connectSync: NULL]; * BXEntityDescription* entity = [[ctx databaseObjectModel] entityForTable: @"table"]; * NSArray* result = [ctx executeFetchForEntity: entity withPredicate: nil error: NULL]; * * for (BXDatabaseObject* object in result) * { * NSLog (@"Object ID: %@ column: %@", * [[object objectID] URIRepresentation], [object valueForKey: @"column"]); * } * * NSDictionary* values = [NSDictionary dictionaryWithObject: @"newValue" forKey: @"column"]; * BXDatabaseObject* newObject = [ctx createObjectForEntity: entity withFieldValues: values error: NULL]; * NSLog (@"new object: %@", newObject); * * return 0; * } * \endhtmlonly * * * \section creating_a_database_context Creating a database context * * The designated initializer of BXDatabaseContext is * \ref BXDatabaseContext::initWithDatabaseURI: "-initWithDatabaseURI:". \ref BXDatabaseContext::init "-init" * is also available but the context does require an URI before connecting. * * BXDatabaseContext requires the URI to be formatted as follows:
* pgsql://username:password\@host/database_name. Currently, as PostgreSQL is the only supported * database, only pgsql:// URIs are allowed. In command line tools, all parameters are required * except for the password, the need for which depends on the database configuration. * * Various methods in BXDatabaseContext take a double pointer to an NSError object as a parameter. if the * called method fails, the NSError will be set on return. If the parameter is NULL, the default error * handler raises a BXException. BXDatabaseContext's delegate may change this behaviour. * * * \section connecting_to_a_database Connecting to a database * * \latexonly * \begin{lstlisting} * [ctx connectSync: NULL]; * \end{lstlisting} * \endlatexonly * \htmlonly * [ctx connectSync: NULL]; * \endhtmlonly * * Connection to the database may be made synchronously using the method * \ref BXDatabaseContext::connectSync: "-connectSync". Applications that use an NSRunLoop also have the * option to use \ref BXDatabaseContext::connectAsync "-connectAsync". The method returns immediately. * When the connection attempt has finished, the context's delegate will be called and notifications will * be posted to the context's notification center (accessed with * \ref BXDatabaseContext::notificationCenter "-notificationCenter"). * * In AppKit applications, the easiest way to connect to the database is to use the IBAction * \ref BXDatabaseContext::connect: "-connect:". In addition to attempting the connection asynchronously, * it also presents a number of panels to the user, if some required information is missing from the URI. * The panels allow the user to specify their username, password and the database host making URIs * like pgsql:///database_name allowed. Additionally a kBXConnectionSetupAlertDidEndNotification * will be posted when the user dismisses an alert panel, which is presented on failure. * * Since NULL is passed in place of an NSError double pointer, a BXException will be thrown on error. * See BXDatabaseContext's documentation for details on error handling. * * * \section getting_an_entity_and_a_predicate Getting a BXEntityDescription and an NSPredicate * * \latexonly * \begin{lstlisting} * BXEntityDescription* entity = [[ctx databaseObjectModel] entityForTable: @"table"]; * \end{lstlisting} * \endlatexonly * \htmlonly * BXEntityDescription* entity = [[ctx databaseObjectModel] entityForTable: @"table"]; * \endhtmlonly * * BXEntityDescriptions are used to specify tables for fetches. For getting a specific * entity description, BXDatabaseObjectModel has two methods: * -entityForTable: * and * -entityForTable:inSchema:. * Entity descriptions may be accessed before making a * connection in which case the database context will check their existence on connect. * * NSPredicates are created by various Cocoa objects and may be passed directly to BXDatabaseContext. * One way to create ad-hoc predicates is by using NSPredicate's method -predicateWithFormat:. * In this example, we fetch all the objects instead of filtering them, though. * * * \section performing_a_fetch Performing a fetch using the entity and the predicate * * \latexonly * \begin{lstlisting} * NSArray* result = [ctx executeFetchForEntity: entity withPredicate: nil error: NULL]; * \end{lstlisting} * \endlatexonly * \htmlonly * NSArray* result = [ctx executeFetchForEntity: entity withPredicate: nil error: NULL]; * \endhtmlonly * * BXDatabaseContext's method * -executeFetchForEntity:withPredicate:error: * and its variations may be used to fetch objects from the database. The method takes a BXEntityDescription * and an NSPredicate and performs a fetch synchronously. The fetched objects are returned in an NSArray. * * * \section handling_the_results Handling the results * * \latexonly * \begin{lstlisting} * for (BXDatabaseObject* object in result) * { * NSLog (@"Object ID: %@ column: %@", * [[object objectID] URIRepresentation], [object valueForKey: @"column"]); * } * \end{lstlisting} * \endlatexonly * \htmlonly * for (BXDatabaseObject* object in result) *{ * NSLog (@"Object ID: %@ column: %@", * [[object objectID] URIRepresentation], [object valueForKey: @"column"]); *} * \endhtmlonly * * Since BXDatabaseObject conforms to NSKeyValueObserving, methods -valueForKey: and * -setValue:forKey: are available. See \ref accessing_values for details. * * * \section creating_objects Creating a new object * * \latexonly * \begin{lstlisting} * NSDictionary* values = [NSDictionary dictionaryWithObject: @"newValue" forKey: @"column"]; * BXDatabaseObject* newObject = [ctx createObjectForEntity: entity * withFieldValues: values error: NULL]; * NSLog (@"new object: %@", newObject); * \end{lstlisting} * \endlatexonly * \htmlonly * NSDictionary* values = [NSDictionary dictionaryWithObject: @"newValue" forKey: @"column"]; * BXDatabaseObject* newObject = [ctx createObjectForEntity: entity withFieldValues: values error: NULL]; * NSLog (@"new object: %@", newObject); * \endhtmlonly * * New rows are inserted with BXDatabaseContext's method -createObjectForEntity:withFieldValues:error:. * The values dictionary may contain initial values for both attributes and to-one relationships in * case the target entity contains the foreign key. */ /** * \page accessing_values Accessing object values * * BXDatabaseObjects implement NSKeyValueCoding and object values may thus be accessed with * -valueForKey: and -setValue:forKey:. The key will be the column name. As with * NSManagedObject, methods like -key and -setKey: are also automatically available. * * Column values are converted to Foundation objects based on the column type. Currently, there is no way to * affect the type conversion. Instead, custom getters may be written for preprocessing * fetched objects. To support this, the column values may also be accessed using * \ref BXDatabaseObject::primitiveValueForKey: "-primitiveValueForKey:". Similarly * -setPrimitiveValue:forKey: may be used to set a column value. * * Currently handled data types are listed in \ref database_types. * * * \latexonly * \begin{sidewaysfigure} * \endlatexonly * \image latex update-change-propagation.eps "Objects being accessed by other clients are automatically faulted as part of the update process." width=\textheight * \latexonly * \end{sidewaysfigure} * \endlatexonly * \image html update-change-propagation.png "Objects being accessed by other clients are automatically faulted as part of the update process" */ /** * \page sql_views SQL views * * Contents of SQL views may be manipulated using database objects provided that some conditions are met. * Unlike tables, views don't have primary keys but BaseTen still needs to be able to reference individual * rows. If a view has a group of columns that can act as a primary key, the columns may be marked as a * primary key with the assistant, after which the view may be enabled. * * Views also lack foreign keys. Despite this entities that correspond to views may have relationships * provided that a certain condition is met: the view needs to have the column or columns of an underlying * table that form a foreign key, and the columns' names need to match. In this case, relationships will * be created between the view and the target table as well as the view and all the views that are based * on the target table and contain the columns the foreign key references to. This applies to the complete * view hierarchy. * * PostgreSQL allows INSERT and UPDATE queries to target views if rules have been created to handle them. * In this case, the view contents may be modified also with BaseTen. */ /** * \page database_types Handled PostgreSQL types * * Composite types, domains and types not listed here are currently returned as NSData. * Array types are returned as NSArrays of the respective type or NSArrays of NSData objects. * * *
Type conversion *
PostgreSQL typeCocoa type
aclitem(A private class)
bigint, bigserialNSNumber
bitNSString
booleanNSNumber
byteaNSData
char, bpcharNSString
dateNSDate
decimal, numericNSDecimalNumber
double precisionNSNumber
int2vectorNSArray of NSNumbers
integer, serialNSNumber
nameNSString
oidNSNumber
pointNSValue
realNSNumber
smallintNSNumber
textNSString
timeNSDate
time with time zoneNSDate
timestampNSDate
timestamp with time zoneNSDate
varbitNSString
varcharNSString
uuidNSString
xmlNSData or NSXMLDocument
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \section string_handling String types * * When NSStrings are passed to the database, they are normalized to Unicode NFD. In case the database's encoding isn't Unicode (UTF-8), PostgreSQL will handle the * conversion. * * Even if the database's encoding is Unicode, PostgreSQL compares bytes, not Unicode characters, in strings as of version 8.3. * Thus, comparison within the database could fail when done with non-normalized strings or strings in NFC. * * * * * \section date_handling Date and time types * * Cocoa's and Core Foundation's date classes store the date as seconds from a reference date, 2001-01-01 00:00:00 UTC. SQL times and timestamps, on the other hand, might have * an associated time zone specified as an offset to GMT. In PostgreSQL 8.3, removing the time zone information by casting truncates the value. Casting a time or a timestamp * lacking a time zone assigns the current time zone to it instead of converting. * * BaseTen does several things to cope with this: * \li It sets the connection's time zone to UTC. * \li It assigns UTC to times and timestamps that don't have a time zone. * \li It converts received times and timestamps in other time zones to UTC. * \li NSCalendarDates passed as parameters will be converted to UTC. * * Therefore, NSDates received from the server should in fact contain the offset from their point in time to the reference date. To ease handling, the date is set to * 2001-01-01 in case of time types. This allows -[NSDate timeIntervalSinceReferenceDate] to return the time's difference to midnight in seconds. * * NSDates are converted to their date representation using NSCalendar and its underlying ICU library. ICU specifies a single cut-over date for the switch from Julian to * Gregorian calendar, which is 1582-10-04. (It isn't currently possible to specify a different cut-over date to NSCalendar.) NSDates before this point will be converted * to Julian calendar dates. The rationale for this is that timestamps can't be passed directly to PostgreSQL, and NSCalendar seems to be the best option for representing * timestamps as dates. PostgreSQL, on the other hand, uses Julian days (number of days since January 1, 4713 BCE with fraction, length of the year specified as 365.2425 * days) for date calculations, and most likely converts them to Gregorian calendar dates for presentation. Thus, your mileage may vary when calculating dates within * the database. * * \note In versions earlier than 1.7, date handling depended on several factors, such as the current time zone and the server's time zone. This is no longer the case. Also, all * date and time types are currently returned as NSDate, not NSCalendarDate. * * * \section xml_handling The XML type * * PostgreSQL's xml data type handles both XML documents and content fragments. BaseTen creates NSData objects from them by default, but if the * table also has a constraint like CHECK (xml_column IS DOCUMENT), NSXMLDocuments will be created instead. The constraint mustn't * contain any other conditions, but there may be additional CHECK constraints. * * * \section custom_database_types Requirements for custom base data types * * In case of BaseTen-enabled tables, column contents are compared on update to determine, which columns did actually change. * Thus, any custom base data types (created with CREATE TYPE) used in these tables need to have the equality * operator =. Currently, the operator needs to be accessible using the default search path. In case the custom type * is such that the concept of equality doesn't apply, the operator may always return false. In this case * the value for the column will always be fetched when the corresponding row changes. * * BaseTen provides custom equality operators for PostgreSQL's geometric types, * for which the default equality operator would only compare equal areas. */ /** * \page relationships Relationships * * BaseTen supports the same types of relationships as Core Data: one-to-one, one-to-many and many-to-many. * After BaseTen schema has been installed, * relationships are created using foreign keys as shown in the following table. * * * Required conditions for relationsips *
Relationship typeRequired conditions
One-to-manyA foreign key constraint on the many-side.
One-to-oneA foreign key constraint the columns of which also have an unique constraint.
Many-to-manyA helper table that has foreign keys referencing two other tables. The foreign key columns also need to form the table's primary key.
* * * * * * * * * * * * * * * * * * \note Before BaseTen 1.8, relationships were only available in enabled tables and views. * * * \section relationship_naming Relationship naming * * Relationship names are determined from foreign key names. For one-to-one and one-to-many * relationships, the foreign key's name should have the form name1__name2, where name1 is * the relationship's name from the foreign key's side, and name2 is the inverse relationship's * name. If the foreign key's name doesn't contain two consecutive underscores, a generated name is * used for the inverse relationship. Similarly, if the foreign key's name begins with two * underscores, a generated name is used for the relationship. The generated name has the format * schema_table_foreignkey. * * Many-to-many relationships have the same name as the foreign key that references the target table. * * BaseTen Assistant generates foreign keys with names like this, but if creating or altering the * database schema isn't an option, a set of identical relationships is created with different names. * Each relationship has the same name as the target table, with the word “Set” appended in the case * of to-many relationships. * * The latter naming is also available with views, while the former is not. * * In case the two relationships created into the same entity have matching names, the one named * after the table and its inverse relationship are removed. In case two relationships created into * one entity using different foreign keys have matching names, they will both be removed with their * inverse relationships. * * * Relationship names *
Relationship typeAvailable names
One-to-many (inverse, from the foreign key's side)targetSet, first part of the foreign key's name
One-to-many (from the referenced side)target, second part of the foreign key's name
One-to-one (from the foreign key's side)target, first part of the foreign key's name
One-to-one (from the referenced side)target, second part of the foreign key's name
Many-to-manytargetSet, name of the foreign key that references the target table
* * * * * * * * * * * * * * * * * * * * * * * * * * \note The relationship names used before version 1.7 are still available. They won't be listed * by BaseTen Assistant, though, and using them will call \ref BXDeprecationWarning. * * * \section relationship_naming_example Relationship example * * Consider the following case: * \latexonly * \lstset{language=SQL, backgroundcolor=\color[rgb]{0.84,0.87,0.90}, rulecolor=\color[gray]{0.53}, frame=single, framesep=0pt, framextopmargin=2pt, framexbottommargin=2pt, fontadjust, columns=fullflexible, captionpos=b} * \begin{lstlisting}[caption=Tables with a one-to-many relationship] * CREATE TABLE person ( * id SERIAL PRIMARY KEY, * firstname VARCHAR (255), * surname VARCHAR (255) * ); * * CREATE TABLE email ( * id SERIAL PRIMARY KEY, * address VARCHAR (255), * person_id INTEGER REFERENCES person (id) * ); * \end{lstlisting} * \endlatexonly * \htmlonly * CREATE TABLE person ( * id SERIAL PRIMARY KEY, * firstname VARCHAR (255), * surname VARCHAR (255) * ); * * CREATE TABLE email ( * id SERIAL PRIMARY KEY, * address VARCHAR (255), * person_id INTEGER REFERENCES person (id) * ); * \endhtmlonly * * Lets say we have two objects: aPerson and anEmail which have been fetched from the person and email * tables, respectively.
* [aPerson valueForKey:\@"emailSet"] will now return a collection of email objects.
* [anEmail valueForKey:\@"person"] will return a single person object. * * If we modify the previous example by adding an unique constraint, we get a one-to-one relationship: * * \latexonly * \begin{lstlisting} * ALTER TABLE email ADD UNIQUE (person_id); * \end{lstlisting} * \endlatexonly * \htmlonly * ALTER TABLE email ADD UNIQUE (person_id); * \endhtmlonly * * Now both of the following messages will return a single object from the corresponding table:
* [aPerson valueForKey:\@"email"]
* [anEmail valueForKey:\@"person"] * * Many-to-many relationships are modeled with helper tables. The helper table needs to have columns to contain * both tables' primary keys. * * Another example: * \latexonly * \begin{lstlisting}[caption=Tables with a many-to-many relationship] * CREATE TABLE person ( * id SERIAL PRIMARY KEY, * firstname VARCHAR (255), * surname VARCHAR (255) * ); * * CREATE TABLE title ( * id SERIAL PRIMARY KEY, * name VARCHAR (255) * ); * * CREATE TABLE person_title_rel ( * person_id INTEGER REFERENCES person (id), * title_id INTEGER REFERENCES title (id), * PRIMARY KEY (person_id, title_id) * ); * \end{lstlisting} * \endlatexonly * \htmlonly *CREATE TABLE person ( * id SERIAL PRIMARY KEY, * firstname VARCHAR (255), * surname VARCHAR (255) *); * *CREATE TABLE title ( * id SERIAL PRIMARY KEY, * name VARCHAR (255) *); * *CREATE TABLE person_title_rel ( * person_id INTEGER REFERENCES person (id), * title_id INTEGER REFERENCES title (id), * PRIMARY KEY (person_id, title_id) *); * \endhtmlonly * * Lets say aPerson has been fetched from the person table and aTitle from the title table. * In this case,
* [aPerson valueForKey:\@"titleSet"] will return a collection of title objects and
* [aTitle valueForKey:\@"personSet"] a collection of person objects.
* Any two foreign keys * in one table will be interpreted as a many-to-many relationship, if they also form the table's * primary key. Objects from the helper table may be retrieved as with one-to-many relationships:
* [aPerson valueForKey:\@"person_title_relSet"]. */ /** * \page predicates Predicates * * Cocoa predicates are used to fetch objects that match certain criteria. Key paths in predicates * correspond to entity attributes and relationships. * * Most types of predicates and expressions are converted to SQL and sent to the database server. * Others cause the returned object set to be filtered again on the client side. Specifically, the following * use cases work in this manner: The affected part of the predicate is replaced with true (or false, * if the part is inside an odd number of NOT predicates), and excess objects are removed from the result set * after it has been received. * *
*
• Use of NSCustomSelectorPredicateOperatorType
• *
• A modifier other than NSDirectPredicateModifier in combination with any of the following: *
*
• NSBeginsWithPredicateOperatorType
• *
• NSEndsWithPredicateOperatorType
• *
• NSMatchesPredicateOperatorType
• *
• NSLikePredicateOperatorType
• *
• NSContainsPredicateOperatorType
• *
• NSInPredicateOperatorType
• *
*
• *
• Use of any of the following predicate options: *
*
• NSDiacriticInsensitivePredicateOption
• *
• NSNormalizedPredicateOption
• *
• NSLocaleSensitivePredicateOption
• *
*
• *
• Use of any of the following expression types: *
*
• NSSubqueryExpressionType
• *
• NSUnionSetExpressionType
• *
• NSIntersectSetExpressionType
• *
• NSMinusSetExpressionType
• *
• NSBlockExpressionType
• *
*
• *
• Use of a function expression with a custom target and selector
• *
• Use of a function expression with any of the following predefined selectors: *
*
• average:
• *
• castObject:toType:
• *
• max:
• *
• median:
• *
• min:
• *
• mode:
• *
• random
• *
• random:
• *
• randomn:
• *
• stddev:
• *
*
• *
*/ /** * \page tracking_changes Tracking database changes * * BXDatabaseObject conforms to NSKeyValueObserving and uses self-updating collections for storing * related objects; changes in them may thus be tracked with KVO. * * BXSynchronizedArrayController's contents will be updated automatically. BXDatabaseContext's fetch * methods also have the option to return a self-updating array instead of an * ordinary one. In this case, the collection's owner has to be specified for KVO notifications to be posted. * See the collection classes' documentation for details. * * Another, a more low-level means of tracking changes is observing NSNotifications. Notifications on * entity changes will be posted to the relevant context's notification center. The notification object * will be a BXEntityDescription which corresponds to the table where the change happened. The names * of the notifications are: * \li kBXInsertNotification on database INSERT * \li kBXUpdateNotification on database UPDATE * \li kBXDeleteNotification on database DELETE * * At the time the notifications are posted, database objects and self-updating collections will * already have been updated. * * * \section trigger_effects Effects of triggers * * When inserting, updating or deleting rows, BaseTen notices (and posts notifications of) changes * that occur as a result of database triggers or rules firing. The only requirement is that said * changes are to entities other than the one being changed by BaseTen; changes to the same entity * will be ignored. */ /** * \page using_appkit_classes Using BaseTenAppKit * * When BaseTenAppKit is linked to an application, BXDatabaseContext gains some additional capabilities. If given * a partial database URI, it will present a number of connection panels when * \ref BXDatabaseContext::connect: "-connect:" is called. * * BXDatabaseObjects may be used much in the same manner as NSManagedObjects to populate various Cocoa views. * To handle some situations unique to BaseTen, * some NSController subclasses have been provided with the framework. For now, the only directly usable one is * BXSynchronizedArrayController. Additionally, there is BXController and additions to NSController for creating * controller subclasses. * * BaseTenAppKit contains a plug-in for Interface Builder. The plug-in should get loaded automatically if * the framework is added to a project. * * \note Under some circumstances the outlets and actions won't show up when the * plug-in has been loaded for the first time. If this happens, save and close your document * and open it again. Also relaunching Interface Builder has solved the issue. * * * \section bxsynchronizedarraycontroller BXSynchronizedArrayController * * Compared to NSArrayController, BXSynchronizedArrayController can do the following things: *
*
• It can present errors to the user when creating a new object fails.
• *
• It can get a BXEntityDescription from its database context and fetch objects using it. NSEntityDescriptions cannot be used because they are CoreData-specific.
• *
• It can lock the edited row in the database when an editing session begins.
• *
• It can provide the selected objects' ids.
• *
* * BXSynchronizedArrayController shouldn't be set to entity mode; the user interface for this isn't even available * in Interface Builder. It also doesn't make use of a managed object context. * * BXSynchronizedArrayController's Content Set may be bound to another synchronized array controller with * a key path that represents a relationship. In case of a one-to-many relationship, the foreign key field * values will also be set when -newObject or -createObject: gets called. * * * \section using_bxdatabasecontext_ib Using BXDatabaseContext from Interface Builder * *
*
1. Load the BaseTen plug-in.
2. *
3. Create a new nib file.
4. *
5. Drag a database context from the library to the file.
6. *
7. Select the database context and choose Attributes from the inspector's pop-up menu.
8. *
9. Enter a valid database URI, pgsql:///database_name at minimum.
10. *
* * * \section using_bxsynchronizedarraycontroller_ib Using BXSynchronizedArrayController from Interface Builder * *
*
1. Drag a BXSynchronizedArrayController from the library to the file.
2. *
3. Select the array controller and choose Attributes from the inspector's pop-up menu.
4. *
5. Enter a table name into the field. *
*
• The schema field may be left empty, in which case public will be used.
• *
*
6. *
7. Bind the Cocoa views to the controller.
8. *
9. Bind the array controller to the database context using the Database Context binding or * connect the databaseContext outlet.
10. *
11. Test the interface. The views should be populated using the database.
12. *
* * * \section using_value_transformers_ib Using BaseTenAppKit's value transformers from Interface Builder * * When database rows get locked, it might be desirable to disable editing and indicate this visually * in the user interface. Most AppKit's classes, have an Editable binding, and some, like NSTableColumn, * have bindings that affect the display of their value. Lets say a table column's Value is * bound to a BXArrayController using my_key as the model key path. BaseTenAppKit could then * be used to set the rows to be conditionally editable like this: *
*
1. Select the table column inside its table view
2. *
3. Open the Bindings Inspector
4. *
5. Click the Editable binding
6. *
7. Set the binding to the array controller and set the controller key to arrangedObjects. *
8. Set the model key to statusInfo.my_key.
9. *
10. Set the value transformer to BXObjectStatusToEditableTransformer.
11. *
* The rows may also be coloured so that their status is visible: *
*
1. Inspecting the same column as in the previous example, click the Text Color binding.
2. *
3. Set the binding to the array controller and set the controller key to arrangedObjects. *
4. Set the model key to statusInfo.my_key.
5. *
6. Set the value transformer to BXObjectStatusToColorTransformer.
7. *
*/ /** * \page autocommit_manual_commit Commit modes and locking * * BXDatabaseContext has two modes for handling transactions, which affect queries sent to the database and the way * the context's undo manager is used. In both cases, the transaction isolation level is set to READ COMMITTED meaning that * changes committed by other connections will be received. The commit mode is set using -setAutocommits:. Generally, * autocommit is well-suited for non-document-based applications. Manual commit is well-suited for document-based * applications, provided that changes are committed frequently enough. * * * \section autocommit Autocommit * * When using autocommit, each query creates its own transaction and changes get propagated immediately to other clients. * Undo works at the level of -[BXDatabaseObject setPrimitiveValue:forKey:]. For each change an invocation of the method * is added to the undo manager with the earlier value as a parameter. * * * \section manual_commit Manual commit * * In manual commit mode, a savepoint is added after each change. Undo causes a ROLLBACK TO SAVEPOINT query to be sent. * This causes not only the changes made by BaseTen to be reverted, but their possible side effects as well. For instance, * if database triggers fire when a specific change is made, its effects will be reverted, too. When -commit: or -rollback * is called, undo queue is emptied. * * In case one client updates a row, BaseTen doesn't send the change to other clients immediately. Instead, it sends a * notification indicating that the row is locked and changing it will cause the connection to block until the other * client ends its transaction. BXDatabaseObject's method -isLockedForKey:, BXDatabaseObjectStatusInfo class and * value transformers in BaseTenAppKit are useful for handling this situation. However, other than BaseTen clients * don't cause the lock status to be set, and the connection could block. * * The downside is that if -[BXDatabaseContext commit:] or -[BXDatabaseContext rollback] aren't called frequently enough, * transactions could become very long, which is against their intended use. This causes server resources to be consumed. * * * \section locking_rows Locking rows * * When a database connection sends UPDATE and DELETE queries, the affected rows will be locked until the connection * ends its transaction. If other connections try to change the rows, their queries will block. To handle this * situation, BaseTen stores information about locked rows into its internal tables and notifies other BaseTen clients * about them. BXSynchronizedArrayController also tries to lock rows when the editing session begins. * * Lock information will be available using BXDatabaseObject's method -isLockedForKey:. * BXDatabaseContext has a method, -setSendsLockQueries:, for enabling or disabling lock notifications. If the * notifications are disabled, BXDatabaseContext won't notify other clients but still reacts to received notifications. * * When editing rows through BXSynchronizedArrayController, it tries to send a SELECT ... FOR UPDATE NOWAIT query * when the editing session begins. If the context is in autocommit mode, a transaction will also be started. * If the query succeeds, a lock notification will be sent regardless of BXDatabaseContext's setting. If the query * fails, the editing session will be ended using -discardEditing. BXSynchronizedArrayController's method * -setLocksRowsOnBeginEditing: can be used to disable this functionality. * * To make the changes visible in the user interface, BaseTenAppKit has some NSValueTransformer subclasses. See * \ref value_transformers for details. */ /** * \page thread_safety Thread safety * * For its mostly used parts, BaseTen isn't thread safe. In particular, BXDatabaseContext needs to be used from the same thread * in which its connection methods have been called. This is because it adds a run loop source to the thread's run loop. * * The documented methods of the following classes are thread safe: * * \li BXEntityDescription * \li BXAttributeDescription * \li BXRelationshipDescription * \li BXDatabaseObjectID * * Additionally, BXDatabaseObject's method -cachedValueForKey: is thread safe. As a result, BXDatabaseObject's values may be * accessed from multiple threads as soon as they have been fetched. * * One possibility to make use of multiple threads is to create a database context for each thread, but * see \ref multiple_contexts "the next chapter". */ /** * \page multiple_contexts Using multiple database contexts * * In general, there aren't many reasons to have multiple database contexts in an application that connects * to a single database. One possibility to make the context available * everywhere it's needed is to make it a property of the NSApplication delegate or an NSDocument subclass. * * Advantages: * \li Thread safety. Since database contexts should be created and used from within a single thread, it * might be advantageous to create one for each thread. * \li Transaction isolation. One could want to query the database state outside the current transaction. * \li Privilege separation. One might want to access the database using roles with different privileges. * \li Different commit modes. * * Disadvantages: * \li Increased memory usage on the server. Each database context makes a connection to the database * (two in manual commit mode). These require an amount of shared memory * on the server. This limits the number of clients who can connect simultaneously. * \li Increased memory and network usage on the client side. Database objects are uniqued and updated * within a context, so each context requires its own copy of the objects. * Each context also needs to update its objects on its own. * \li Database objects cannot be passed from one context to another. This causes problems. */ /** * \page linking_to_baseten Linking to BaseTen and BaseTenAppKit * * Mac OS X's linker specifies paths to dynamic libraries (including frameworks) using a the install name of the library. The install name is specified in the library * itself. BaseTen and BaseTenAppKit distributed on the disk image have their install names set to a location inside the loading application's bundle, in the Frameworks folder. * When linking to the frameworks in Xcode, a Copy Files build phase should be added for the application target: *
*
1. Right-click your application target in the Groups & Files table
2. *
3. Select Add, New Build Phase and New Copy Files Build Phase
4. *
5. Select Frameworks as the destination
6. *
7. Click the disclosure triangle next to your target
8. *
9. Drag BaseTen and BaseTenAppKit inside the new build phase
10. *
* * The frameworks are built with the -headerpad_max_install_names linker option, so changing the install names with tools like install_name_tool should also be possible. * When building BaseTen and BaseTenAppKit using the Debug configuration, the install name is left empty, which causes it to be set to the build directory. */ /** * \page building_baseten Building BaseTen * * For a successful build, Xcode 3.1 and Mac OS X 10.5 SDK are required. * * BaseTen has several subprojects, namely BaseTenAppKit and a plug-in for Interface Builder 3. The default target in * BaseTen.xcodeproj, BaseTen + GC, builds them as well; the plug-in and the AppKit framework will appear in the * subprojects' build folders, which are set to the default folder. The built files will be either in * build folders in the subprojects' folders or in the user-specified build folder. The documentation will be * in the Documentation folder. * * * \section building_for_the_release_dmg Building for the release disk image * * The files needed to build the release disk image are in the SVN repository as well. Doxygen is needed during * the process. To create the DMG, follow these steps: *
*
1. From the checked-out directory, cd ReleaseDMG.
2. *
3. The default location for the built files is BaseTen-dmg-build in the current directory. To set a custom path, edit the SYMROOT variable in create_release_dmg.sh.
4. *
5. * Do ./create_release_dmg.sh. The built DMG will appear in the ReleaseDMG folder. *
*
• If you don't have LaTeX installed, do ./create_release_dmg.sh -–without-latex instead. The PDF manual won't be included on the DMG, though.
• *
*
6. *
*/ /** * \page database_usage Database administration * * \latexonly \section*{Topics} \endlatexonly * \li \subpage baseten_enabling * \li \subpage database_dumps * \li \subpage postgresql_installation */ /** * \page baseten_enabling Enabling relations for use with BaseTen * * Some tables are created in BaseTen schema to track changes in other relations and storing relationships * between tables and views. The association is based on relation names. * * While this arrangement allows clients to fault only changed objects, it has some unfortunate side effects: * \li Altering relations' names after having them enabled will not work. To rename relations, they need * to be disabled first and re-enabled afterwards. * \li Altering relations' primary keys will not work. Again, disabling and re-enabling is required. * \li Altering relations' columns will not work. Again, disabling and re-enabling is required. * \li Altering relations' foreign keys causes BaseTen's relationship information to become out-of-date * and needing to be refreshed. * * All this can be done using BaseTen Assistant. * * \note In version 1.5, relations and BaseTen's tables were associated with each other based on relation * names. This didn't work for all names, though, and made renaming enabled relations impossible. * In versions 1.6 through 1.6.2, the association was based on relation oids. While this made * renaming relations possible, it also made dumping database contents exceedingly difficult. * * * \section sql_enabling Enabling relations and updating relationship cache using SQL functions * * In addition to using BaseTen Assistant, it is possible to enable and disable tables with SQL functions. * The functions are baseten.enable (oid) and baseten.disable (oid). The object identifier * argument can be looked up from PostgreSQL's system tables, pg_class and pg_namespace. * * Views' primary keys are stored in baseten.view_pkey. The table has three columns: nspname, * relname and attname, which correspond to the view's schema name, the view's name and each primary * key column's name respectively. To enable a view, its primary key needs to be specified first. * * Relationships and view hierarchies among other things are stored in automatically-generated tables. * These should be refreshed with the SQL function baseten.refresh_caches () after all changes to views, * primary keys and foreign keys. */ /** * \page database_dumps Making a database dump * * After having been in use, the BaseTen schema might contain some temporary information. The temporary information is removed periodically when the * database is queried, but for creating installation scripts it might be desirable to remove all unnecessary data. This can be done from BaseTen * Assistant or by running the SQL function baseten.prune (). * * For BaseTen schema to work, the table contents for most tables are needed, so dumps excluding the data are not recommended. */ /** * \page postgresql_installation PostgreSQL installation * * PostgreSQL is distributed as an Installer package at the following address:
* http://www.postgresql.org/download/macosx * Another option is to build the server from source. Here's a brief tutorial. *
*
1. Get the latest PostgreSQL source release (8.2 or later) from http://www.postgresql.org/ftp/source.
2. *
3. Uncompress, configure, make, [sudo] make install. On Mac OS X, Bonjour and OpenSSL are available, so ./configure –-with-bonjour –-with-openssl && make && sudo make install probably gives the expected results.
4. *
5. It's usually a good idea to create a separate user and group for PostgreSQL, but Mac OS X already comes with a database-specific user: for mysql. We'll just use that and hope PostgreSQL doesn't mind.
6. *
7. Make mysql the owner of the PostgreSQL folder, then sudo to mysql:\n * * sudo chown -R mysql:mysql /usr/local/pgsql\n * sudo -u mysql -s * *
8. *
9. Initialize the PostgreSQL database folder. We'll use en_US.UTF-8 as the default locale:\nLC_ALL=en_US.UTF-8 /usr/local/pgsql/bin/initdb -D \\\n /usr/local/pgsql/data
10. *
11. Launch the PostgreSQL server itself:\n * * /usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data \\\n * -l /usr/local/pgsql/data/pg.log start * *
12. Create a superuser account for yourself. This way, you don't have to sudo to mysql to create new databases and users.\n * /usr/local/pgsql/bin/createuser your-short-user-name *
13. *
14. Exit the mysql sudo and create a database. If you create a database with your short user name, psql will connect to it by default.\n * * exit\n * /usr/local/pgsql/bin/createdb your-short-user-name * *
15. *
*/