This file is indexed.

/usr/share/perl5/Rose/DB/Object/Manager.pm is in librose-db-object-perl 1:0.815-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
package Rose::DB::Object::Manager;

use strict;

use Carp();

use List::Util qw(first);
#use List::MoreUtils qw(uniq);
use Scalar::Util qw(weaken refaddr);

use Rose::DB::Object::Iterator;
use Rose::DB::Object::QueryBuilder qw(build_select build_where_clause);
use Rose::DB::Object::Constants
  qw(PRIVATE_PREFIX STATE_LOADING STATE_IN_DB MODIFIED_COLUMNS);

# XXX: A value that is unlikely to exist in a primary key column value
use constant PK_JOIN => "\0\2,\3\0";

our $VERSION = '0.813';

our $Debug = 0;

#
# Class data
#

use Rose::Class::MakeMethods::Generic
(
  inheritable_scalar =>
  [
    'error',
    'total', 
    'error_mode',
    '_object_class',
    '_base_name',
    '_default_manager_method_types',
    'default_objects_per_page',
    'default_limit_with_subselect',
    'default_nested_joins',
    'dbi_prepare_cached',
    'strict_ops',
  ],
);

__PACKAGE__->error_mode('fatal');
__PACKAGE__->default_objects_per_page(20);
__PACKAGE__->default_limit_with_subselect(1);
__PACKAGE__->default_nested_joins(1);
__PACKAGE__->dbi_prepare_cached(0);
__PACKAGE__->strict_ops(0);
__PACKAGE__->default_manager_method_types(qw(objects iterator count delete update));

sub handle_error
{
  my($class, $object) = @_;

  my $mode = $class->error_mode;

  return  if($mode eq 'return');

  my $level = $Carp::CarpLevel;
  local $Carp::CarpLevel = $level + 1;  

  if($mode eq 'croak' || $mode eq 'fatal')
  {
    Carp::croak $object->error;
  }
  elsif($mode eq 'carp')
  {
    Carp::carp $object->error;
  }
  elsif($mode eq 'cluck')
  {
    Carp::croak $object->error;
  }
  elsif($mode eq 'confess')
  {
    Carp::confess $object->error;
  }
  else
  {
    Carp::croak "(Invalid error mode set: '$mode') - ", $object->error;
  }

  return 1;
}

sub normalize_get_objects_args
{
  # Handle all these arg forms:
  #
  #   get_objects(a => b, c => d, ...);
  #   get_objects([ ... ], a => b, c => d, ...)
  #   get_objects({ ... }, a => b, c => d, ...)

  if(ref $_[1])
  {
    my $class = shift;

    if(ref $_[0] eq 'HASH')
    {
      return ($class, query => [ %{shift(@_)} ], @_);
    }
    elsif(ref $_[0] eq 'ARRAY')
    {
      return ($class, query => shift, @_);
    }
    else { Carp::croak 'Invalid arguments: ', join(', ', @_) }
  }

  return @_;
}

# XXX: These are duplicated from ManyToMany.pm because I don't want to use()
# XXX: that module from here if I don't have to.  Lazy or foolish?  Hm.
# XXX: Anyway, make sure they stay in sync!
use constant MAP_RECORD_METHOD => 'map_record';
use constant DEFAULT_REL_KEY   => PRIVATE_PREFIX . '_default_rel_key';

sub object_class { }

sub default_manager_method_types
{
  my($class) = shift;

  if(@_)
  {
    if(@_ == 1 && ref $_[0] eq 'ARRAY')
    {
      $class->_default_manager_method_types(@_);
    }
    else
    {
      $class->_default_manager_method_types([ @_ ]);
    }
  }

  return wantarray ? 
    @{$class->_default_manager_method_types} : $class->_default_manager_method_types;
}

sub make_manager_methods
{
  my($class) = shift;

  if(@_ == 1)
  {
    @_ = (methods => { $_[0] => [ $class->default_manager_method_types ] });
  }
  else
  {
    Carp::croak "make_manager_methods() called with an odd number of arguments"  
      unless(@_ % 2 == 0);
  }

  my %args = @_;

  local $Debug = $args{'debug'}  if(exists $args{'debug'});

  my $calling_class  = ($class eq __PACKAGE__) ? (caller)[0] : $class;
  my $target_class   = $args{'target_class'} || $calling_class;
  my $object_class   = $args{'object_class'};
  my $class_invocant = UNIVERSAL::isa($target_class, __PACKAGE__) ? 
                         $target_class : __PACKAGE__;

  unless($object_class)
  {
    if(UNIVERSAL::isa($target_class, 'Rose::DB::Object::Manager'))
    {
      $object_class = $target_class->object_class;
    }

    if(!$object_class && UNIVERSAL::isa($target_class, 'Rose::DB::Object'))
    {
      $object_class = $target_class;
    }
  }

  unless($object_class)
  {
    Carp::croak "Could not determine object class.  Please pass a value for ",
                "the object_class parameter", 
                (UNIVERSAL::isa($target_class, 'Rose::DB::Object::Manager') ?
                 " or override the object_class() method in $target_class" : '');
  }

  unless(UNIVERSAL::isa($object_class, 'Rose::DB::Object'))
  {
    my $error;

    TRY:
    {
      local $@;
      eval "require $object_class";
      $error = $@;
    }

    if($error)
    {
      Carp::croak "Could not load object class $object_class - $error";
    }
  }

  my $meta = $object_class->meta;
  my $cm   = $meta->convention_manager;

  my $base_name = $args{'base_name'} || $cm->auto_manager_base_name($meta->table, $object_class);

  if(!$args{'methods'})
  {
    unless($base_name)
    {
      Carp::croak "Missing methods parameter and base_name parameter, and the ",
                  "convention manager's auto_manager_base_name() method did not ",
                  "return a true value"
    }

    $args{'methods'} = 
    { 
      $base_name => [ $class->default_manager_method_types ] 
    };
  }
  elsif($args{'base_name'})
  {
    Carp::croak "Please pass the methods parameter OR the base_name parameter, not both";
  }

  Carp::croak "Invalid 'methods' parameter - should be a hash ref"
    unless(ref $args{'methods'} eq 'HASH');

  $class->_base_name($base_name);
  $class->_object_class($object_class);

  while(my($name, $types) = each %{$args{'methods'}})
  {
    $class->_base_name($name)  unless($base_name);

    my $have_full_name = ($name =~ s/\(\)$//) ? 1 : 0;

    Carp::croak "Invalid value for the '$name' parameter"
      if(ref $types && ref $types ne 'ARRAY');

    if($have_full_name && ref $types && @$types > 1)
    {
      Carp::croak "Cannot use explicit method name $name() with more ",
                  "than one method type";
    }

    foreach my $type ((ref $types ? @$types : ($types)))
    {
      no strict 'refs';

      if($type eq 'objects')
      {
        my $method_name = 
          $have_full_name ? $name : 
            ($cm->auto_manager_method_name($type, $base_name, $object_class) || "get_$name");

        foreach my $class ($target_class, $class_invocant)
        {
          my $method = "${class}::$method_name";
          my $short_method = $method_name;
          Carp::croak "A $method method already exists"
            if(defined &{$method});

          Carp::croak "The $short_method method is inherited from Rose::DB::Object::Manager ",
                      "and cannot be overriden in $target_class"
            if(Rose::DB::Object::Manager->can($short_method));
        }

        $Debug && warn "Making method: $target_class->$method_name()\n";
        *{"${target_class}::$method_name"} = sub
        {
          shift;
          $class_invocant->get_objects(@_, object_class => $object_class);
        };
      }
      elsif($type eq 'count')
      {
        my $method_name = 
          $have_full_name ? $name : 
            ($cm->auto_manager_method_name($type, $base_name, $object_class) || "get_${name}_count");

        foreach my $class ($target_class, $class_invocant)
        {
          my $method = "${class}::$method_name";
          Carp::croak "A $method method already exists"
            if(defined &{$method});
        }

        $Debug && warn "Making method: $target_class->$method_name()\n";
        *{"${target_class}::$method_name"} = sub
        {
          shift;
          $class_invocant->get_objects(
            @_, count_only => 1, object_class => $object_class)
        };
      }
      elsif($type eq 'iterator')
      {
        my $method_name = 
          $have_full_name ? $name : 
            ($cm->auto_manager_method_name($type, $base_name, $object_class) || "get_${name}_iterator");

        foreach my $class ($target_class, $class_invocant)
        {
          my $method = "${class}::$method_name";
          Carp::croak "A $method method already exists"
            if(defined &{$method});
        }

        $Debug && warn "Making method: $target_class->$method_name()\n";
        *{"${target_class}::$method_name"} = sub
        {
          shift;
          $class_invocant->get_objects(
            @_, return_iterator => 1, object_class => $object_class)
        };
      }
      elsif($type eq 'delete')
      {
        my $method_name = 
          $have_full_name ? $name : 
            ($cm->auto_manager_method_name($type, $base_name, $object_class) || "delete_$name");

        foreach my $class ($target_class, $class_invocant)
        {
          my $method = "${class}::$method_name";
          Carp::croak "A $method method already exists"
            if(defined &{$method});
        }

        $Debug && warn "Making method: $target_class->$method_name()\n";
        *{"${target_class}::$method_name"} = sub
        {
          shift;
          $class_invocant->delete_objects(@_, object_class => $object_class);
        };
      }
      elsif($type eq 'update')
      {
        my $method_name = 
          $have_full_name ? $name : 
            ($cm->auto_manager_method_name($type, $base_name, $object_class) || "update_$name");

        foreach my $class ($target_class, $class_invocant)
        {
          my $method = "${class}::$method_name";
          Carp::croak "A $method method already exists"
            if(defined &{$method});
        }

        $Debug && warn "Making method: $target_class->$method_name()\n";
        *{"${target_class}::$method_name"} = sub
        {
          shift;
          $class_invocant->update_objects(@_, object_class => $object_class);
        };
      }
      else
      {
        Carp::croak "Invalid method type: $type";
      }
    }
  }
}

sub get_objects_count
{
  my($class) = shift;
  $class->get_objects(@_, count_only => 1);
}

sub get_objects_iterator { shift->get_objects(@_, return_iterator => 1) }
sub get_objects_sql      { shift->get_objects(@_, return_sql => 1) }

use constant WITH => 555; # arbitrary

sub get_objects
{
  my($class, %args);

  if(ref $_[1])
  {
    $class = shift;

    if(ref $_[0] eq 'HASH')
    {
      %args = (query => [ %{shift(@_)} ], @_);
    }
    elsif(ref $_[0] eq 'ARRAY')
    {
      %args = (query => shift, @_);
    }
    else { Carp::croak 'Invalid arguments: ', join(', ', @_) }

    unshift(@_, $class); # restore original args  
  }
  else
  {
    ($class, %args) = @_;
  }

  $class->error(undef);

  my $object_class = delete $args{'object_class'} 
    || $class->object_class || Carp::croak "Missing object class argument";

  my $return_sql       = delete $args{'return_sql'};
  my $return_iterator  = delete $args{'return_iterator'};
  my $count_only       = delete $args{'count_only'};
  my $require_objects  = delete $args{'require_objects'};
  my $with_objects     = delete $args{'with_objects'};

  my $skip_first       = delete $args{'skip_first'} || 0;
  my $distinct         = delete $args{'distinct'};
  my $fetch            = delete $args{'fetch_only'};
  my $hints            = delete $args{'hints'} || {};
  my $select           = $args{'select'};

  # Alias by popular demand...
  $args{'query'} = delete $args{'where'}
    if($args{'where'} && !exists $args{'query'});

  $args{'strict_ops'} = $class->strict_ops  unless(exists $args{'strict_ops'});

  my $no_forced_sort = delete $args{'no_forced_sort'};

  my $table_aliases    = exists $args{'table_aliases'} ? 
    $args{'table_aliases'} : ($args{'table_aliases'} = 1);

  # Coerce for_update boolean alias into lock argument
  if(delete $args{'for_update'})
  {
    $args{'lock'}{'type'} ||= 'for update';
  }

  $with_objects    = undef  if(ref $with_objects && !@$with_objects);
  $require_objects = undef  if(ref $require_objects && !@$require_objects);

  local $Debug = $args{'debug'}  if(exists $args{'debug'});

  my $try_subselect_limit = (exists $args{'limit_with_subselect'}) ? 
    $args{'limit_with_subselect'} : $class->default_limit_with_subselect;

  my $subselect_limit = 0;

  # Can't do direct inject with custom select lists
  my $direct_inject = $select ? 0 : delete $args{'inject_results'};

  my(%fetch, %rel_name, %di_keys);

  my $meta = $object_class->meta;

  $args{'hints'} = $hints->{'t1'} || $hints->{$meta->table} || $hints;

  my $prepare_cached = 
    exists $args{'prepare_cached'} ? $args{'prepare_cached'} :
    $class->dbi_prepare_cached;

  my $db   = delete $args{'db'} || $object_class->init_db;
  my $dbh  = delete $args{'dbh'};
  my $dbh_retained = 0;

  unless($dbh)
  {
    unless($dbh = $db->retain_dbh)
    {
      $class->error($db->error);
      $class->handle_error($class);
      return undef;
    }

    $dbh_retained = 1;
  }

  # Work-around for http://rt.cpan.org//Ticket/Display.html?id=33193
  local $dbh->{'pg_expand_array'} = 0
    if($dbh->{'Driver'}{'Name'} eq 'Pg' && index($dbh->{'Driver'}{'Version'}, '2.0.') == 0);

  my $nested_joins = $args{'nested_joins'} = $db->supports_nested_joins ?
    (defined $args{'nested_joins'} ? $args{'nested_joins'} : $class->default_nested_joins) : 0;

  my $use_explicit_joins = (defined $args{'explicit_joins'}) ? 
    $args{'explicit_joins'} : !$db->likes_implicit_joins;

  my $with_map_records;

  if($with_map_records = delete $args{'with_map_records'})
  {
    unless(ref $with_map_records)
    {
      if($with_map_records =~ /^[A-Za-z_]\w*$/)
      {
        $with_map_records = { DEFAULT_REL_KEY() => $with_map_records };
      }
      elsif($with_map_records)
      {
        $with_map_records = { DEFAULT_REL_KEY() => MAP_RECORD_METHOD };
      }
      else
      {
        $with_map_records = 0;
      }
    }
  }

  my $outer_joins = ($with_objects && !$require_objects) ? 1 : 0;

  my($num_required_objects, %required_object, $num_with_objects,
     %with_objects, @belongs_to, %seen_rel, %rel_tn, %join_type);

  $with_objects    = [ $with_objects ]     if($with_objects && !ref $with_objects);
  $require_objects = [ $require_objects ]  if($require_objects && !ref $require_objects);

  #print STDERR 'WITH: ', Dumper($with_objects);
  #print STDERR 'REQUIRE: ', Dumper($require_objects);

  # XXX: Currently, the most robust join-type conflict checking only
  # XXX: happens if a least one join-type override is present.  In
  # XXX: other cases, the "with" wins.  This is "safe" but not 
  # XXX: necessarily efficient.

  # If there are any join-type overrides
  if(first { index($_, '!') > 0 || index($_, '?') > 0 }
     (($with_objects ? @$with_objects : ()),
      ($require_objects ? @$require_objects : ())))
  {
    my $i = 0;
    my $requires_start = $with_objects ? @$with_objects : 0;
    my $in_require = 0;
    my $join_type;

    # Pull out the join modifiers
    foreach my $arg (($with_objects ? @$with_objects : ()),
                     ($require_objects ? @$require_objects : ()))
    {
      $in_require = 1  if(!$in_require && $i++ == $requires_start);

      my $save_arg = $arg;
      $arg =~ tr/!?//d;

      if(index($arg, '.') < 0)
      {
        $save_arg =~ s/([!?])$//;

        no warnings 'uninitialized';
        $join_type = ($1 eq '!' || (!$1 && $in_require)) ? 'JOIN' : 'LEFT OUTER JOIN';

        Carp::croak "Conflicting suffix for '$arg' - please choose either ! or ?"
          if($join_type{$arg} && $join_type{$arg} ne $join_type);

        $join_type{$arg} = $join_type;
      }
      else
      {
        $save_arg =~ s/([!?])$//;

        no warnings 'uninitialized';
        $join_type = ($1 eq '!' || (!$1 && $in_require)) ? 'JOIN' : 'LEFT OUTER JOIN';

        Carp::croak "Conflicting suffix for '$arg' - please choose either ! or ?"
          if($join_type{$arg} && $join_type{$arg} ne $join_type);

        $join_type{$arg} = $join_type;

        while($save_arg =~ s/\.[^.]+$//)
        {
          $save_arg =~ s/([!?])$//;

          $join_type = ($1 eq '!' || (!$1 && $in_require)) ? 'JOIN' : 'LEFT OUTER JOIN';

          (my $clean_arg = $save_arg) =~ tr/!?//d;

          Carp::croak "Conflicting suffix for '$clean_arg' - please choose either ! or ?"
            if($join_type{$clean_arg} && $join_type{$clean_arg} ne $join_type);

          $join_type{$clean_arg} = $join_type;
        }
      }
    }

    if(grep { $_ eq 'LEFT OUTER JOIN' } values %join_type)
    {
      $outer_joins = 1;
    }
  }

  # Putting join conditions in the WHERE clause can change the meaning of
  # the query when outer joins are used, so disable them in that case.
  my $use_redundant_join_conditions =
    $outer_joins ? 0 : delete $args{'redundant_join_conditions'};

  #use Data::Dumper;
  #print STDERR 'JOIN TYPES: ', Dumper(\%join_type);
  #print STDERR 'POST WITH: ', Dumper($with_objects);
  #print STDERR 'POST REQUIRE: ', Dumper($require_objects);

  if($with_objects)
  {
    # Doing this implicitly is never a good idea
    #unless(defined $use_redundant_join_conditions)
    #{
    #  $use_redundant_join_conditions = $db->likes_redundant_join_conditions;
    #}

    # Copy argument (shallow copy)
    $with_objects = [ @$with_objects ]; #[ uniq @$with_objects ];

    # Expand multi-level arguments
    if(first { index($_, '.') >= 0 } @$with_objects)
    {
      my @with_objects;

      foreach my $arg (@$with_objects)
      {
        next  if($seen_rel{$arg});

        if(index($arg, '.') < 0)
        {
          $seen_rel{$arg} = WITH;
          push(@with_objects, $arg);
        }
        else
        {
          my @expanded = ($arg);
          $seen_rel{$arg} = WITH;

          while($arg =~ s/\.([^.]+)$//)
          {
            next  if($seen_rel{$arg}++);
            unshift(@expanded, $arg);
          }

          push(@with_objects, @expanded);          
        }
      }

      $with_objects = \@with_objects;
    }
    else
    {
      $seen_rel{$_} = WITH  for(@$with_objects);
    }

    $num_with_objects = @$with_objects;
    %with_objects = map { $_ => 1 } @$with_objects;
  }

  if($require_objects)
  {
    # Copy argument (shallow copy)
    $require_objects = [ @$require_objects ]; #[ uniq @$require_objects ];

    # Expand multi-level arguments
    if(first { index($_, '.') >= 0 } @$require_objects)
    {
      my @require_objects;

      foreach my $arg (@$require_objects)
      {
        if(index($arg, '.') < 0)
        {
          if(my $seen = $seen_rel{$arg})
          {
            if($seen == WITH)
            {
              Carp::croak "require_objects argument '$arg' conflicts with ",
                          "with_objects argument of the same name";
            }
            next;
          }

          $seen_rel{$arg}++;
          push(@require_objects, $arg);
        }
        else
        {
          my @expanded = ($arg);

          if(my $seen = $seen_rel{$arg})
          {
            if($seen == WITH)
            {
              Carp::croak "require_objects argument '$arg' conflicts with ",
                          "with_objects argument of the same name";
            }
            next;
          }

          $seen_rel{$arg}++;

          while($arg =~ s/\.[^.]+$//)
          {
            next  if($seen_rel{$arg});
            unshift(@expanded, $arg);
            $seen_rel{$arg}++;
          }

          push(@require_objects, @expanded);          
        }
      }

      $require_objects = \@require_objects;
    }
    else
    {
      foreach my $arg (@$require_objects)
      {
        if($seen_rel{$arg})
        {
          Carp::croak "require_objects argument '$arg' conflicts with ",
                      "with_objects argument of the same name";
        }
      }
    }

    $num_required_objects = @$require_objects;
    %required_object = map { $_ => 1 } @$require_objects;
    push(@$with_objects, @$require_objects)
  }

  my %object_args = (ref $args{'object_args'} eq 'HASH') ? %{$args{'object_args'}} : ();
  my %subobject_args;

  $args{'share_db'} = 1  unless(exists $args{'share_db'});

  if(delete $args{'share_db'})
  {
    $object_args{'db'}    = $db;
    $subobject_args{'db'} = $db;
  }

  my($fields, $fields_string, $table);

  $args{'nonlazy'} = []  unless(defined $args{'nonlazy'});
  my $nonlazy = $args{'nonlazy'};
  my %nonlazy = (ref $nonlazy ? map { $_ => 1 } @$nonlazy : ());

  my @tables     = ($meta->fq_table($db));
  my @tables_sql = ($meta->fq_table_sql($db));

  my $use_lazy_columns = (!ref $nonlazy || $nonlazy{'self'}) ? 0 : $meta->has_lazy_columns;

  my(%columns, %methods, %all_columns);

  if($use_lazy_columns)
  {
    %columns     = ($tables[0] => scalar $meta->nonlazy_columns);
    %all_columns = ($tables[0] => scalar $meta->columns);
    %methods     = ($tables[0] => scalar $meta->nonlazy_column_mutator_method_names);
    %di_keys     = ($object_class => scalar $meta->nonlazy_column_db_value_hash_keys);
  }
  else
  {
    %columns = ($tables[0] => scalar $meta->columns);
    %methods = ($tables[0] => scalar $meta->column_mutator_method_names);  
    %di_keys = ($object_class => scalar $meta->column_db_value_hash_keys);
  }

  my %classes = ($tables[0] => $object_class);
  my @classes = ($object_class);
  my %meta    = ($object_class => $meta);

  my @table_names = ($meta->table);
  my @rel_names   = ($meta->table);

  my(@joins, @subobject_methods, @mapped_object_methods, $clauses);

  my $handle_dups = 0;
  #my $deep_joins  = 0;
  my @has_dups;

  my $manual_limit = 0;

  my $num_subtables = $with_objects ? @$with_objects : 0;

  if($distinct || $fetch)
  {
    if($fetch && ref $distinct)
    {
      Carp::croak "The 'distinct' and 'fetch' parameters cannot be used ",
                  "together if they both contain lists of tables";
    }

    $args{'distinct'} = 1  if($distinct);

    %fetch = (t1 => 1, $tables[0] => 1, $meta->table => 1);

    if(ref $fetch || ref $distinct)
    {
      foreach my $arg (ref $distinct ? @$distinct : @$fetch)
      {
        $fetch{$arg} = 1;
      }
    }
  }

  # Handle "page" arguments
  if(exists $args{'page'} || exists $args{'per_page'})
  {
    if(exists $args{'limit'} || exists $args{'offset'})
    {
      Carp::croak 'Cannot include the "page" or "per_page" ',
                  'options when the "limit" or "offset" option ',
                  'is used';
    }

    my $page     = delete $args{'page'} || 1;
    my $per_page = delete $args{'per_page'} || $class->default_objects_per_page;

    $page     = 1  if($page < 1);
    $per_page = $class->default_objects_per_page  if($per_page < 1);

    $args{'limit'} = $per_page;

    if($page > 1)
    {
      $args{'offset'} = ($page - 1) * $per_page;
    }
  }

  # Pre-process sort_by args
  if(my $sort_by = $args{'sort_by'})
  {
    $sort_by = [ $sort_by ]  unless(ref $sort_by eq 'ARRAY');

    if($num_subtables == 0 && defined $table_aliases && $table_aliases == 0)
    {
      # trim t1. or primary table prefixes
      my $prefix_re = '\b(?:t1|' . $meta->table . ')\.';
      $prefix_re = qr($prefix_re);

      foreach my $sort (@$sort_by)
      {
        $sort =~ s/$prefix_re//g  unless(ref $sort);
      }
    }

    $args{'sort_by'} = $sort_by;
  }

  my $num_to_many_rels = 0;
  # Adjust for explicitly included map_record tables, which should
  # not count towards the multi_many_ok warning.
  my $num_to_many_rels_adjustment = 0;

  my($multi_many, @subobject_method_map);

  if($with_objects)
  {
    # XXX: Hack to avoid spurious ORA-00918 errors
    # XXX: http://ora-00918.ora-code.com/msg/28663.html
    if(($args{'limit'} || $args{'offset'}) && $dbh->{'Driver'}{'Name'} eq 'Oracle')
    {
      $args{'unique_aliases'} = 1;
    }

    # Copy clauses arg
    $clauses = $args{'clauses'} ? [ @{$args{'clauses'}} ] : [];

    my $i = 1;

    # Sanity check with_objects arguments, and determine if we're going to
    # have to handle duplicate data from multiple joins.  If so, note
    # which with_objects arguments refer to relationships that may return
    # more than one object.
    foreach my $name (@$with_objects)
    {
      my $tn_name = $name;

      if(index($tn_name, '.') > 0) # dot at start is invalid, so "> 0" is correct
      {
        $tn_name =~ /^(.+)\.([^.]+)$/;
      }

      $rel_tn{$tn_name} = $i + 1; # note the tN table number of this relationship

      my $key;

      # Chase down multi-level keys: e.g., colors.name.types
      if(index($name, '.') >= 0)
      {
        #$deep_joins = 1;

        my $chase_meta = $meta;

        while($name =~ /\G([^.]+)(?:\.|$)/g)
        {
          my $sub_name = $1;

          $key = $chase_meta->foreign_key($sub_name) ||
                 $chase_meta->relationship($sub_name) ||
                 Carp::confess "Invalid with_objects or require_objects argument: ",
                               "no foreign key or relationship named '$sub_name' ",
                               'found in ', $chase_meta->class;

          $chase_meta = $key->can('foreign_class') ? 
            $key->foreign_class->meta : $key->class->meta;
        }
      }
      else
      {
        $key = $meta->foreign_key($name) || $meta->relationship($name) ||
          Carp::confess "Invalid with_objects or require_objects argument: ",
                        "no foreign key or relationship named '$name' ",
                        "found in $class";
      }

      my $rel_type = $key->type;

      if($rel_type =~ /\bmany$/)
      {
        $handle_dups  = 1;
        $has_dups[$i] = 1;

        # "many to many" relationships have an extra table (the mapping table)
        if($rel_type eq 'many to many')
        {
          $i++;
          $has_dups[$i] = 1;
          # $num_subtables will be incremented elsewhere (below)

          # Adjust for explicitly included map_record tables, which should
          # not count towards the multi_many_ok warning.
          $num_to_many_rels_adjustment++;
        }

        if($args{'limit'})
        {
          if($try_subselect_limit && $db->supports_select_from_subselect && 
             (!$args{'offset'} || $db->supports_limit_with_offset) && 
             !$args{'select'})
          {
            unless($fetch && @$fetch && $fetch->[0] eq 't1')
            {
              $subselect_limit = 1;
              delete $args{'limit'};
              delete $args{'offset'};
            }
          }
          else
          {
            $manual_limit = delete $args{'limit'};
          }
        }

        # This restriction seems unnecessary now
        #if($required_object{$name} && $num_required_objects > 1 && $num_subtables > 1)
        #{
        #  Carp::croak 
        #    qq(The "require_objects" parameter cannot be used with ),
        #    qq(a "... to many" relationship ("$name" in this case) ),
        #    qq(unless that relationship is the only one listed and ),
        #    qq(the "with_objects" parameter is not used);
        #}
      }

      $i++;
    }

    $num_to_many_rels = grep { defined $_ } @has_dups;

    # Adjust for explicitly included map_record tables, which should
    # not count towards the multi_many_ok warning.
    $multi_many = (($num_to_many_rels - $num_to_many_rels_adjustment)  > 1) ? 1 : 0;

    unless($args{'multi_many_ok'})
    {
      if($multi_many)
      {
        Carp::carp
          qq(WARNING: Fetching sub-objects via more than one ),
          qq("one to many" relationship in a single query may ),
          qq(produce many redundant rows, and the query may be ),
          qq(slow.  If you're sure you want to do this, you can ),
          qq(silence this warning by using the "multi_many_ok" ),
          qq(parameter\n);
      }
    }

    $i = 1; # reset iterator for second pass through with_objects

    # Build lists of columns, classes, methods, and join conditions for all
    # of the with_objects and/or require_objects arguments.
    foreach my $arg (@$with_objects)
    {
      my($parent_meta, $parent_tn, $name);

      if(index($arg, '.') > 0) # dot at start is invalid, so "> 0" is correct
      {
        $arg =~ /^(.+)\.([^.]+)$/;
        my $parent = $1;
        $name = $2;

        # value of $i as of last iteration
        $parent_tn = defined $rel_tn{$parent} ? $rel_tn{$parent}: $i; 

        $belongs_to[$i] = $parent_tn - 1;
        $parent_meta = $classes[$parent_tn - 1]->meta;
      }
      else
      {
        $parent_meta = $meta;
        $name = $arg;
        $parent_tn = 1;
        $belongs_to[$i] = 0;
      }

      #$rel_tn{$arg} = $i + 1; # note the tN table number of this relationship

      my $rel = $parent_meta->foreign_key($name) || 
                $parent_meta->relationship($name) ||
                Carp::croak "No relationship named '$name' in class ",
                            $parent_meta->class;

      my $rel_type = $rel->type;

      if($rel_type eq 'foreign key' || $rel_type eq 'one to one' ||
         $rel_type eq 'many to one' || $rel_type eq 'one to many')
      {
        my $ft_class = $rel->class 
          or Carp::confess "$class - Missing foreign object class for '$name'";

        my $ft_columns = $rel->key_columns;

        if(!$ft_columns && $rel_type ne 'one to many')
        {
          Carp::confess "$class - Missing key columns for '$name'";
        }

        if($rel->can('query_args') && (my $query_args = $rel->query_args))
        {
          # (Re)map query parameters to the correct table
          # t1 -> No change (the primary table)
          # t2 -> The foreign table
          for(my $i = 0; $i < @$query_args; $i += 2)
          {
            my $param = $query_args->[$i];

            if(ref $param)
            {
              push(@{$args{'query'}}, $param);
              $i--;
              next;
            }

            unless($param =~ s/^t2\./t$rel_tn{$arg}./)
            {
              $param = "t$rel_tn{$arg}.$param"  unless($param =~ /^t\d+\./);
            }

            push(@{$args{'query'}}, $param, $query_args->[$i + 1]);
          }
        }

        my $ft_meta = $ft_class->meta; 

        $meta{$ft_class} = $ft_meta;

        push(@tables, $ft_meta->fq_table($db));
        push(@tables_sql, $ft_meta->fq_table_sql($db));
        push(@rel_names, $rel_name{'t' . (scalar @tables)} = $rel->name);
        push(@table_names, $ft_meta->table);
        push(@classes, $ft_class);

        # Iterator will be the tN value: the first sub-table is t2, and so on
        $i++;

        my $use_lazy_columns = (!ref $nonlazy || $nonlazy{$name}) ? 0 : $ft_meta->has_lazy_columns;

        if($use_lazy_columns)
        {
          $columns{$tables[-1]}     = $ft_meta->nonlazy_columns;
          $all_columns{$tables[-1]} = $ft_meta->columns;
          $methods{$tables[-1]}     = $ft_meta->nonlazy_column_mutator_method_names;
          $di_keys{$classes[-1]}    = $ft_meta->nonlazy_column_db_value_hash_keys;
        }
        else
        {
          $columns{$tables[-1]}  = $ft_meta->columns;   
          $methods{$tables[-1]}  = $ft_meta->column_mutator_method_names;        
          $di_keys{$classes[-1]} = $ft_meta->column_db_value_hash_keys;
        }

        $classes{$tables[-1]} = $ft_class;

        $subobject_methods[$i - 1] = 
          $direct_inject ? $rel->hash_key :
          $rel->method_name('get_set') ||
          $rel->method_name('get_set_now') ||
          $rel->method_name('get_set_on_save') ||
          Carp::confess "No 'get_set', 'get_set_now', or 'get_set_on_save' ",
                        "method found for $rel_type '$name' in class ",
                        $rel->parent->class;

        #$subobject_keys[$i - 1] = $rel->hash_key;

        # Reset each() iterator
        #keys(%$ft_columns);

        my(@redundant, @redundant_null);

        unless($ft_columns && %$ft_columns)
        {
          if($with_objects{$arg})
          {
            $joins[$i]{'type'} = $join_type{$arg} || 'LEFT OUTER JOIN';
          }
          elsif($use_explicit_joins)
          {
            $joins[$i]{'type'} = $join_type{$arg} || 'JOIN';
          }
        }

        # Add join condition(s)
        while(my($local_column, $foreign_column) = each(%$ft_columns))
        {
          # Use outer joins to handle duplicate or optional information.
          # Foreign keys that have all non-null columns are not outer-
          # joined when nested joins are enabled, however.
          if(!($rel_type eq 'foreign key' && $rel->is_required &&
               $rel->referential_integrity && $nested_joins) &&
             ($outer_joins || $with_objects{$arg}))
          {
            # Aliased table names
            push(@{$joins[$i]{'conditions'}}, "t${parent_tn}.$local_column = t$i.$foreign_column");

            if($multi_many)
            {
              my $local_method   = $parent_meta->column_mutator_method_name($local_column);
              my $foreign_method = $ft_meta->column_accessor_method_name($foreign_column);
              push(@{$subobject_method_map[$i][$belongs_to[$i - 1]]}, [ $local_method, $foreign_method ]);
            }

            # Fully-qualified table names
            #push(@{$joins[$i]{'conditions'}}, "$tables[0].$local_column = $tables[-1].$foreign_column");

            $joins[$i]{'type'} = $join_type{$arg} || 'LEFT OUTER JOIN';
            $joins[$i]{'hints'} = $hints->{"t$i"} || $hints->{$name};

            # MySQL is stupid about using its indexes when "JOIN ... ON (...)"
            # conditions are the only ones given, so the code below adds some
            # redundant WHERE conditions.  They should only be added when they
            # do not change the meaning of the query, in which case they
            # should nudge MySQL into using its indexes.  
            # The clauses: "((<ON conditions>) OR (<any columns are null>))"
            # We build the two clauses separately in the loop below, then
            # combine it all after the loop is done.
            if($use_redundant_join_conditions)
            {
              # Aliased table names
              push(@redundant, "t${parent_tn}.$local_column = t$i.$foreign_column");
              push(@redundant_null, ($has_dups[$i - 1] ?
                   "t$i.$foreign_column IS NULL" :
                   "t${parent_tn}.$local_column IS NULL"));

              # Fully-qualified table names
              #push(@redundant, "$tables[$parent_tn - 1].$local_column = $tables[-1].$foreign_column");
              #push(@redundant_null, ($has_dups[$i - 1] ?
              #     "$tables[-1].$foreign_column IS NULL" :
              #     "$tables[$parent_tn - 1].$local_column IS NULL"));
            }
          }
          else
          {
            if($use_explicit_joins)
            {
              # Aliased table names
              push(@{$joins[$i]{'conditions'}}, "t${parent_tn}.$local_column = t$i.$foreign_column");

              # Fully-qualified table names
              #push(@{$joins[$i]{'conditions'}}, "$tables[$parent_tn - 1].$local_column = $tables[-1].$foreign_column");

              $joins[$i]{'type'} = $join_type{$arg} || 'JOIN';  
              $joins[$i]{'hints'} = $hints->{"t$i"} || $hints->{$name};
            }
            else # implicit join with no ON clause
            {
              # Aliased table names
              push(@$clauses, "t${parent_tn}.$local_column = t$i.$foreign_column");

              # Fully-qualified table names
              #push(@$clauses, "$tables[$parent_tn - 1].$local_column = $tables[-1].$foreign_column");
            }
          }
        }

        $joins[$i]{'parent_tn'} = $parent_tn  if($joins[$i] && $joins[$i]{'type'} eq 'JOIN');

        # XXX: Undocumented for now...
        if($rel->can('join_args') && (my $join_args = $rel->join_args))
        {
          my $cond = 
            build_where_clause(dbh         => $dbh,
                               tables      => [ @tables[$parent_tn - 1, $i - 1] ],
                               columns     => \%columns,
                               all_columns => \%all_columns,
                               classes     => \%classes,
                               meta        => \%meta,
                               db          => $db,
                               pretty      => $Debug,
                               query       => $join_args);

          # XXX: Ugly hack...
          for($cond)
          {
            s/(?:^| )@{[ $tables[$parent_tn - 1] ]}\./t$parent_tn./mg;
            s/(?:^| )@{[ $tables[$i - 1] ]}\./t$i./mg;
            s/(?:^| )t1\./t$parent_tn./mg;
            s/(?:^| )t2\./t$i./mg;
            s/^\s\s+/ /mg;
            s/\A\s+//;
            s/\n/ /g;
          }

          push(@{$joins[$i]{'conditions'}}, $cond);
        }

        if(@redundant)
        {
          push(@$clauses, '((' . join(' AND ', @redundant) . ') OR (' .
                          join(' OR ', @redundant_null) . '))');
        }

        $joins[$i]{'conditions'} ||= [ '1 = 1' ]  if($joins[$i]);

        # Add sub-object sort conditions
        if($rel->can('manager_args') && (my $mgr_args = $rel->manager_args))
        {
          # Don't bother sorting by columns if we're not even selecting them
          if($mgr_args->{'sort_by'} && (!%fetch || 
             ($fetch{$tables[-1]} && !$fetch{$rel_names[-1]})))
          {
            my $sort_by = ref $mgr_args->{'sort_by'} eq 'ARRAY' ?
              [ @{$mgr_args->{'sort_by'}} ] : [ $mgr_args->{'sort_by'} ];

            foreach my $sort (@$sort_by)
            {
              no warnings 'uninitialized';
              $sort =~ s/^(['"`]?)(\w+)\1(\s+(?:ASC|DESC))?$/t$i.$1$2$1$3/i
                unless(ref $sort);
            }

            push(@{$args{'sort_by'}}, @$sort_by);
          }
        }
      }
      elsif($rel_type eq 'many to many')
      {
        #
        # First add table, columns, and clauses for the map table itself
        #

        my $map_class = $rel->map_class 
          or Carp::confess "$class - Missing map class for '$name'";

        my $map_meta = $map_class->meta; 

        $meta{$map_class} = $map_meta;

        push(@tables, $map_meta->fq_table($db));
        push(@tables_sql, $map_meta->fq_table_sql($db));
        # %rel_name gets the foreign table (below), not the map table here
        push(@rel_names, $rel->name);
        push(@table_names, $map_meta->table);
        push(@classes, $map_class);

        my $rel_mgr_args = $rel->manager_args || {};

        my $map_record_method;
        my $rel_map_record_method = $rel->map_record_method;

        if(my $rel_with_map_records = $rel_mgr_args->{'with_map_records'})
        {
          $map_record_method =
            ($with_map_records && exists $with_map_records->{$name}) ? $with_map_records->{$name} :
            $rel_map_record_method ? $rel_map_record_method : MAP_RECORD_METHOD;
        }
        elsif($with_map_records)
        {
          $map_record_method =
            exists $with_map_records->{$name} ? $with_map_records->{$name} : 
            $with_map_records->{DEFAULT_REL_KEY()} || 0;
        }

        if($map_record_method)
        {
          my $use_lazy_columns = (!ref $nonlazy || $nonlazy{$name}) ? 0 : $map_meta->has_lazy_columns;

          if($use_lazy_columns)
          {
            $columns{$tables[-1]}     = $map_meta->nonlazy_columns;
            $all_columns{$tables[-1]} = $map_meta->columns;
            $methods{$tables[-1]}     = $map_meta->nonlazy_column_mutator_method_names;
            $di_keys{$classes[-1]}    = $map_meta->nonlazy_column_db_value_hash_keys;
          }
          else
          {
            $columns{$tables[-1]}  = $map_meta->columns;   
            $methods{$tables[-1]}  = $map_meta->column_mutator_method_names;        
            $di_keys{$classes[-1]} = $map_meta->column_db_value_hash_keys;
          }
        }
        else
        {
          $columns{$tables[-1]} = []; # Don't fetch map class columns
          $methods{$tables[-1]} = [];
        }

        $classes{$tables[-1]} = $map_class;

        my $column_map = $rel->column_map;

        # Iterator will be the tN value: the first sub-table is t2, and so on.
        # Increase once for map table.
        $i++;

        # Increase the tN table number of this relationship as well
        $rel_tn{$arg} = $i + 1; 

        $belongs_to[$i] = $belongs_to[$i - 1];

        $mapped_object_methods[$i - 1] = $map_record_method || 0;

        if($map_record_method)
        {
          my $ft_class = $rel->foreign_class 
            or Carp::confess "$class - Missing foreign class for '$name'";

          if($ft_class->can($map_record_method))
          {
            if($direct_inject && (my $map_record_key = $ft_class->meta->map_record_method_key($map_record_method)))
            {
              $mapped_object_methods[$i - 1] = $map_record_key;
            }
          }
          else
          {
            my $map_record_key =
              Rose::DB::Object::Metadata::Relationship::ManyToMany::make_map_record_method(
                $ft_class, $map_record_method, $map_class);

            if($direct_inject && $mapped_object_methods[$i - 1])
            {
              $mapped_object_methods[$i - 1] = $map_record_key;
            }
          }
        }

        # Add join condition(s)
        while(my($local_column, $foreign_column) = each(%$column_map))
        {
          # Use outer joins to handle duplicate or optional information.
          if($outer_joins || $with_objects{$arg})
          {
            # Aliased table names
            push(@{$joins[$i]{'conditions'}}, "t$i.$local_column = t${parent_tn}.$foreign_column");

            # Fully-qualified table names
            #push(@{$joins[$i]{'conditions'}}, "$tables[-1].$local_column = $tables[$parent_tn - 1].$foreign_column");

            $joins[$i]{'type'} = $join_type{$arg} || 'LEFT OUTER JOIN';
            $joins[$i]{'hints'} = $hints->{"t$i"} || $hints->{$name};
          }
          else
          {
            if($use_explicit_joins)
            {
              # Aliased table names
              push(@{$joins[$i]{'conditions'}}, "t$i.$local_column = t${parent_tn}.$foreign_column");

              # Fully-qualified table names
              #push(@{$joins[$i]{'conditions'}}, "$tables[-1].$local_column = $tables[$parent_tn - 1].$foreign_column");

              $joins[$i]{'type'} = $join_type{$arg} || 'JOIN';
              $joins[$i]{'hints'} = $hints->{"t$i"} || $hints->{$name};
            }
            else # implicit join with no ON clause
            {
              # Aliased table names
              push(@$clauses, "t$i.$local_column = t${parent_tn}.$foreign_column");

              # Fully-qualified table names
              #push(@$clauses, "$tables[-1].$local_column = $tables[$parent_tn - 1].$foreign_column");
            }
          }
        }

        $joins[$i]{'parent_tn'} = $parent_tn  if($joins[$i] && $joins[$i]{'type'} eq 'JOIN');

        #
        # Now add table, columns, and clauses for the foreign object
        #

        $num_subtables++; # Account for the extra table

        my $ft_class = $rel->foreign_class 
          or Carp::confess "$class - Missing foreign class for '$name'";

        my $ft_meta = $ft_class->meta; 
        $meta{$ft_class} = $ft_meta;

        my $map_to = $rel->map_to 
          or Carp::confess "Missing map_to value for relationship '$name' ",
                           "in clas $class";

        my $foreign_rel = 
          $map_meta->foreign_key($map_to)  || $map_meta->relationship($map_to) ||
            Carp::confess "No foreign key or relationship named '$map_to' ",
                          "found in $map_class";        

        my $ft_columns = $foreign_rel->key_columns 
          or Carp::confess "$ft_class - Missing key columns for '$map_to'";

        push(@tables, $ft_meta->fq_table($db));
        push(@tables_sql, $ft_meta->fq_table_sql($db));
        push(@rel_names, $rel_name{'t' . (scalar @tables)} = $rel->name);
        push(@table_names, $ft_meta->table);
        push(@classes, $ft_class);

        my $use_lazy_columns = (!ref $nonlazy || $nonlazy{$name}) ? 0 : $ft_meta->has_lazy_columns;

        if($use_lazy_columns)
        {
          $columns{$tables[-1]}     = $ft_meta->nonlazy_columns;
          $all_columns{$tables[-1]} = $ft_meta->columns;
          $methods{$tables[-1]}     = $ft_meta->nonlazy_column_mutator_method_names;
          $di_keys{$classes[-1]}    = $ft_meta->nonlazy_column_db_value_hash_keys;
        }
        else
        {
          $columns{$tables[-1]}  = $ft_meta->columns;   
          $methods{$tables[-1]}  = $ft_meta->column_mutator_method_names;        
          $di_keys{$classes[-1]} = $ft_meta->column_db_value_hash_keys;
        }

        $classes{$tables[-1]} = $ft_class;

        # Iterator will be the tN value: the first sub-table is t2, and so on.
        # Increase again for foreign table.
        $i++;

        $subobject_methods[$i - 1] =
          $direct_inject ? $rel->hash_key :
          $rel->method_name('get_set') ||
          $rel->method_name('get_set_now') ||
          $rel->method_name('get_set_on_save') ||
          Carp::confess "No 'get_set', 'get_set_now', or 'get_set_on_save' ",
                        "method found for relationship '$name' in class ",
                        "$class";

        #$subobject_keys[$i - 1] = $rel->hash_key;

        # Reset each() iterator
        #keys(%$ft_columns);

        # Add join condition(s)
        while(my($local_column, $foreign_column) = each(%$ft_columns))
        {
          # Use left joins if the map table used an outer join above
          if($outer_joins || $with_objects{$arg})
          {
            # Aliased table names
            push(@{$joins[$i]{'conditions'}}, 't' . ($i - 1) . ".$local_column = t$i.$foreign_column");

            # Fully-qualified table names
            #push(@{$joins[$i]{'conditions'}}, "$tables[-2].$local_column = $tables[-1].$foreign_column");

            $joins[$i]{'type'} = $join_type{$arg} || 'LEFT OUTER JOIN';
            $joins[$i]{'hints'} = $hints->{"t$i"} || $hints->{$name};
          }
          else
          {
            if($use_explicit_joins)
            {
              # Aliased table names
              push(@{$joins[$i]{'conditions'}}, 't' . ($i - 1) . ".$local_column = t$i.$foreign_column");

              # Fully-qualified table names
              #push(@{$joins[$i]{'conditions'}}, "$tables[-2].$local_column = $tables[-1].$foreign_column");

              $joins[$i]{'type'} = $join_type{$arg} || 'JOIN';
              $joins[$i]{'hints'} = $hints->{"t$i"} || $hints->{$name};
            }
            else # implicit join with no ON clause
            {
              # Aliased table names
              push(@$clauses, 't' . ($i - 1) . ".$local_column = t$i.$foreign_column");

              # Fully-qualified table names
              #push(@$clauses, "$tables[-2].$local_column = $tables[-1].$foreign_column");
            }
          }
        }

        $joins[$i]{'parent_tn'} = $i - 1  if($joins[$i] && $joins[$i]{'type'} eq 'JOIN');

        # Add sub-object sort conditions
        if($rel->can('manager_args') && (my $mgr_args = $rel->manager_args))
        {
          # Don't bother sorting by columns if we're not even selecting them
          if($mgr_args->{'sort_by'} && (!%fetch || 
             ($fetch{$tables[-1]} && !$fetch{$rel_names[-1]})))
          {
            my $sort_by = ref $mgr_args->{'sort_by'} eq 'ARRAY' ?
              [ @{$mgr_args->{'sort_by'}} ] : [ $mgr_args->{'sort_by'} ];

            # translate un-prefixed simple columns
            foreach my $sort (@$sort_by)
            {
              no warnings 'uninitialized';
              $sort =~ s/^(['"`]?)(\w+)\1(\s+(?:ASC|DESC))?$/t$i.$1$2$1$3/i
                unless(ref $sort);
            }

            push(@{$args{'sort_by'}}, @$sort_by);
          }
        }
      }
      else
      {
        Carp::croak "Don't know how to auto-join relationship '$name' of type '$rel_type'";
      }
    }

    $args{'clauses'} = $clauses; # restore clauses arg
  }

  # Flesh out list of fetch tables and cull columns for those tables
  if(%fetch)
  {
    foreach my $i (1 .. $#tables) # skip first table, which is always selected
    {
      my $tn = 't' . ($i + 1);
      my $rel_name = $rel_name{$tn} || '';

      (my $trimmed_table = $tables[$i]) =~ s/^[^.]+\.//;

      unless($fetch{$tn} || $fetch{$tables[$i]} || $fetch{$trimmed_table} || 
             $fetch{$rel_names[$i]} || $fetch{$rel_name})
      {
        $columns{$tables[$i]} = [];
        $methods{$tables[$i]} = [];
      }
    }
  }

  $args{'table_map'} = { reverse %rel_tn };

  my %tn;

  if($select)
  {
    if($fetch)
    {
      Carp::croak "The 'select' and 'fetch' parameters cannot be used together";
    }

    $select = [ split(/\s*,\s*/, $select) ]  unless(ref $select);

    my $i = 1;
    %tn = map { $_ => $i++ } @table_names; # @tables;
    my $expand_dotstar = 0;

    foreach my $item (@$select)
    {
      my($column, $tn);

      next  if(ref $item eq 'SCALAR');

      if(index($item, '.') < 0 && $item !~ /\s+ AS \s+ \w+ \s* \Z/xi)
      {
        $expand_dotstar = 1  if($item eq '*');
        $column = $item;
        $item = "t1.$item"  if($table_aliases > 0);
        $tn = 1;
      }
      elsif($item =~ /^t(\d+)\.(.+)$/)
      {
        $tn     = $1;
        $item   = $2 unless($table_aliases);
        $column = $2;
        $expand_dotstar = 1  if($item =~ /^t\d+\.\*$/);
      }
      elsif($item =~ /^(['"]?)([^.(]+)\1\.(['"]?)(.+)(\3)$/)
      {
        my $num = $tn{$2} || $rel_tn{$2};
        $item = "t$num.$3$4$5";
        $tn = $num;
        $column = $4;
        $expand_dotstar = 1  if($item =~ /^t\d+\.\*$/);
      }

      if(defined $tn)
      {
        my $meta = $meta{$classes{$tables[$tn - 1]}};

        if($meta->column($column) && (my $alias = $meta->column($column)->alias))
        {
          $item .= ' AS ' . $alias  unless($alias eq $column);
        }
      }
    }

    # Expand tN.* specifiers, if necessary
    if($expand_dotstar)
    {
      my @select;

      foreach my $item (@$select)
      {
        next  if(ref $item eq 'SCALAR');

        unless($item =~ /^(?: t(\d+)\. )? \* $/x)
        {
          push(@select, $item);
          next;
        }

        my $tn = $1 || 1;
        my $meta = $meta{$classes{$tables[$tn - 1]}};
        my $prefix = $table_aliases ? "t$tn." : '';

        foreach my $column ($meta->columns)
        {
          if(my $alias = $column->alias)
          {
            push(@select, "$prefix$column AS $alias");
          }
          else
          {
            push(@select, "$prefix$column");
          }
        }
      }

      $select = \@select;
    }

    $args{'select'} = $select;
  }

  if($count_only)
  {
    delete $args{'limit'};
    delete $args{'offset'};
    delete $args{'sort_by'};

    my($sql, $bind, @bind_params);

    # Do we have to use DISTINCT to count?
    my $use_distinct = (delete $args{'distinct'} || $with_objects) ? 1 : 0;

    if(!$use_distinct && $require_objects)
    {
      foreach my $name (@$require_objects)
      {
        # Ignore error here since it'll be caught and handled later anyway
        my $key = 
          $meta->foreign_key($name) || $meta->relationship($name) || next;

        my $rel_type = $key->type;

        if(index($key->type, 'many') >= 0)
        {
          $use_distinct = 1;
          last;
        }
      }
    }

    BUILD_SQL:
    {
      my($select, $wrap);

      my $pk_columns = $meta->primary_key_column_names;

      if(!$use_distinct || @$pk_columns == 1 || 
         $db->supports_multi_column_count_distinct)
      {
        my $select_arg = delete $args{'select'};

        $select = $use_distinct ? 
          'COUNT(DISTINCT ' .  join(', ', ($select_arg ? @$select_arg : (map { "t1.$_" } @$pk_columns))) . ')' :
          'COUNT(*)';
      }
      else
      {
        $select = $use_distinct ? 
          'DISTINCT ' . join(', ', map { "t1.$_" } @$pk_columns) : 'COUNT(*)';
        $wrap = 1;
      }

      local $Carp::CarpLevel = $Carp::CarpLevel + 1;

      ($sql, $bind) =
        build_select(dbh          => $dbh,
                     select       => $select,
                     tables       => \@tables,
                     tables_sql   => \@tables_sql,
                     columns      => \%columns,
                     all_columns  => \%all_columns,
                     classes      => \%classes,
                     joins        => \@joins,
                     meta         => \%meta,
                     db           => $db,
                     pretty       => $Debug,
                     bind_params  => \@bind_params,
                     object_class => $object_class,
                     %args);

      if($wrap)
      {
        $sql = "SELECT COUNT(*) FROM ($sql) sq";
      }
    }

    if($return_sql)
    {
      $db->release_dbh  if($dbh_retained);
      return wantarray ? ($sql, $bind) : $sql;
    }

    my $count = 0;

    my $error;

    TRY:
    {
      local $@;

      eval
      {
        local $dbh->{'RaiseError'} = 1;
        $Debug && warn "$sql (", join(', ', @$bind), ")\n";
        my $sth = $prepare_cached ? $dbh->prepare_cached($sql, undef, 3) : 
                                    $dbh->prepare($sql);

        if(@bind_params)
        {
          my $i = 1;

          foreach my $value (@$bind)
          {
            $sth->bind_param($i, $value, $bind_params[$i - 1]);
            $i++;
          }

          $sth->execute;
        }
        else
        {
          $sth->execute(@$bind);
        }

        ($count) = $sth->fetchrow_array;
        $sth->finish;
      };

      $error = $@;
    }

    if($error)
    {
      $class->total(undef);
      $class->error(ref $error ? $error : "get_objects() - $error");
      $class->handle_error($class);
      return undef;
    }

    $class->total($count);
    return $count;
  }

  # Post-process sort_by args
  if(my $sort_by = $args{'sort_by'})
  {
    # Alter sort_by SQL, replacing table and relationship names with aliases.
    # This is to prevent databases like PostgreSQL from "adding missing FROM
    # clause"s.  See: http://sql-info.de/postgresql/postgres-gotchas.html#1_5
    if($table_aliases)
    {
      my $i = 0;

      foreach my $table (@tables)
      {
        $i++; # Table aliases are 1-based

        my $table_unquoted = $db->unquote_table_name($table);

        # Conditionalize schema part, if necessary
        $table_unquoted =~ s/^([^.]+\.)/(?:\Q$1\E)?/;

        foreach my $sort (grep { !ref } @$sort_by)
        {
          no warnings 'uninitialized';
          unless($sort =~ s/^(['"`]?)(\w+)\1(\s+(?:ASC|DESC))?$/t1.$1$2$1$3/i ||
                 $sort =~ s/\b$table_unquoted\./t$i./g)
          {
            if(my $rel_name = $rel_name{"t$i"})
            {
              $sort =~ s/\b$rel_name\./t$i./g  unless($rel_name =~ /^t\d+$/);
            }
          }
        }
      }

      # When selecting sub-objects via a "... to many" relationship, force
      # a sort by t1's primary key unless sorting by some other column in
      # t1.  This is required to ensure that all result rows from each row
      # in t1 are grouped together.  But don't do it when we're selecting
      # columns from just one table.  (Compare to 3 because the primary table
      # name, fully-qualified name, and the "t1" alias are always in the list.)
      if($num_to_many_rels > 0 && (!%fetch || (keys %fetch || 0) > 3) && !$no_forced_sort)
      {
        my $do_prefix = 1;

        foreach my $sort (@$sort_by)
        {
          if(!ref $sort && $sort =~ /^t1\./)
          {
            $do_prefix = 0;
            last;
          }
        }

        if($do_prefix)
        {
          unshift(@$sort_by, join(', ', map { "t1.$_" } $meta->primary_key_column_names));
        }
      }
    }
    else # otherwise, trim t1. prefixes
    {
      my $prefix_re = '\b(?:t1|' . $meta->table . ')\.';
      $prefix_re = qr($prefix_re);

      foreach my $sort (@$sort_by)
      {
        $sort =~ s/$prefix_re//g  unless(ref $sort);
      }
    }

    # TODO: remove duplicate/redundant sort conditions
    $args{'sort_by'} = $sort_by;
  }
  elsif($num_to_many_rels > 0 && (!%fetch || (keys %fetch || 0) > 3) && !$no_forced_sort)
  {
    # When selecting sub-objects via a "... to many" relationship, force a
    # sort by t1's primary key to ensure that all result rows from each
    # row in t1 are grouped together.  But don't do it when we're selecting
    # columns from just one table. (Compare to 3 because the primary table
    # name, fully-qualified name, and the "t1" alias are always in the list.)
    $args{'sort_by'} = [ join(', ', map { "t1.$_" } $meta->primary_key_column_names) ];
  }

  if(defined $args{'offset'})
  {
    Carp::croak "Offset argument is invalid without a limit argument"
      unless($args{'limit'} || $manual_limit);

    if($db->supports_limit_with_offset && !$manual_limit && !$subselect_limit)
    {
      $db->format_limit_with_offset($args{'limit'}, $args{'offset'}, \%args);
      #$args{'limit'} = $db->format_limit_with_offset($args{'limit'}, $args{'offset'});
      #delete $args{'offset'};
      $skip_first = 0;
    }
    elsif($manual_limit)
    {
      $skip_first += delete $args{'offset'};
    }
    else
    {
      $skip_first += delete $args{'offset'};
      $args{'limit'} += $skip_first;
      $db->format_limit_with_offset($args{'limit'}, undef, \%args);
      #$args{'limit'} = $db->format_limit_with_offset($args{'limit'});
    }
  }
  elsif($args{'limit'})
  {
    $db->format_limit_with_offset($args{'limit'}, undef, \%args);
    #$args{'limit'} = $db->format_limit_with_offset($args{'limit'});
  }

  my($count, @objects, $iterator);

  my($sql, $bind, @bind_params);

  BUILD_SQL:
  {
    local $Carp::CarpLevel = $Carp::CarpLevel + 1;

    ($sql, $bind) =
      build_select(dbh          => $dbh,
                   tables       => \@tables,
                   tables_sql   => \@tables_sql,
                   columns      => \%columns,
                   all_columns  => \%all_columns,
                   classes      => \%classes,
                   joins        => \@joins,
                   meta         => \%meta,
                   db           => $db,
                   pretty       => $Debug,
                   bind_params  => \@bind_params,
                   object_class => $object_class,
                   %args);

    if($subselect_limit)
    {
      my($class, %sub_args) = @_;

      # The sort clause is important, so it can't be deleted, but it 
      # also can't contain references to any table but t1.
      if($args{'sort_by'} && $num_subtables > 0)
      {
        my @sort_by;

        foreach my $arg (@{$args{'sort_by'}})
        {
          push(@sort_by, $arg)  if(index((ref $arg ? $$arg : $arg), 't1.') == 0);
        }

        $sub_args{'sort_by'} = \@sort_by;
      }

      # Not safe to delete this if the query references columns in these tables
      #delete $sub_args{'with_objects'};

      $sub_args{'fetch_only'}  = [ 't1' ];
      $sub_args{'from_and_where_only'} = 1;

      my @t1_bind_params;
      $sub_args{'bind_params'} = \@t1_bind_params;

      my($t1_sql, $t1_bind) = $class->get_objects_sql(%sub_args);

      my $columns = $sub_args{'select'};

      unless($columns)
      {
        my $multi_table = 
          ($sub_args{'with_objects'} && (!ref $sub_args{'with_objects'} || @{$sub_args{'with_objects'}})) ||
          ($sub_args{'require_objects'} && (!ref $sub_args{'require_objects'} || @{$sub_args{'require_objects'}}));

        if($multi_table)
        {
          $table_aliases = 1;
        }
        else
        {
          $table_aliases = $multi_table  unless(defined $table_aliases);
        }

        $columns = $table_aliases ?
          join(', ', map { "t1.$_" } @{$columns{$tables[0]}}) :
          join(', ', map { $_ } @{$columns{$tables[0]}});
      }

      my $distinct = ($num_with_objects && scalar @{[ @has_dups[1 .. $num_with_objects] ]}) ? ' DISTINCT' : '';

      $t1_sql = "SELECT$distinct $columns FROM\n$t1_sql";
      $t1_sql =~ s/^/    /mg  if($Debug);
      $t1_sql = $db->format_select_from_subselect($t1_sql);

      $sql =~ s/(\nFROM\n\s*)\S.+\s+t1\b/$1$t1_sql t1/;

      unshift(@$bind, @$t1_bind);

      if(@t1_bind_params)
      {
        unshift(@bind_params, @t1_bind_params);
      }
    }
  }

  if($return_sql)
  {
    $db->release_dbh  if($dbh_retained);
    return wantarray ? ($sql, $bind) : $sql;
  }

  my $error;

  TRY:
  {
    local $@;

    eval
    {
      local $dbh->{'RaiseError'} = 1;

      $Debug && warn "$sql (", join(', ', @$bind), ")\n";
      # $meta->prepare_select_options (defunct)
      my $sth = $prepare_cached ? $dbh->prepare_cached($sql, undef, 3) : 
                                  $dbh->prepare($sql) or die $dbh->errstr;

      $sth->{'RaiseError'} = 1;

      if(@bind_params)
      {
        my $i = 1;

        foreach my $value (@$bind)
        {
          $sth->bind_param($i, $value, $bind_params[$i - 1]);
          $i++;
        }

        $sth->execute;
      }
      else
      {
        $sth->execute(@$bind);
      }

      my %row;

      my $col_num   = 1;
      my $table_num = 0;

      if($select)
      {      
        foreach my $orig_item (@$select)
        {
          my($class, $table_num, $column);

          my $item = (ref $orig_item eq 'SCALAR') ? $$orig_item : $orig_item;

          if($item =~ s/\s+AS\s+(\w.+)$//i)
          {
            $column = $1;
          }

          if(index($item, '.') < 0)
          {
            $table_num = 0;
            $class = $classes[$table_num];
            $column ||= $item;
          }
          elsif($item =~ /^t(\d+)\.(.+)$/)
          {
            $table_num = $1 - 1;
            $class = $classes[$table_num];
            $column ||= $2;
          }
          elsif($item =~ /^(['"]?)([^.(]+)\1\.(['"]?)(.+)\3$/)
          {
            my $table = $2;
            $class = $classes{$table};
            $column ||= $4;
            my $table_num = $tn{$table} || $rel_tn{$table};
          }
          else
          {
            $table_num = 0;
            $class = $classes[$table_num];
            $column ||= $item;
          }

          $sth->bind_col($col_num++, \$row{$class,$table_num}{$column});
        }
      }
      else
      {
        if($direct_inject)
        {
          my $driver = $db->driver || 'unknown';

          foreach my $table (@tables)
          {
            my $class   = $classes{$table};
            my $key_map = $di_keys{$class};

            foreach my $column (@{$methods{$table}})
            {
              if($key_map->{$column} eq $column)
              {
                $sth->bind_col($col_num++, \$row{$class,$table_num}{$column});
              }
              else # attribute uses a db-formatted key
              {
                $sth->bind_col($col_num++, \$row{$class,$table_num}{$key_map->{$column},$driver});
              }
            }

            $table_num++;
          }
        }
        else
        {
          foreach my $table (@tables)
          {
            my $class = $classes{$table};

            foreach my $column (@{$methods{$table}})
            {
              $sth->bind_col($col_num++, \$row{$class,$table_num}{$column});
            }

            $table_num++;
          }
        }
      }

      if($return_iterator)
      {
        $iterator = Rose::DB::Object::Iterator->new(active => 1);

        my $count = 0;

        # More trading of code duplication for performance: build custom
        # subroutines depending on how much work needs to be done for
        # each iteration.

        if($with_objects)
        {
          # Ug, we have to handle duplicate data due to "...to many" relationships
          # fetched via outer joins.
          if($handle_dups)# || $deep_joins)
          {
            my(@seen, %seen, @sub_objects);

            #my @pk_columns = $meta->primary_key_column_names;
            my $pk_columns = $meta->primary_key_column_names_or_aliases;

            # Get list of primary key columns for each sub-table
            my @sub_pk_columns;

            foreach my $i (1 .. $num_subtables)
            {
              #$sub_pk_columns[$i + 1] = [ $classes[$i]->meta->primary_key_column_names ];
              $sub_pk_columns[$i + 1] = $classes[$i]->meta->primary_key_column_names_or_aliases;
            }

            my($last_object, %subobjects, %parent_objects);

            weaken(my $witerator = $iterator);

            $iterator->_next_code(sub
            {
              my($self) = shift;

              my $object = 0;
              my $object_is_ready = 0;

              my(@objects, $error);

              TRY:
              {
                local $@;

                eval
                {
                  ROW: for(;;)
                  {
                    last ROW  unless($sth);

                    while($sth->fetch)
                    {
                      my $pk = join(PK_JOIN, map { $row{$object_class,0}{$_} } @$pk_columns);

                      # If this is a new main (t1) table row that we haven't seen before
                      unless($seen[0]{$pk}++)
                      {
                        # First, finish building the last object, if it exists
                        if($last_object)
                        {
                          #$Debug && warn "Finish $object_class $last_object->{'id'}\n";

                          if($direct_inject)
                          {
                            while(my($ident, $parent) = each(%parent_objects))
                            {
                              while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                              {
                                $parent->{$method} = $subobjects;
                              }
                            }                      
                          }
                          else
                          {
                            while(my($ident, $parent) = each(%parent_objects))
                            {
                              local $parent->{STATE_LOADING()} = 1;

                              while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                              {
                                $parent->$method($subobjects);
                              }
                            }
                          }

                          %subobjects = ();
                          %parent_objects = ();

                          # Add the object to the final list of objects that we'll return
                          push(@objects, $last_object);

                          $object_is_ready = 1;
                        }

                        #$Debug && warn "Make $object_class $pk\n";

                        # Now, create the object from this new main table row
                        if($direct_inject)
                        {
                          $object = bless { STATE_IN_DB() => 1, %{$row{$object_class,0}}, %object_args }, $object_class;
                        }
                        else
                        {
                          $object = $object_class->new(%object_args);

                          local $object->{STATE_LOADING()} = 1;
                          $object->init(%{$row{$object_class,0}});
                          $object->{STATE_IN_DB()} = 1;
                        }

                        $last_object = $object; # This is the "last object" from now on
                        @sub_objects = ();      # The list of sub-objects is per-object
                        splice(@seen, 1);       # Sub-objects seen is also per-object,
                                                # so trim it, but leave the t1 table info
                        %seen = ();             # Wipe sub-object parent tracking.
                      }

                      $object ||= $last_object or die "Missing object for primary key '$pk'";

                      my $map_record;

                      foreach my $i (1 .. $num_subtables)
                      {
                        my $mapped_object_method = $mapped_object_methods[$i];
                        next  if(defined $mapped_object_method && !$mapped_object_method);

                        my $class  = $classes[$i];
                        my $tn = $i + 1;

                        # Null primary key columns are not allowed
                        my $sub_pk = join(PK_JOIN, grep { defined } map { $row{$class,$i}{$_} } @{$sub_pk_columns[$tn]});
                        next  unless(length $sub_pk);

                        my $subobject = $seen[$i]{$sub_pk};

                        unless($subobject)
                        {
                          # Make sub-object
                          if($direct_inject)
                          {
                            $subobject = bless { STATE_IN_DB() => 1, %{$row{$class,$i}}, %subobject_args }, $class;
                          }
                          else
                          {    
                            $subobject = $class->new(%subobject_args);
                            local $subobject->{STATE_LOADING()} = 1;
                            $subobject->init(%{$row{$class,$i}});
                            $subobject->{STATE_IN_DB()} = 1;
                          }

                          $seen[$i]{$sub_pk} = $subobject;
                        }

                        # If this object belongs to an attribute that can have more
                        # than one object then just save it for later in the
                        # per-object sub-objects list.
                        if($has_dups[$i])
                        {
                          if($mapped_object_methods[$i])
                          {
                            $map_record = $subobject;
                          }
                          else
                          {
                            if($map_record)
                            {
                              my $method = $mapped_object_methods[$i - 1] or next;

                              if($direct_inject)
                              {
                                $subobject->{$method} = $map_record;
                              }
                              else
                              {
                                local $subobject->{STATE_LOADING()} = 1;
                                $subobject->$method($map_record);
                              }

                              $map_record = 0;
                            }

                            next  if(defined $mapped_object_methods[$i]);

                            if($has_dups[$i] && (my $bt = $belongs_to[$i]))
                            {
                              #$subobjects_belong_to[$i] = $#{$sub_objects[$bt]};

                              my $parent_object = $sub_objects[$bt];

                              # XXX: Special heavyweight subobject pairing in multi-many queries
                              if($multi_many && ref $parent_object eq 'ARRAY' && @$parent_object > 1)
                              {
                                my $maps = $subobject_method_map[$i + 1][$bt];
                                my %check;

                                foreach my $map (@$maps)
                                {
                                  my $subobject_method = $map->[1];
                                  $check{$subobject_method} = $subobject->$subobject_method();
                                }

                                PARENT: foreach my $check_parent (reverse @$parent_object)
                                {
                                  foreach my $map (@$maps)
                                  {
                                    my $parent_method = $map->[0];
                                    next PARENT  unless($check_parent->$parent_method() eq $check{$map->[1]});
                                  }

                                  $parent_object = $check_parent;
                                  last PARENT;
                                }
                              }

                              # XXX: This relies on parent objects coming before child
                              # objects in the list of tables in the FROM clause.
                              $parent_object = $parent_object->[-1] #$parent_object->[$subobjects_belong_to[$i]]
                                if(ref $parent_object eq 'ARRAY');

                              my $method = $subobject_methods[$i];

                              my $ident = refaddr $parent_object;
                              next  if($seen{$ident,$method}{$sub_pk}++);
                              $parent_objects{$ident} = $parent_object;
                              push(@{$subobjects{$ident}{$method}}, $subobject);
                            }
                            else
                            {
                              my $ident = refaddr $object;
                              my $method = $subobject_methods[$i];
                              next  if($seen{$ident,$method}{$sub_pk}++);
                              $parent_objects{$ident} = $object;
                              push(@{$subobjects{$ident}{$method}}, $subobject);
                            }

                            push(@{$sub_objects[$i]}, $subobject);
                          }
                        }
                        else # Otherwise, just assign it
                        {
                          $sub_objects[$i] = $subobject;
                          my $parent_object;

                          if(my $bt = $belongs_to[$i])
                          {
                            $parent_object = $sub_objects[$bt];
                            # XXX: This relies on parent objects coming before
                            # child objects in the list of tables in the FROM
                            # clause.
                            $parent_object = $parent_object->[-1]  if(ref $parent_object eq 'ARRAY');
                          }
                          else
                          {
                            $parent_object = $object;
                          }

                          my $method = $subobject_methods[$i];

                          # Only assign "... to one" values once
                          next  if($seen{refaddr $parent_object,$method}++);

                          if($direct_inject)
                          {
                            $parent_object->{$method} = $subobject;
                          }
                          else
                          {
                            local $parent_object->{STATE_LOADING()} = 1;
                            $parent_object->$method($subobject);
                          }
                        }
                      }

                      if($skip_first)
                      {
                        next ROW  if($seen[0]{$pk} > 1);
                        ++$count  if($seen[0]{$pk} == 1);
                        next ROW  if($count <= $skip_first);

                        $skip_first = 0;
                        @objects = ();        # Discard all skipped objects...
                        $object_is_ready = 0; # ...so none are ready now
                        next ROW;
                      }

                      if($object_is_ready)
                      {
                        $self->{'_count'}++;
                        last ROW;
                      }

                      no warnings;
                      if($manual_limit && $self->{'_count'} == $manual_limit)
                      {
                        $self->finish;
                        last ROW;
                      }
                    }

                    # Handle the left-over "last object" that needs to be finished and
                    # added to the final list of objects to return.
                    if($last_object && !$object_is_ready)
                    {
                      #$Debug && warn "Finish straggler $object_class $last_object->{'id'}\n";

                      if($direct_inject)
                      {
                        while(my($ident, $parent) = each(%parent_objects))
                        {
                          while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                          {
                            $parent->{$method} = $subobjects;
                          }
                        }
                      }
                      else
                      {
                        while(my($ident, $parent) = each(%parent_objects))
                        {
                          local $parent->{STATE_LOADING()} = 1;

                          while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                          {
                            $parent->$method($subobjects);
                          }
                        }
                      }

                      push(@objects, $last_object);

                      # Set everything up to return this object, then be done
                      $last_object = undef;
                      $self->{'_count'}++;
                      $sth = undef;
                      last ROW;
                    }

                    last ROW;
                  }
                };

                $error = $@;
              }

              if($error)
              {
                $self->error(ref $error ? $error : "next() - $error");
                $class->handle_error($self);
                return undef;
              }

              @objects = ()  if($skip_first);

              if(@objects)
              {
                no warnings; # undef count okay
                if($manual_limit && $self->{'_count'} == $manual_limit)
                {
                  $self->total($self->{'_count'});
                  $self->finish;
                }

                #$Debug && warn "Return $object_class $objects[-1]{'id'}\n";
                return shift(@objects);
              }

              #$Debug && warn "Return 0\n";
              return 0;
            });

          }
          else # no duplicate rows to handle
          {
            $iterator->_next_code(sub
            {
              my($self) = shift;

              my $object = 0;

              my $error;

              TRY:
              {
                local $@;

                eval
                {
                  ROW: for(;;)
                  {
                    unless($sth->fetch)
                    {
                      return 0;
                    }

                    next ROW  if($skip_first && ++$count <= $skip_first);

                    if($direct_inject)
                    {
                      $object = bless { STATE_IN_DB() => 1, %{$row{$object_class,0}}, %object_args }, $object_class;
                    }
                    else
                    {
                      $object = $object_class->new(%object_args);

                      local $object->{STATE_LOADING()} = 1;
                      $object->init(%{$row{$object_class,0}});
                      $object->{STATE_IN_DB()} = 1;
                    }

                    my @sub_objects;

                    if($with_objects)
                    {
                      foreach my $i (1 .. $num_subtables)
                      {
                        my $method = $subobject_methods[$i];
                        my $class  = $classes[$i];

                        # Skip undefined subobjects
                        next  unless(grep { defined } values %{$row{$class,$i}});

                        my $subobject;

                        if($direct_inject)
                        {
                          $subobject = bless { STATE_IN_DB() => 1, %{$row{$class,$i}}, %subobject_args }, $class;
                        }
                        else
                        {
                          $subobject = $class->new(%subobject_args);
                          local $subobject->{STATE_LOADING()} = 1;
                          $subobject->init(%{$row{$class,$i}});
                          $subobject->{STATE_IN_DB()} = 1;
                        }

                        $sub_objects[$i] = $subobject;

                        if($direct_inject)
                        {
                          if(my $bt = $belongs_to[$i])
                          {
                            $sub_objects[$bt]->{$method} = $subobject;
                          }
                          else
                          {
                            $object->{$method} = $subobject;
                          }
                        }
                        else
                        {
                          if(my $bt = $belongs_to[$i])
                          {
                            local $sub_objects[$bt]->{STATE_LOADING()} = 1;
                            $sub_objects[$bt]->$method($subobject);
                          }
                          else
                          {
                            local $object->{STATE_LOADING()} = 1;
                            $object->$method($subobject);
                          }
                        }
                      }
                    }

                    $skip_first = 0;
                    $self->{'_count'}++;
                    last ROW;
                  }
                };

                $error = $@;
              }

              if($error)
              {
                $self->error(ref $error ? $error : "next() - $error");
                $class->handle_error($self);
                return undef;
              }

              return $skip_first ? undef : $object;
            });
          }
        }
        else # no sub-objects at all
        {
          $iterator->_next_code(sub
          {
            my($self) = shift;

            my $object = 0;

            my $error;

            TRY:
            {
              local $@;

              eval
              {
                ROW: for(;;)
                {
                  unless($sth->fetch)
                  {
                    #$self->total($self->{'_count'});
                    return 0;
                  }

                  next ROW  if($skip_first && ++$count <= $skip_first);

                  if($direct_inject)
                  {
                    $object = bless { STATE_IN_DB() => 1, %{$row{$object_class,0}}, %object_args }, $object_class;
                  }
                  else
                  {
                    $object = $object_class->new(%object_args);

                    local $object->{STATE_LOADING()} = 1;
                    $object->init(%{$row{$object_class,0}});
                    $object->{STATE_IN_DB()} = 1;
                  }

                  $skip_first = 0;
                  $self->{'_count'}++;
                  last ROW;
                }
              };

              $error = $@;
            }

            if($error)
            {
              $self->error(ref $error ? $error : "next() - $error");
              $class->handle_error($self);
              return undef;
            }

            return $object;
          });
        }

        $iterator->_finish_code(sub
        {
          $sth->finish      if($sth);
          $db->release_dbh  if($db && $dbh_retained);
          $sth = undef;
          $db = undef;
        });

        $iterator->_destroy_code(sub
        {
          $db->release_dbh  if($db && $dbh_retained);
          $sth = undef;
          $db = undef;
        });

        return $iterator;
      }

      $count = 0;

      if($with_objects)
      {
        # This "if" clause is a totally separate code path for handling
        # duplicates rows.  I'm doing this for performance reasons.
        if($handle_dups)# || $deep_joins)
        {
          my(@seen, %seen, @sub_objects);

          #my @pk_columns = $meta->primary_key_column_names;
          my $pk_columns = $meta->primary_key_column_names_or_aliases;

          # Get list of primary key columns for each sub-table
          my @sub_pk_columns;

          foreach my $i (1 .. $num_subtables)
          {
            #$sub_pk_columns[$i + 1] = [ $classes[$i]->meta->primary_key_column_names ];
            $sub_pk_columns[$i + 1] = $classes[$i]->meta->primary_key_column_names_or_aliases;
          }

          my($last_object, %subobjects, %parent_objects);

          ROW: while($sth->fetch)
          {
            my $pk = join(PK_JOIN, map { $row{$object_class,0}{$_} } @$pk_columns);

            my $object;

            # If this is a new main (t1) table row that we haven't seen before
            unless($seen[0]{$pk}++)
            {
              # First, finish building the last object, if it exists
              if($last_object)
              {
                if($direct_inject)
                {
                  while(my($ident, $parent) = each(%parent_objects))
                  {
                    while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                    {
                      $parent->{$method} = $subobjects; # XXX
                    }
                  }              
                }
                else
                {
                  while(my($ident, $parent) = each(%parent_objects))
                  {
                    local $parent->{STATE_LOADING()} = 1;

                    while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                    {
                      $parent->$method($subobjects);
                    }
                  }
                }

                %subobjects = ();
                %parent_objects = ();

                # Add the object to the final list of objects that we'll return
                push(@objects, $last_object);

                if(!$skip_first && $manual_limit && @objects == $manual_limit)
                {
                  last ROW;
                }
              }

              # Now, create the object from this new main table row
              if($direct_inject)
              {
                $object = bless { STATE_IN_DB() => 1, %{$row{$object_class,0}}, %object_args }, $object_class;
              }
              else
              {
                $object = $object_class->new(%object_args);

                local $object->{STATE_LOADING()} = 1;
                $object->init(%{$row{$object_class,0}});
                $object->{STATE_IN_DB()} = 1;
              }

              $last_object = $object; # This is the "last object" from now on.
              @sub_objects = ();      # The list of sub-objects is per-object.
              splice(@seen, 1);       # Sub-objects seen is also per-object,
                                      # so trim it, but leave the t1 table info.
              %seen = ();             # Wipe sub-object parent tracking.
            }

            $object ||= $last_object or die "Missing object for primary key '$pk'";

            my $map_record;

            foreach my $i (1 .. $num_subtables)
            {
              my $mapped_object_method = $mapped_object_methods[$i];
              next  if(defined $mapped_object_method && !$mapped_object_method);

              my $class  = $classes[$i];
              my $tn = $i + 1;

              # Null primary key columns are not allowed
              my $sub_pk = join(PK_JOIN, grep { defined } map { $row{$class,$i}{$_} } @{$sub_pk_columns[$tn]});
              next  unless(length $sub_pk);

              my $subobject = $seen[$i]{$sub_pk};

              unless($subobject)
              {
                # Make sub-object
                if($direct_inject)
                {
                  $subobject = bless { STATE_IN_DB() => 1, %{$row{$class,$i}}, %subobject_args },  $class;
                }
                else
                {    
                  $subobject = $class->new(%subobject_args);
                  local $subobject->{STATE_LOADING()} = 1;
                  $subobject->init(%{$row{$class,$i}});
                  $subobject->{STATE_IN_DB()} = 1;
                }

                $seen[$i]{$sub_pk} = $subobject;
              }

              # If this object belongs to an attribute that can have more
              # than one object then just save it for later in the
              # per-object sub-objects list.
              if($has_dups[$i])
              {
                if($mapped_object_method)
                {
                  $map_record = $subobject;
                }
                else
                {
                  if($map_record)
                  {
                    my $method = $mapped_object_methods[$i - 1] or next;

                    if($direct_inject)
                    {
                      $subobject->{$method} = $map_record;
                    }
                    else
                    {
                      local $subobject->{STATE_LOADING()} = 1;
                      $subobject->$method($map_record);
                    }

                    $map_record = 0;
                  }

                  next  if(defined $mapped_object_methods[$i]);

                  if($has_dups[$i] && (my $bt = $belongs_to[$i]))
                  {
                    #$subobjects_belong_to[$i] = $#{$sub_objects[$bt]};

                    my $parent_object = $sub_objects[$bt];

                    # XXX: Special heavyweight subobject pairing in multi-many queries
                    if($multi_many && ref $parent_object eq 'ARRAY' && @$parent_object > 1)
                    {
                      my $maps = $subobject_method_map[$i + 1][$bt];
                      my %check;

                      foreach my $map (@$maps)
                      {
                        my $subobject_method = $map->[1];
                        $check{$subobject_method} = $subobject->$subobject_method();
                      }

                      PARENT: foreach my $check_parent (reverse @$parent_object)
                      {
                        foreach my $map (@$maps)
                        {
                          my $parent_method = $map->[0];
                          next PARENT  unless($check_parent->$parent_method() eq $check{$map->[1]});
                        }

                        $parent_object = $check_parent;
                        last PARENT;
                      }
                    }

                    # XXX: This relies on parent objects coming before child
                    # objects in the list of tables in the FROM clause.
                    $parent_object = $parent_object->[-1] #$parent_object->[$subobjects_belong_to[$i]]
                      if(ref $parent_object eq 'ARRAY');

                    my $method = $subobject_methods[$i];

                    my $ident = refaddr $parent_object;
                    next  if($seen{$ident,$method}{$sub_pk}++);
                    $parent_objects{$ident} = $parent_object;
                    push(@{$subobjects{$ident}{$method}}, $subobject);
                  }
                  else
                  {
                    my $ident = refaddr $object;
                    my $method = $subobject_methods[$i];
                    next  if($seen{$ident,$method}{$sub_pk}++);
                    $parent_objects{$ident} = $object;
                    push(@{$subobjects{$ident}{$method}}, $subobject);
                  }

                  push(@{$sub_objects[$i]}, $subobject);
                }
              }
              else # Otherwise, just assign it
              {
                push(@{$sub_objects[$i]}, $subobject);

                my $parent_object;

                if(my $bt = $belongs_to[$i])
                {
                  $parent_object = $sub_objects[$bt];
                  # XXX: This relies on parent objects coming before child
                  # objects in the list of tables in the FROM clause.
                  $parent_object = $parent_object->[-1]  if(ref $parent_object eq 'ARRAY');
                }
                else
                {
                  $parent_object = $object;
                }

                my $method = $subobject_methods[$i];

                # Only assign "... to one" values once
                next  if($seen{refaddr $parent_object,$method}++);

                if($direct_inject)
                {
                  $parent_object->{$method} = $subobject;
                }
                else
                {
                  local $parent_object->{STATE_LOADING()} = 1;
                  $parent_object->$method($subobject);
                }
              }
            }

            if($skip_first)
            {
              next ROW  if($seen[0]{$pk} > 1);
              next ROW  if(@objects < $skip_first);

              $skip_first = 0;
              @objects = (); # Discard all skipped objects
              next ROW;
            }
          }

          # Handle the left-over "last object" that needs to be finished and
          # added to the final list of objects to return.
          if($last_object && !$skip_first)
          {
            if($direct_inject)
            {
              while(my($ident, $parent) = each(%parent_objects))
              {
                while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                {
                  $parent->{$method} = $subobjects; # XXX
                }
              }
            }
            else
            {
              while(my($ident, $parent) = each(%parent_objects))
              {
                local $parent->{STATE_LOADING()} = 1;

                while(my($method, $subobjects) = each(%{$subobjects{$ident}}))
                {
                  $parent->$method($subobjects);
                }
              }
            }

            unless($manual_limit && @objects >= $manual_limit)
            {
              push(@objects, $last_object);
            }
          }

          @objects = ()  if($skip_first);
        }
        else # simple sub-objects case: nothing worse than one-to-one relationships
        {
          if($skip_first)
          {
            while($sth->fetch)
            {
              next  if(++$count < $skip_first);
              last;
            }
          }

          while($sth->fetch)
          {
            my $object;

            if($direct_inject)
            {
              $object = bless { STATE_IN_DB() => 1, %{$row{$object_class,0}}, %object_args }, $object_class;
            }
            else
            {
              $object = $object_class->new(%object_args);

              local $object->{STATE_LOADING()} = 1;
              $object->init(%{$row{$object_class,0}});
              $object->{STATE_IN_DB()} = 1;
            }

            my @sub_objects;

            foreach my $i (1 .. $num_subtables)
            {
              my $method = $subobject_methods[$i];
              my $class  = $classes[$i];

              # Skip undefined subobjects
              next  unless(grep { defined } values %{$row{$class,$i}});

              my $subobject;

              if($direct_inject)
              {
                $subobject = bless { STATE_IN_DB() => 1, %{$row{$class,$i}}, %subobject_args }, $class;
              }
              else
              {
                $subobject = $class->new(%subobject_args);
                local $subobject->{STATE_LOADING()} = 1;
                $subobject->init(%{$row{$class,$i}});
                $subobject->{STATE_IN_DB()} = 1;
              }

              $sub_objects[$i] = $subobject;

              if($direct_inject)
              {
                if(my $bt = $belongs_to[$i])
                {
                  $sub_objects[$bt]->{$method} = $subobject;
                }
                else
                {
                  $object->{$method} = $subobject;
                }
              }
              else
              {
                if(my $bt = $belongs_to[$i])
                {
                  local $sub_objects[$bt]->{STATE_LOADING()} = 1;
                  $sub_objects[$bt]->$method($subobject);
                }
                else
                {
                  local $object->{STATE_LOADING()} = 1;
                  $object->$method($subobject);
                }
              }
            }

            push(@objects, $object);
          }
        }
      }
      else # even simpler: no sub-objects at all
      {
        if($skip_first)
        {
          while($sth->fetch)
          {
            next  if(++$count < $skip_first);
            last;
          }
        }

        if($direct_inject)
        {
          my $key_map = $di_keys{$object_class};

          while($sth->fetch)
          {
            push(@objects, bless { STATE_IN_DB() => 1, %{$row{$object_class,0}}, %object_args }, $object_class);
          }
        }
        else
        {
          while($sth->fetch)
          {
            my $object = $object_class->new(%object_args);

            local $object->{STATE_LOADING()} = 1;
            $object->init(%{$row{$object_class,0}});
            $object->{STATE_IN_DB()} = 1;

            push(@objects, $object);
          }
        }
      }

      $sth->finish;
    };

    $error = $@;
  }

  return $iterator  if($iterator);

  $db->release_dbh  if($dbh_retained);

  if($error)
  {
    $class->error(ref $error ? $error : "get_objects() - $error");
    $class->handle_error($class);
    return undef;
  }

  return \@objects;
}

sub _map_action
{
  my($class, $action, @objects) = @_;

  $class->error(undef);

  foreach my $object (@objects)
  {
    unless($object->$action())
    {
      $class->error($object->error);
      $class->handle_error($class);
      return;
    }
  }

  return 1;
}

sub save_objects   { shift->_map_action('save', @_)   }

sub delete_objects
{
  my($class, %args);

  if(ref $_[1])
  {
    $class = shift;

    if(ref $_[0] eq 'HASH')
    {
      %args = (where => [ %{shift(@_)} ], @_);
    }
    elsif(ref $_[0] eq 'ARRAY')
    {
      %args = (where => shift, @_);
    }
    else { Carp::croak 'Invalid arguments: ', join(', ', @_) }

    unshift(@_, $class); # restore original args  
  }
  else
  {
    ($class, %args) = @_;
  }

  $class->error(undef);

  my $object_class = $args{'object_class'} || $class->object_class 
    or Carp::croak "Missing object class argument";

  my $meta = $object_class->meta;

  my $prepare_cached = 
    exists $args{'prepare_cached'} ? $args{'prepare_cached'} :
    $class->dbi_prepare_cached;

  my $db  = $args{'db'} ||= $object_class->init_db;
  my $dbh = $args{'dbh'};
  my $dbh_retained = 0;

  unless($dbh)
  {
    unless($dbh = $db->retain_dbh)
    {
      $class->error($db->error);
      $class->handle_error($class);
      return undef;
    }

    $args{'dbh'} = $dbh;
    $dbh_retained = 1;
  }

  $args{'query'} = delete $args{'where'};

  unless(($args{'query'} && @{$args{'query'}}) || 
         ($args{'clauses'} && @{$args{'clauses'}}) ||
         delete $args{'all'})
  {
    Carp::croak "$class - Refusing to delete all rows from the table '",
                $meta->fq_table($db), "' without an explict ",
                "'all => 1' parameter. (No 'where' or 'clauses' parameters ",
                "were passed to limit the scope of the delete operation.)";
  }

  if($args{'query'} && @{$args{'query'}} && $args{'all'})
  {
    Carp::croak "Illegal use of the 'where' and 'all' parameters in the same call";
  }

  # Yes, I'm re-using get_objects() code like crazy, and often
  # in weird ways.  Shhhh, it's a secret.

  my @bind_params;
  $args{'bind_params'} = \@bind_params;

  # Avert your eyes...
  my($where, $bind) = 
    $class->get_objects(%args, return_sql => 1, where_only => 1, table_aliases => undef);

  my $sql = 'DELETE FROM ' . $meta->fq_table_sql($db) .
            ($where ? " WHERE\n$where" : '');

  my($count, $error);

  TRY:
  {
    local $@;

    eval
    {
      local $dbh->{'RaiseError'} = 1;  
      $Debug && warn "$sql - bind params: ", join(', ', @$bind), "\n";

      # $meta->prepare_bulk_delete_options (defunct)
      my $sth = $prepare_cached ? $dbh->prepare_cached($sql, undef, 3) : 
                                  $dbh->prepare($sql) or die $dbh->errstr;

      if(@bind_params)
      {
        my $i = 1;

        foreach my $value (@$bind)
        {
          $sth->bind_param($i, $value, $bind_params[$i - 1]);
          $i++;
        }

        $sth->execute;
      }
      else
      {
        $sth->execute(@$bind);
      }

      $count = $sth->rows || 0;
    };

    $error = $@;
  }

  if($error)
  {
    $class->error(ref $error ? $error : "delete_objects() - $error");
    $class->handle_error($class);
    return undef;
  }

  return $count;
}

sub update_objects
{
  my($class, %args) = @_;

  $class->error(undef);

  my $object_class = $args{'object_class'} || $class->object_class 
    or Carp::croak "Missing object class argument";

  my $meta = $object_class->meta;

  my $prepare_cached = 
    exists $args{'prepare_cached'} ? $args{'prepare_cached'} :
    $class->dbi_prepare_cached;

  my $db  = $args{'db'} ||= $object_class->init_db;
  my $dbh = $args{'dbh'};
  my $dbh_retained = 0;

  unless($dbh)
  {
    unless($dbh = $db->retain_dbh)
    {
      $class->error($db->error);
      $class->handle_error($class);
      return undef;
    }

    $args{'dbh'} = $dbh;
    $dbh_retained = 1;
  }

  unless(($args{'where'} && @{$args{'where'}}) || delete $args{'all'})
  {
    Carp::croak "$class - Refusing to update all rows in the table '",
                $meta->fq_table_sql($db), "' without an explict ",
                "'all => 1' parameter";
  }

  if($args{'where'} && @{$args{'where'}} && $args{'all'})
  {
    Carp::croak "Illegal use of the 'where' and 'all' parameters in the same call";
  }

  my $where = delete $args{'where'};
  my $set   = delete $args{'set'} 
    or Carp::croak "Missing requires 'set' parameter";

  $set = [ %$set ]  if(ref $set eq 'HASH');

  # Yes, I'm re-using get_objects() code like crazy, and often
  # in weird ways.  Shhhh, it's a secret.

  my @bind_params;
  $args{'bind_params'} = \@bind_params;

  $args{'query'} = $set;

  # Avert your eyes...
  my($set_sql, $set_bind) = 
    $class->get_objects(%args,
                        return_sql    => 1,
                        where_only    => 1,
                        logic         => ',', 
                        set           => 1, 
                        table_aliases => 0);

  my $sql;

  my $where_bind = [];

  if($args{'query'} = $where)
  {
    my $where_sql;

    ($where_sql, $where_bind) = 
      $class->get_objects(%args, 
                          return_sql    => 1,
                          where_only    => 1,
                          table_aliases => 0);

    $sql = 'UPDATE ' . $meta->fq_table_sql($db) . 
           "\nSET\n$set_sql\nWHERE\n$where_sql";
  }
  else
  {
    $sql = 'UPDATE ' . $meta->fq_table_sql($db) . "\nSET\n$set_sql";
  }

  my($count, $error);

  TRY:
  {
    local $@;

    eval
    {
      local $dbh->{'RaiseError'} = 1;  
      $Debug && warn "$sql (", join(', ', @$set_bind, @$where_bind), ")\n";

      # $meta->prepare_bulk_update_options (defunct)
      my $sth = $prepare_cached ? $dbh->prepare_cached($sql, undef, 3) : 
                                  $dbh->prepare($sql) or die $dbh->errstr;

      if(@bind_params)
      {
        my $i = 1;

        foreach my $value (@$set_bind, @$where_bind)
        {
          $sth->bind_param($i, $value, $bind_params[$i - 1]);
          $i++;
        }

        $sth->execute;
      }
      else
      {
        $sth->execute(@$set_bind, @$where_bind);
      }

      $count = $sth->rows || 0;
    };

    $error = $@;
  }

  if($error)
  {
    $class->error(ref $error ? $error : "update_objects() - $error");
    $class->handle_error($class);
    return undef;
  }

  return $count;
}

sub make_manager_method_from_sql
{
  my($class) = shift;

  my %args;

  if(@_ == 2)
  {
    %args = (method => $_[0], sql => $_[1]);
  }
  else { %args = @_ }

  my $named_args = delete $args{'params'};

  my $method = delete $args{'method'} or  Carp::croak "Missing method name";
  my $code;

  $args{'_methods'} = {}; # Will fill in on first run

  my $worker_method = $args{'iterator'} ?
    'get_objects_iterator_from_sql' : 'get_objects_from_sql';

  if($named_args)
  {    
    my @params = @$named_args; # every little bit counts

    $code = sub 
    {
      my($self, %margs) = @_;
      $self->$worker_method(
        %args,
        args => [ delete @margs{@params} ], 
        %margs);
    };
  }
  else
  {
    $code = sub { shift->$worker_method(%args, args => \@_) };
  }

  no strict 'refs';
  *{"${class}::$method"} = $code;

  return $code;
}

sub get_objects_from_sql
{
  my($class) = shift;

  my(%args, $sql);

  if(@_ == 1) { $sql = shift }
  else
  {
    %args = @_;
    $sql = $args{'sql'};
  }

  Carp::croak "Missing SQL"  unless($sql);

  my $object_class = $args{'object_class'} || $class->object_class ||
    Carp::croak "Missing object class";

  my $meta = $object_class->meta 
    or Carp::croak "Could not get meta for $object_class";

  my $prepare_cached = 
    exists $args{'prepare_cached'} ? $args{'prepare_cached'} :
    $class->dbi_prepare_cached;

  my $methods   = $args{'_methods'};
  my $exec_args = $args{'args'} || [];
  my $attr      = $args{'prepare_options'};

  my $have_methods = ($args{'_methods'} && %{$args{'_methods'}}) ? 1 : 0;

  my $db  = delete $args{'db'} || $object_class->init_db;
  my $dbh = delete $args{'dbh'};
  my $dbh_retained = 0;

  unless($dbh)
  {
    unless($dbh = $db->retain_dbh)
    {
      $class->error($db->error);
      $class->handle_error($class);
      return undef;
    }

    $dbh_retained = 1;
  }

  my %object_args =
  (
    (exists $args{'share_db'} ? $args{'share_db'} : 1) ? (db => $db) : ()
  );

  my(@objects, $error);

  TRY:
  {
    local $@;

    eval
    {
      local $dbh->{'RaiseError'} = 1;

      $Debug && warn "$sql (", join(', ', @$exec_args), ")\n";
      my $sth = $prepare_cached ? $dbh->prepare_cached($sql, $attr, 3) : 
                                  $dbh->prepare($sql, $attr) or die $dbh->errstr;

      $sth->execute(@$exec_args);

      while(my $row = $sth->fetchrow_hashref)
      {
        unless($have_methods)
        {
          foreach my $col (keys %$row)
          {
            if($meta->column($col))
            {
              $methods->{$col} = $meta->column_mutator_method_name($col);
            }
            elsif($object_class->can($col))
            {
              $methods->{$col} = $col;
            }
            elsif($meta->column(lc $col))
            {
              $methods->{$col} = $meta->column_mutator_method_name(lc $col);
            }
            elsif($object_class->can(lc $col))
            {
              $methods->{$col} = lc $col;
            }
          }

          $have_methods = 1;
        }

        my $object = $object_class->new(%object_args);

        local $object->{STATE_LOADING()} = 1;
        $object->{STATE_IN_DB()} = 1;

        while(my($col, $val) = each(%$row))
        {
          my $method = $methods->{$col} || $col;
          $object->$method($val);
        }

        $object->{MODIFIED_COLUMNS()} = {};

        push(@objects, $object);
      }
    };

    $error = $@;
  }

  $db->release_dbh  if($dbh_retained);

  if($error)
  {
    $class->total(undef);
    $class->error(ref $error ? $error : "get_objects_from_sql() - $error");
    $class->handle_error($class);
    return undef;
  }

  return \@objects;
}

sub get_objects_iterator_from_sql
{
  my($class) = shift;

  my(%args, $sql);

  if(@_ == 1) { $sql = shift }
  else
  {
    %args = @_;
    $sql = $args{'sql'};
  }

  Carp::croak "Missing SQL"  unless($sql);

  my $object_class = $args{'object_class'} || $class->object_class ||
    Carp::croak "Missing object class";

  weaken(my $meta = $object_class->meta
    or Carp::croak "Could not get meta for $object_class");

  my $prepare_cached = 
    exists $args{'prepare_cached'} ? $args{'prepare_cached'} :
    $class->dbi_prepare_cached;

  my $methods   = $args{'_methods'};
  my $exec_args = $args{'args'} || [];
  my $attr      = $args{'prepare_options'};

  my $have_methods = ($args{'_methods'} && %{$args{'_methods'}}) ? 1 : 0;

  my $db  = delete $args{'db'} || $object_class->init_db;
  my $dbh = delete $args{'dbh'};
  my $dbh_retained = 0;

  unless($dbh)
  {
    unless($dbh = $db->retain_dbh)
    {
      $class->error($db->error);
      $class->handle_error($class);
      return undef;
    }

    $dbh_retained = 1;
  }

  my %object_args =
  (
    (exists $args{'share_db'} ? $args{'share_db'} : 1) ? (db => $db) : ()
  );

  my($sth, $error);

  TRY:
  {
    local $@;

    eval
    {
      local $dbh->{'RaiseError'} = 1;

      $Debug && warn "$sql (", join(', ', @$exec_args), ")\n";
      $sth = $prepare_cached ? $dbh->prepare_cached($sql, $attr, 3) : 
                               $dbh->prepare($sql, $attr) or die $dbh->errstr;

      $sth->execute(@$exec_args);
    };

    $error = $@;
  }

  if($error)
  {
    $db->release_dbh  if($dbh_retained);
    $class->total(undef);
    $class->error(ref $error ? $error : "get_objects_iterator_from_sql() - $error");
    $class->handle_error($class);
    return undef;
  }

  my $iterator = Rose::DB::Object::Iterator->new(active => 1);

  $iterator->_next_code(sub
  {
    my($self) = shift;

    my $object = 0;

    my $error;

    TRY:
    {
      local $@;

      eval
      {
        ROW: for(;;)
        {
          my $row = $sth->fetchrow_hashref or return 0;

          unless($have_methods)
          {
            foreach my $col (keys %$row)
            {
              if($meta->column($col))
              {
                $methods->{$col} = $meta->column_mutator_method_name($col);
              }
              elsif($object_class->can($col))
              {
                $methods->{$col} = $col;
              }
              elsif($meta->column(lc $col))
              {
                $methods->{$col} = $meta->column_mutator_method_name(lc $col);
              }
              elsif($object_class->can(lc $col))
              {
                $methods->{$col} = lc $col;
              }
            }

            $have_methods = 1;
          }

          $object = $object_class->new(%object_args);

          local $object->{STATE_LOADING()} = 1;
          $object->{STATE_IN_DB()} = 1;

          while(my($col, $val) = each(%$row))
          {
            my $method = $methods->{$col};
            $object->$method($val);
          }

          $object->{MODIFIED_COLUMNS()} = {};

          $self->{'_count'}++;
          last ROW;
        }
      };

      $error = $@;
    }

    if($error)
    {
      $self->error(ref $error ? $error : "next() - $error");
      $class->handle_error($self);
      return undef;
    }

    return $object;
  });

  $iterator->_finish_code(sub
  {
    $sth->finish      if($sth);
    $db->release_dbh  if($db && $dbh_retained);
    $sth = undef;
    $db = undef;
  });

  $iterator->_destroy_code(sub
  {
    $db->release_dbh  if($db && $dbh_retained);
    $sth = undef;
    $db = undef;
  });

  return $iterator;
}

sub perl_class_definition
{
  my($class) = shift;

  my $object_class = $class->object_class || $class->_object_class;

  no strict 'refs';
  my @isa = @{"${class}::ISA"};

  my $use_bases = "use base qw(@isa);";

  return<<"EOF";
package $class;

use strict;

$use_bases

use $object_class;

sub object_class { '@{[ $class->object_class || $class->_object_class ]}' }

__PACKAGE__->make_manager_methods('@{[ $class->_base_name ]}');

1;
EOF
}

1;

__END__

=head1 NAME

Rose::DB::Object::Manager - Fetch multiple Rose::DB::Object-derived objects from the database using complex queries.

=head1 SYNOPSIS

  ##
  ## Given the following Rose::DB::Object-derived classes...
  ##

  package Category;

  use base 'Rose::DB::Object';

  __PACKAGE__->meta->setup
  (
    table   => 'categories',
    columns =>
    [
      id          => { type => 'int', primary_key => 1 },
      name        => { type => 'varchar', length => 255 },
      description => { type => 'text' },
    ],

    unique_key => 'name',
  );

  ...

  package CodeName;

  use base 'Rose::DB::Object';

  __PACKAGE__->meta->setup
  (
    table   => 'code_names',
    columns =>
    [
      id          => { type => 'int', primary_key => 1 },
      product_id  => { type => 'int' },
      name        => { type => 'varchar', length => 255 },
      applied     => { type => 'date', not_null => 1 },
    ],

    foreign_keys =>
    [
      product =>
      {
        class       => 'Product',
        key_columns => { product_id => 'id' },
      },
    ],
  );

  ...

  package Product;

  use base 'Rose::DB::Object';

  __PACKAGE__->meta->setup
  (
    table   => 'products',
    columns =>
    [
      id          => { type => 'int', primary_key => 1 },
      name        => { type => 'varchar', length => 255 },
      description => { type => 'text' },
      category_id => { type => 'int' },
      region_num  => { type => 'int' },

      status => 
      {
        type      => 'varchar', 
        check_in  => [ 'active', 'inactive' ],
        default   => 'inactive',
      },

      start_date  => { type => 'datetime' },
      end_date    => { type => 'datetime' },

      date_created  => { type => 'timestamp', default => 'now' },  
      last_modified => { type => 'timestamp', default => 'now' },
    ],

    unique_key => 'name',

    foreign_keys =>
    [
      category =>
      {
        class       => 'Category',
        key_columns =>
        {
          category_id => 'id',
        }
      },
    ],

    relationships =>
    [
      code_names =>
      {
        type  => 'one to many',
        class => 'CodeName',
        column_map   => { id => 'product_id' },
        manager_args => 
        {
          sort_by => CodeName->meta->table . '.applied DESC',
        },
      },
    ],
  );

  ...

  ##
  ## Create a manager class
  ##

  package Product::Manager;

  use base 'Rose::DB::Object::Manager';

  sub object_class { 'Product' }

  __PACKAGE__->make_manager_methods('products');

  # The call above creates the methods shown below.  (The actual 
  # method bodies vary slightly, but this is the gist of it...)
  #
  # sub get_products
  # {
  #   shift->get_objects(@_, object_class => 'Product');
  # }
  #
  # sub get_products_iterator
  # {
  #   shift->get_objects_iterator(@_, object_class => 'Product');
  # }
  #
  # sub get_products_count
  # {
  #   shift->get_objects_count(@_, object_class => 'Product');
  # }
  #
  # sub update_products
  # {
  #   shift->update_objects(@_, object_class => 'Product');
  # }
  #
  # sub delete_products
  # {
  #   shift->delete_objects(@_, object_class => 'Product');
  # }

  ...

  ##
  ## Use the manager class
  ##

  #
  # Get a reference to an array of objects
  #

  $products = 
    Product::Manager->get_products
    (
      query =>
      [
        category_id => [ 5, 7, 22 ],
        status      => 'active',
        start_date  => { lt => '15/12/2005 6:30 p.m.' },
        name        => { like => [ '%foo%', '%bar%' ] },
      ],
      sort_by => 'category_id, start_date DESC',
      limit   => 100,
      offset  => 80,
    );

  foreach my $product (@$products)
  {
    print $product->id, ' ', $product->name, "\n";
  }

  #
  # Get objects iterator
  #

  $iterator = 
    Product::Manager->get_products_iterator
    (
      query =>
      [
        category_id => [ 5, 7, 22 ],
        status      => 'active',
        start_date  => { lt => '15/12/2005 6:30 p.m.' },
        name        => { like => [ '%foo%', '%bar%' ] },
      ],
      sort_by => 'category_id, start_date DESC',
      limit   => 100,
      offset  => 80,
    );

  while($product = $iterator->next)
  {
    print $product->id, ' ', $product->name, "\n";
  }

  print $iterator->total;

  #
  # Get objects count
  #

  $count =
    Product::Manager->get_products_count
    (
      query =>
      [
        category_id => [ 5, 7, 22 ],
        status      => 'active',
        start_date  => { lt => '15/12/2005 6:30 p.m.' },
        name        => { like => [ '%foo%', '%bar%' ] },
      ],
    ); 

   die Product::Manager->error  unless(defined $count);

  print $count; # or Product::Manager->total()

  #
  # Get objects and sub-objects in a single query
  #

  $products = 
    Product::Manager->get_products
    (
      with_objects => [ 'category', 'code_names' ],
      query =>
      [
        category_id => [ 5, 7, 22 ],
        status      => 'active',
        start_date  => { lt => '15/12/2005 6:30 p.m.' },

        # We need to disambiguate the "name" column below since it
        # appears in more than one table referenced by this query. 
        # When more than one table is queried, the tables have numbered
        # aliases starting from the "main" table ("products").  The
        # "products" table is t1, "categories" is t2, and "code_names"
        # is t3.  You can read more about automatic table aliasing in
        # the documentation for the get_objects() method below.
        #
        # "category.name" and "categories.name" would work too, since
        # table and relationship names are also valid prefixes.

        't2.name'   => { like => [ '%foo%', '%bar%' ] },
      ],
      sort_by => 'category_id, start_date DESC',
      limit   => 100,
      offset  => 80,
    );

  foreach my $product (@$products)
  {
    # The call to $product->category does not hit the database
    print $product->name, ': ', $product->category->name, "\n";

    # The call to $product->code_names does not hit the database
    foreach my $code_name ($product->code_names)
    {
      # This call doesn't hit the database either
      print $code_name->name, "\n";
    }
  }

  #
  # Update objects
  #

  $num_rows_updated =
    Product::Manager->update_products(
      set =>
      {
        end_date   => DateTime->now,
        region_num => { sql => 'region_num * -1' }
        status     => 'defunct',
      },
      where =>
      [
        start_date => { lt => '1/1/1980' },
        status     => [ 'active', 'pending' ],
      ]);

  #
  # Delete objects
  #

  $num_rows_deleted =
    Product::Manager->delete_products(
      where =>
      [
        status  => [ 'stale', 'old' ],
        name    => { like => 'Wax%' },
        or =>
        [
          start_date => { gt => '2008-12-30' },
          end_date   => { gt => 'now' },
        ],
      ]);

=head1 DESCRIPTION

L<Rose::DB::Object::Manager> is a base class for classes that select rows from tables fronted by L<Rose::DB::Object>-derived classes.  Each row in the table(s) queried is converted into the equivalent L<Rose::DB::Object>-derived object.

Class methods are provided for fetching objects all at once, one at a time through the use of an iterator, or just getting the object count.  Subclasses are expected to create syntactically pleasing wrappers for L<Rose::DB::Object::Manager> class methods, either manually or with the L<make_manager_methods|/make_manager_methods> method.  A very minimal example is shown in the L<synopsis|/SYNOPSIS> above.

=head1 CLASS METHODS

=over 4

=item B<dbi_prepare_cached [BOOL]>

Get or set a boolean value that indicates whether or not this class will use L<DBI>'s L<prepare_cached|DBI/prepare_cached> method by default (instead of the L<prepare|DBI/prepare> method) when preparing SQL queries.  The default value is false.

=item B<default_limit_with_subselect [BOOL]>

Get or set a boolean value that determines whether or not this class will consider using a sub-query to express C<limit>/C<offset> constraints when fetching sub-objects related through one of the "...-to-many" relationship types.  Not all databases support this syntax, and not all queries can use it even in supported databases.  If this parameter is true, the feature will be used when possible, by default.  The default value is true.

=item B<default_manager_method_types [ LIST | ARRAYREF ]>

Get or set the default list of method types used by the L<make_manager_methods|/make_manager_methods> method.  The default list is C<objects>, C<iterator>, C<count>, C<delete>, and C<update>.

=item B<default_nested_joins [BOOL]>

Get or set a boolean value that determines whether or not this class will consider using nested JOIN syntax when fetching related objects.  Not all databases support this syntax, and not all queries can use it even in supported databases.  If this parameter is true, the feature will be used when possible, by default.  The default value is true.

=item B<default_objects_per_page [NUM]>

Get or set the default number of items per page, as returned by the L<get_objects|/get_objects> method when used with the C<page> and/or C<per_page> parameters.  The default value is 20.

=item B<delete_objects [ PARAMS | ARRAYREF | HASHREF ]>

Delete rows from a table fronted by a L<Rose::DB::Object>-derived class based on PARAMS, where PARAMS are name/value pairs.  Returns the number of rows deleted, or undef if there was an error.

If the first argument is a reference to a hash or array, it is converted to a reference to an array (if necessary) and taken as the value of the C<where> parameter. 

Valid parameters are:

=over 4

=item B<all BOOL>

If set to a true value, this parameter indicates an explicit request to delete all rows from the table.  If both the C<all> and the C<where> parameters are passed, a fatal error will occur.

=item B<db DB>

A L<Rose::DB>-derived object used to access the database.  If omitted, one will be created by calling the L<init_db|Rose::DB::Object/init_db> method of the L<object_class|/object_class>. 

=item B<prepare_cached BOOL>

If true, then L<DBI>'s L<prepare_cached|DBI/prepare_cached> method will be used (instead of the L<prepare|DBI/prepare> method) when preparing the SQL statement that will delete the objects.  If omitted, the default value is determined by the L<dbi_prepare_cached|/dbi_prepare_cached> class method.

=item B<object_class CLASS>

The name of the L<Rose::DB::Object>-derived class that fronts the table from which rows are to be deleted.  This parameter is required; a fatal error will occur if it is omitted.  Defaults to the value returned by the L<object_class|/object_class> class method.

=item B<where ARRAYREF>

The query parameters, passed as a reference to an array of name/value pairs.  These pairs are used to formulate the "where" clause of the SQL query that is used to delete the rows from the table.  Arbitrarily nested boolean logic is supported.

For the complete list of valid parameter names and values, see the documentation for the C<query> parameter of the L<build_select|Rose::DB::Object::QueryBuilder/build_select> function in the L<Rose::DB::Object::QueryBuilder> module.

If this parameter is omitted, this method will refuse to delete all rows from the table and a fatal error will occur.  To delete all rows from a table, you must pass the C<all> parameter with a true value.  If both the C<all> and the C<where> parameters are passed, a fatal error will occur.

=back

=item B<error>

Returns the text message associated with the last error, or false if there was no error.

=item B<error_mode [MODE]>

Get or set the error mode for this class.  The error mode determines what happens when a method of this class encounters an error.  The default setting is "fatal", which means that methods will L<croak|Carp/croak> if they encounter an error.

B<PLEASE NOTE:> The error return values described in the method documentation in the rest of this document are only relevant when the error mode is set to something "non-fatal."  In other words, if an error occurs, you'll never see any of those return values if the selected error mode L<die|perlfunc/die>s or L<croak|Carp/croak>s or otherwise throws an exception when an error occurs.

Valid values of MODE are:

=over 4

=item carp

Call L<Carp::carp|Carp/carp> with the value of the object L<error|Rose::DB::Object/error> as an argument.

=item cluck

Call L<Carp::cluck|Carp/cluck> with the value of the object L<error|Rose::DB::Object/error> as an argument.

=item confess

Call L<Carp::confess|Carp/confess> with the value of the object L<error|Rose::DB::Object/error> as an argument.

=item croak

Call L<Carp::croak|Carp/croak> with the value of the object L<error|Rose::DB::Object/error> as an argument.

=item fatal

An alias for the "croak" mode.

=item return

Return a value that indicates that an error has occurred, as described in the documentation for each method.

=back

In all cases, the class's C<error> attribute will also contain the error message.

=item B<get_objects [ PARAMS | HASHREF | ARRAYREF ]>

Get L<Rose::DB::Object>-derived objects based on PARAMS, where PARAMS are name/value pairs.  Returns a reference to a (possibly empty) array, or undef if there was an error.  

If the first argument is a reference to a hash or array, it is converted to a reference to an array (if necessary) and taken as the value of the C<query> parameter. 

Each table that participates in the query will be aliased.  Each alias is in the form "tN" where "N" is an ascending number starting with 1.  The tables are numbered as follows.

=over 4

=item * The primary table is always "t1"

=item * The table(s) that correspond to each relationship or foreign key named in the C<with_objects> parameter are numbered in order, starting with "t2"

=item * The table(s) that correspond to each relationship or foreign key named in the C<require_objects> parameter are numbered in order, starting where the C<with_objects> table aliases left off.

=back

"Many to many" relationships have two corresponding tables, and therefore will use two "tN" numbers.  All other supported of relationship types only have just one table and will therefore use a single "tN" number.

For example, imagine that the C<Product> class shown in the L<synopsis|/SYNOPSIS> also has a "many to many" relationship named "colors."  Now consider this call:

    $products = 
      Product::Manager->get_products(
        require_objects => [ 'category' ],
        with_objects    => [ 'code_names', 'colors' ],
        multi_many_ok   => 1,
        query           => [ status => 'defunct' ],
        sort_by         => 't1.name');

The "products" table is "t1" since it's the primary table--the table behind the C<Product> class that C<Product::Manager> manages.  Next, the C<with_objects> tables are aliased.  The "code_names" table is "t2".  Since "colors" is a "many to many" relationship, it gets two numbers: "t3" and "t4".  Finally, the C<require_objects> tables are numbered: the table behind the foreign key "category" is "t5".  Here's an annotated version of the example above:

    # Table aliases in the comments
    $products = 
      Product::Manager->get_products(
                           # t5
        require_objects => [ 'category' ],
                           # t2            t3, t4
        with_objects    => [ 'code_names', 'colors' ],
        multi_many_ok   => 1,
        query           => [ status => 'defunct' ],
        sort_by         => 't1.name'); # "products" is "t1"

Also note that the C<multi_many_ok> parameter was used in order to suppress the warning that occurs when more than one "... to many" relationship is included in the combination of C<require_objects> and C<with_objects> ("code_names" (one to many) and "colors" (many to many) in this case).  See the documentation for C<multi_many_ok> below.

The "tN" table aliases are for convenience, and to isolate end-user code from the actual table names.  Ideally, the actual table names should only exist in one place in the entire code base: in the class definitions for each L<Rose::DB::OBject>-derived class.

That said, when using L<Rose::DB::Object::Manager>, the actual table names can be used as well.  But be aware that some databases don't like a mix of table aliases and real table names in some kinds of queries.

Valid parameters to L<get_objects|/get_objects> are:

=over 4

=item B<allow_empty_lists BOOL>

If set to true, C<query> parameters with empty lists as values are allowed.  For example:

    @ids = (); # empty list

    Product::Manager->get_products(
      query =>
      [
        id => \@ids,
        ...
      ]);

By default, passing an empty list as a value will cause a fatal error.

=item B<db DB>

A L<Rose::DB>-derived object used to access the database.  If omitted, one will be created by calling the L<init_db|Rose::DB::Object/init_db> method of the C<object_class>.

=item B<debug BOOL>

If true, print the generated SQL to STDERR.

=item B<distinct [ BOOL | ARRAYREF ]>

If set to any kind of true value, then the "DISTINCT" SQL keyword will be added to the "SELECT" statement.  Specific values trigger the behaviors described below.

If set to a simple scalar value that is true, then only the columns in the primary table ("t1") are fetched from the database.

If set to a reference to an array of table names, "tN" table aliases, or relationship or foreign key names, then only the columns from the corresponding tables will be fetched.  In the case of relationships that involve more than one table, only the "most distant" table is considered.  (e.g., The map table is ignored in a "many to many" relationship.)  Columns from the primary table ("t1") are always selected, regardless of whether or not it appears in the list.

This parameter conflicts with the C<fetch_only> parameter in the case where both provide a list of table names or aliases.  In this case, if the value of the C<distinct> parameter is also reference to an array table names or aliases, then a fatal error will occur.

=item B<fetch_only ARRAYREF>

ARRAYREF should be a reference to an array of table names or "tN" table aliases. Only the columns from the corresponding tables will be fetched.  In the case of relationships that involve more than one table, only the "most distant" table is considered.  (e.g., The map table is ignored in a "many to many" relationship.)  Columns from the primary table ("t1") are always selected, regardless of whether or not it appears in the list.

This parameter conflicts with the C<distinct> parameter in the case where both provide a list of table names or aliases.  In this case, then a fatal error will occur.

=item B<for_update BOOL>

If true, this parameter is translated to be the equivalent of passing the L<lock|/lock> parameter and setting the C<type> to C<for update>.  For example, this:

    for_update => 1

is equivalent to this:

    lock => { type => 'for update' }

See the L<lock|/lock> parameter below for more information.

=item B<hints HASHREF>

A reference to a hash of hints that influence the SQL generated to fetch the objects.  Hints are just "suggestions" and may be ignored, depending on the actual features of the database being queried.  Use the L<debug|/debug> parameter to see the generated SQL.  Most of the current hints apply to MySQL only.  See the relevant documentation for more details:

L<http://dev.mysql.com/doc/refman/5.0/en/select.html>

The hints hash is keyed by tN table aliases or relationship names.  The value of each key is a reference to a hash of hint directives.  In the absence of any key for "t1" or the name of the primary table, the entire hints hash is considered applicable to the primary table.

Valid hint directives are:

=over 4

=item B<all_rows BOOL>

If true, direct the database to choose the query plan that returns all the records as quickly as possible.

=item B<big_result BOOL>

If true, indicate to the database that the result set is expected to be big.

=item B<buffer_result BOOL>

If true, force the result to be put into a temporary table.

=item B<cache BOOL>

If true, ask the database to store the result in its query cache.

=item B<calc_found_rows BOOL>

If true, ask the database to internally calculate the number of rows found, ignoring any L<limit|/limit> or L<offset|/offset> arguments.

=item B<comment TEXT>

Add a comment after the "SELECT" keyword in the query.  TEXT should B<not> be surrounded by any comment delimiters.  The appropriate delimiters will be added automatically.

=item B<first_rows BOOL>

If true, direct the database to choose the query plan that returns the first result record as soon as possible.

=item B<force_index [ INDEX | ARRAYREF ]>

Force the use of the named indexes, specified by an index name or a reference to an array of index names.

=item B<high_priority BOOL>

If true, give this query higher priority.

=item B<ignore_index [ INDEX | ARRAYREF ]>

Ignore the named indexes, specified by an index name or a reference to an array of index names.

=item B<no_cache BOOL>

If true, ask the database not to store the result in its query cache.

=item B<small_result BOOL>

If true, indicate to the database that the result set is expected to be small.

=item B<straight_join BOOL>

If true, ask the database to join the tables in the order that they are listed in the "FROM" clause of the SQL statement.

=item B<strict_ops BOOL>

If true, any comparison operator used in the C<query> that is not listed in the L<Rose::DB::Object::QueryBuilder> documentation will cause a fatal error.  The default value is determined by the L<strict_ops|/strict_ops> class method.

=item B<use_index [ INDEX | ARRAYREF ]>

Prefer to use the named indexes, specified by an index name or a reference to an array of index names.

=back

=item B<inject_results BOOL>

If true, then the data returned from the database will be directly "injected" into the objects returned by this method, bypassing the constructor and column mutator methods for each object class.  The default is false.  This parameter is ignored (i.e., treated as if it were false) if the C<select> parameter is passed.

This parameter is useful for situations where the performance of L<get_objects|/get_objects> is limited by the speed at which L<Rose::DB::Object>-derived objects can be created.  It's safe to set this parameter to true only if the constructor and column mutator methods for all of the classes involved do not have any side-effects (or if it's is okay to bypass any side-effects).

The default L<Rose::DB::Object> L<constructor|Rose::DB::Object/new> and the column mutator methods created by the column classes included in the L<Rose::DB::Object> module distribution do not have any side-effects and should therefore be safe to use with this parameter.

=item B<limit NUM>

Return a maximum of NUM objects.

=item B<limit_with_subselect BOOL>

This parameter controls whether or not this method will consider using a sub-query to express  C<limit>/C<offset> constraints when fetching sub-objects related through one of the "...-to-many" relationship types.  Not all databases support this syntax, and not all queries can use it even in supported databases.  If this parameter is true, the feature will be used when possible.

The default value is determined by the L<default_limit_with_subselect|/default_limit_with_subselect> class method.

=item B<lock [ TYPE | HASHREF ]>

Select the objects using some form of locking.  These lock directives have database-specific behavior and not all directives are supported by all databases.  Consult your database's documentation to find out more.  Use the L<debug|/debug> parameter to see the generated SQL.

The value should be a reference to a hash or a TYPE string, which is equivalent to setting the value of the C<type> key in the hash reference form.  For example, these are both equivalent:

    lock => 'for update'
    lock => { type => 'for update' }

Valid hash keys are:

=over 4

=item B<columns ARRAYREF>

A reference to an array of column names to lock.  The columns may be prefixed with their table name or their C<tN> alias (e.g., C<mytable.mycol> or C<t2.mycol>) or left unadorned if they are not ambiguous.  References to scalars will be de-referenced and used as-is, included literally in the SQL locking clause.

=item B<nowait BOOL>

If true, do not wait to acquire the lock.  If supported, this is usually by adding a C<NOWAIT> directive to the SQL.

=item B<on ARRAYREF>

A reference to an array of items to lock.  Depending on the database, these may be column or tables.  Both column and table names should be specified using dot-separated relationship paths.

For example, C<vendor.region.name> would lock the C<name> column in the table arrived at by traversing the C<vendor> and then the C<region> relationships, starting from the primary table (C<t1>).  Lone column names may also be used, provided they're not ambiguous.

For locking whole tables, C<vendor.region> would lock the table arrived at by traversing the C<vendor> and then the C<region> relationships.  (See the L<require_objects|/require_objects> parameter for more information on relationship traversal.)

Finally, references to scalars will be de-referenced and used as-is, included literally in the SQL locking clause.

=item B<skip_locked BOOL>

If true, skip any locked rows.  If supported, this is usually by adding a C<SKIP LOCKED> clause to the SQL.

=item B<tables ARRAYREF>

A reference to an array of tables to lock.  Table named or C<tN> aliases may be used.  References to scalars will be de-referenced and used as-is, included literally in the SQL locking clause.

=item B<type TYPE>

The type of lock to acquire.  Valid values for TYPE are C<for update> and C<shared>.  This hash key is required unless the L<for_update|/for_update> parameter was passed with a true value.

=item B<wait TIME>

Wait for the specified TIME (generally seconds) before giving up acquiring the lock. If supported, this is usually by adding a C<WAIT ...> clause to the SQL.

=back

You may pass only one of the parameters that specifies "what to lock" (i.e., C<columns>, C<on>, or C<tables>).

=item B<nested_joins BOOL>

This parameter controls whether or not this method will consider using nested JOIN syntax when fetching related objects.  Not all databases support this syntax, and not all queries will use it even in supported databases.  If this parameter is true, the feature will be used when possible.

The default value is determined by the L<default_nested_joins|/default_nested_joins> class method.

=item B<multi_many_ok BOOL>

If true, do not print a warning when attempting to do multiple LEFT OUTER JOINs against tables related by "... to many" relationships.  See the documentation for the C<with_objects> parameter for more information.

=item B<nonlazy [ BOOL | ARRAYREF ]>

By default, L<get_objects|/get_objects> will honor all L<load-on-demand columns|Rose::DB::Object::Metadata::Column/load_on_demand> when fetching objects.  Use this parameter to override that behavior and select all columns instead.

If the value is a true boolean value (typically "1"), then all columns will be fetched for all participating classes (i.e., the main object class as well as any sub-object classes).

The value can also be a reference to an array of relationship names.  The sub-objects corresponding to each relationship name will have all their columns selected.  To refer to the main class (the "t1" table), use the special name "self".

=item B<object_args HASHREF>

A reference to a hash of name/value pairs to be passed to the constructor of each C<object_class> object fetched, in addition to the values from the database.

=item B<object_class CLASS>

The name of the L<Rose::DB::Object>-derived objects to be fetched.  This parameter is required; a fatal error will occur if it is omitted.  Defaults to the value returned by the L<object_class|/object_class> class method.

=item B<offset NUM>

Skip the first NUM rows.  If the database supports some sort of "limit with offset" syntax (e.g., "LIMIT 10 OFFSET 20") then it will be used.  Otherwise, the first NUM rows will be fetched and then discarded.

This parameter can only be used along with the C<limit> parameter, otherwise a fatal error will occur.

=item B<page NUM>

Show page number NUM of objects.  Pages are numbered starting from 1.  A page number less than or equal to zero causes the page number to default to 1.

The number of objects per page can be set by the C<per_page> parameter.  If the C<per_page> parameter is supplied and this parameter is omitted, it defaults to 1 (the first page).

If this parameter is included along with either of the C<limit> or <offset> parameters, a fatal error will occur.

=item B<per_page NUM>

The number of objects per C<page>.   Defaults to the value returned by the L<default_objects_per_page|/default_objects_per_page> class method (20, by default).

If this parameter is included along with either of the C<limit> or <offset> parameters, a fatal error will occur.

=item B<prepare_cached BOOL>

If true, then L<DBI>'s L<prepare_cached|DBI/prepare_cached> method will be used (instead of the L<prepare|DBI/prepare> method) when preparing the SQL statement that will fetch the objects.  If omitted, the default value is determined by the L<dbi_prepare_cached|/dbi_prepare_cached> class method.

=item B<query ARRAYREF>

The query parameters, passed as a reference to an array of name/value pairs.  These pairs are used to formulate the "where" clause of the SQL query that, in turn, is used to fetch the objects from the database.  Arbitrarily nested boolean logic is supported.

For the complete list of valid parameter names and values, see the documentation for the C<query> parameter of the L<build_select|Rose::DB::Object::QueryBuilder/build_select> function in the L<Rose::DB::Object::QueryBuilder> module.

This class also supports an extension to the query syntax supported by L<Rose::DB::Object::QueryBuilder>.  In addition to table names and aliases, column (or column method) names may be prefixed with foreign key or relationship names.  These names may be chained, with dots (".") separating the components.

For example, imagine three tables, C<products>, C<vendors>, and C<regions>, fronted by three L<Rose::DB::Object>-derived classes, C<Product>, C<Vendor>, and C<Region>, respectively.  Each C<Product> has a C<Vendor>, and each C<Vendor> has a C<Region>.

To select only products whose vendors are in the United States, use a query argument like this:

    query => [ 'vendor.region.name' => 'US' ],

This assumes that the C<Product> class has a relationship or foreign key named "vendor" that points to the product's C<Vendor>, and that the C<Vendor> class has a foreign key or relationship named "region" that points to the vendor's C<Region>, and that 'vendor.region' (or any foreign key or relationship name chain that begins with 'vendor.region.') is an argument to the C<with_objects> or C<require_objects> parameters.

Please note that the "L<tN|Rose::DB::Object::QueryBuilder/tables>" table aliases are not allowed in front of these kinds of chained relationship parameters.  (The chain of relationship names specifies the target table, so any "tN" alias would be redundant at best, or present a conflict at worst.)

=item B<require_objects ARRAYREF>

Only fetch rows from the primary table that have all of the associated sub-objects listed in ARRAYREF, a reference to an array of L<foreign key|Rose::DB::Object::Metadata/foreign_keys> or L<relationship|Rose::DB::Object::Metadata/relationships> names defined for C<object_class>.  The supported relationship types are "L<one to one|Rose::DB::Object::Metadata::Relationship::OneToOne>," "L<one to many|Rose::DB::Object::Metadata::Relationship::OneToMany>," and  "L<many to many|Rose::DB::Object::Metadata::Relationship::ManyToMany>".

For each foreign key or relationship name listed in ARRAYREF, another table will be added to the query via an implicit inner join.  The join conditions will be constructed automatically based on the foreign key or relationship definitions.  Note that each related table must have a L<Rose::DB::Object>-derived class fronting it.

Foreign key and relationship names may be chained, with dots (".") separating each name.  For example, imagine three tables, C<products>, C<vendors>, and C<regions>, fronted by three L<Rose::DB::Object>-derived classes, C<Product>, C<Vendor>, and C<Region>, respectively.  Each C<Product> has a C<Vendor>, and each C<Vendor> has a C<Region>.

To fetch C<Product>s along with their C<Vendor>s, and their vendors' C<Region>s, provide a C<with_objects> argument like this:

    require_objects => [ 'vendor.region' ],

This assumes that the C<Product> class has a relationship or foreign key named "vendor" that points to the product's C<Vendor>, and that the C<Vendor> class has a foreign key or relationship named "region" that points to the vendor's C<Region>.

This chaining syntax can be used to traverse relationships of any kind, including "one to many" and "many to many" relationships, to an arbitrary depth.

The following optional suffixes may be added after any name in the chain in order to override the join type used:

    Suffix    Join Type
    ------    ----------
    !         Inner join
    ?         Left outer join

Each link in a C<require_objects> chain uses an inner join by default.  In other words, the following C<require_objects> parameters are all equivalent:

    # These all mean the same thing
    require_objects => [ 'vendor.region'   ]
    require_objects => [ 'vendor!.region!' ]
    require_objects => [ 'vendor.region!'  ]
    require_objects => [ 'vendor!.region'  ]

Thus, it is only really useful to use the C<?> suffix in C<require_objects> parameters (though the C<!> suffixes don't do any harm).  Here's a useful example of a call with hybrid join chain:

    $products =
      Product::Manager->get_products(
        require_objects => [ 'vendor.region?' ]);

All product objects returned would have associated vendor objects, but those vendor objects may or may not have associated region objects.

Note that inner joins may be implicit and L<nested_joins|/nested_joins> may or may not be used.  When in doubt, use the L<debug|/debug> parameter to see the generated SQL.

B<Warning:> there may be a geometric explosion of redundant data returned by the database if you include more than one "... to many" relationship in ARRAYREF.  Sometimes this may still be more efficient than making additional queries to fetch these sub-objects, but that all depends on the actual data.  A warning will be emitted (via L<Carp::cluck|Carp/cluck>) if you include more than one "... to many" relationship in ARRAYREF.  If you're sure you know what you're doing, you can silence this warning by passing the C<multi_many_ok> parameter with a true value.

B<Note:> the C<require_objects> list currently cannot be used to simultaneously fetch two objects that both front the same database table, I<but are of different classes>.  One workaround is to make one class use a synonym or alias for one of the tables.  Another option is to make one table a trivial view of the other.  The objective is to get the table names to be different for each different class (even if it's just a matter of letter case, if your database is not case-sensitive when it comes to table names).

=item B<select [ CLAUSE | ARRAYREF ]>

Select only the columns specified in either a comma-separated string of column names or a reference to an array of column names.  Strings are naively split between each comma.  If you need more complex parsing, please use the array-reference argument format instead.

Column names should be prefixed by the appropriate "tN" table alias, the table name, or the foreign key or relationship name.  The prefix should be joined to the column name with a dot (".").  Examples: C<t2.name>, C<vendors.age>.

Unprefixed columns are assumed to belong to the primary table ("t1") and are explicitly prefixed as such when selecting from more than one table.  If a column name matches C</ AS \w+$/> then no prefix is applied.

If the column name is "*" (e.g., C<t1.*>) then all columns from that table are selected.

If an item in the referenced array is itself a reference to a scalar, then that item will be dereferenced and passed through unmodified.

If selecting sub-objects via the C<with_objects> or C<require_objects> parameters, you must select the primary key columns from each sub-object table.  Failure to do so will cause those sub-objects I<not> to be created.

Be warned that you should provide some way to determine which column or method and which class an item belongs to: a tN prefix, a column name, or at the very least an "... AS ..." alias clause.

If any C<with_objects> or C<require_objects> arguments are included in this call, the C<select> list must include at least the primary key column(s) from each table that contributes to the named relationships.

This parameter conflicts with the C<fetch_only> parameter.  A fatal error will occur if both are used in the same call.

If this parameter is omitted, then all columns from all participating tables are selected (optionally modified by the C<nonlazy> parameter).

=item B<share_db BOOL>

If true, C<db> will be passed to each L<Rose::DB::Object>-derived object when it is constructed.  Defaults to true.

=item B<sort_by [ CLAUSE | ARRAYREF ]>

A fully formed SQL "ORDER BY ..." clause, sans the words "ORDER BY", or a reference to an array of strings or scalar references to be de-referenced as needed, joined with a comma, and appended to the "ORDER BY" clause.

If an argument is a reference to a scalar, then it is passed through to the ORDER BY clause unmodified.

Otherwise, within each string, any instance of "NAME." will be replaced with the appropriate "tN." table alias, where NAME is a table, foreign key, or relationship name.  All unprefixed simple column names are assumed to belong to the primary table ("t1").

If selecting sub-objects (via C<require_objects> or C<with_objects>) that are related through "one to many" or "many to many" relationships, the first condition in the sort order clause must be a column in the primary table (t1).  If this condition is not met, the list of primary key columns will be added to the beginning of the sort order clause automatically.

=item B<table_aliases BOOL>

When only a single table is used in q auery, this parameter controls whether or not the "tN" aliases are used.  If the parameter is not passed, then tables are aliased.  If it is passed with a false value, then tables are not aliased.  When more than one table participates in a query, the "tN" table aliases are always used and this option is ignored.

=item B<unique_aliases BOOL>

If true, and if there is no explicit value for the C<select> parameter and more than one table is participating in the query, then each selected column will be given a unique alias by prefixing it with its table alias and an underscore.  The default value is false.  Example:

    SELECT
      t1.id    AS t1_id,
      t1.name  AS t1_name,
      t2.id    AS t2_id,
      t2.name  AS t2_name
    FROM
      foo AS t1,
      bar AS t2
    WHERE
      ...

These unique aliases provide a technique of last resort for unambiguously addressing a column in a query clause.

=item B<where ARRAYREF>

This is an alias for the C<query> parameter (see above).

=item B<with_map_records [ BOOL | METHOD | HASHREF ]>

When fetching related objects through a "L<many to many|Rose::DB::Object::Metadata::Relationship::ManyToMany>" relationship, objects of the L<map class|Rose::DB::Object::Metadata::Relationship::ManyToMany/map_class> are not retrieved by default.  Use this parameter to override the default behavior.

If the value is "1", then each object fetched through a mapping table will have its associated map record available through a C<map_record()> attribute.

If a method name is provided instead, then each object fetched through a mapping table will have its associated map record available through a method of that name.

If the value is a reference to a hash, then the keys of the hash should be "many to many" relationship names, and the values should be the method names through which the maps records will be available for each relationship.

=item B<with_objects ARRAYREF>

Also fetch sub-objects (if any) associated with rows in the primary table based on a reference to an array of L<foreign key|Rose::DB::Object::Metadata/foreign_keys> or L<relationship|Rose::DB::Object::Metadata/relationships> names defined for C<object_class>.  The supported relationship types are "L<one to one|Rose::DB::Object::Metadata::Relationship::OneToOne>," "L<one to many|Rose::DB::Object::Metadata::Relationship::OneToMany>," and  "L<many to many|Rose::DB::Object::Metadata::Relationship::ManyToMany>".

For each foreign key or relationship name listed in ARRAYREF, another table will be added to the query via an explicit LEFT OUTER JOIN.  (Foreign keys whose columns are all NOT NULL are the exception, however.  They are always fetched via inner joins.)   The join conditions will be constructed automatically based on the foreign key or relationship definitions.  Note that each related table must have a L<Rose::DB::Object>-derived class fronting it.  See the L<synopsis|/SYNOPSIS> for an example.

"Many to many" relationships are a special case.  They will add two tables to the query (the "map" table plus the table with the actual data), which will offset the "tN" table numbering by one extra table.

Foreign key and relationship names may be chained, with dots (".") separating each name.  For example, imagine three tables, C<products>, C<vendors>, and C<regions>, fronted by three L<Rose::DB::Object>-derived classes, C<Product>, C<Vendor>, and C<Region>, respectively.  Each C<Product> has a C<Vendor>, and each C<Vendor> has a C<Region>.

To fetch C<Product>s along with their C<Vendor>s, and their vendors' C<Region>s, provide a C<with_objects> argument like this:

    with_objects => [ 'vendor.region' ],

This assumes that the C<Product> class has a relationship or foreign key named "vendor" that points to the product's C<Vendor>, and that the C<Vendor> class has a foreign key or relationship named "region" that points to the vendor's C<Region>.

This chaining syntax can be used to traverse relationships of any kind, including "one to many" and "many to many" relationships, to an arbitrary depth.  

The following optional suffixes may be added after any name in the chain in order to override the join type used:

    Suffix    Join Type
    ------    ----------
    !         Inner join
    ?         Left outer join

Each link in a C<with_objects> chain uses a left outer join by default.  In other words, the following C<with_objects> parameters are all equivalent:

    # These all mean the same thing
    with_objects => [ 'vendor.region'   ]
    with_objects => [ 'vendor?.region?' ]
    with_objects => [ 'vendor.region?'  ]
    with_objects => [ 'vendor?.region'  ]

Thus, it is only really useful to use the C<!> suffix in C<with_objects> parameters (though the C<?> suffixes don't do any harm).  Here's a useful example of a call with hybrid join chain:

    $products =
      Product::Manager->get_products(
        with_objects => [ 'vendor!.region' ]);

All product objects returned would have associated vendor objects, but those vendor object may or may not have associated region objects.

Note that inner joins may be implicit and L<nested_joins|/nested_joins> may or may not be used.  When in doubt, use the L<debug|/debug> parameter to see the generated SQL.

B<Warning:> there may be a geometric explosion of redundant data returned by the database if you include more than one "... to many" relationship in ARRAYREF.  Sometimes this may still be more efficient than making additional queries to fetch these sub-objects, but that all depends on the actual data.  A warning will be emitted (via L<Carp::cluck|Carp/cluck>) if you include more than one "... to many" relationship in ARRAYREF.  If you're sure you know what you're doing, you can silence this warning by passing the C<multi_many_ok> parameter with a true value.

B<Note:> the C<with_objects> list currently cannot be used to simultaneously fetch two objects that both front the same database table, I<but are of different classes>.  One workaround is to make one class use a synonym or alias for one of the tables.  Another option is to make one table a trivial view of the other.  The objective is to get the table names to be different for each different class (even if it's just a matter of letter case, if your database is not case-sensitive when it comes to table names).

=back

=item B<get_objects_count [PARAMS]>

Accepts the same arguments as L<get_objects|/get_objects>, but just returns the number of objects that would have been fetched, or undef if there was an error.

=item B<get_objects_from_sql [ SQL | PARAMS ]>

Fetch objects using a custom SQL query.  Pass either a single SQL query string or name/value parameters as arguments.  Valid parameters are:

=over 4

=item B<args ARRAYREF>

A reference to an array of arguments to be passed to L<DBI>'s L<execute|DBI/execute> method when the query is run.  The number of items in this array must exactly match the number of placeholders in the SQL query.

=item B<db DB>

A L<Rose::DB>-derived object used to access the database.  If omitted, one will be created by calling the L<init_db|Rose::DB::Object/init_db> method of the C<object_class>.

=item B<object_class CLASS>

The class name of the L<Rose::DB::Object>-derived objects to be fetched.  Defaults to the value returned by the L<object_class|/object_class> class method.

=item B<prepare_cached BOOL>

If true, then L<DBI>'s L<prepare_cached|DBI/prepare_cached> method will be used (instead of the L<prepare|DBI/prepare> method) when preparing the SQL statement that will fetch the objects.  If omitted, the default value is determined by the L<dbi_prepare_cached|/dbi_prepare_cached> class method.

=item B<prepare_options HASHREF>

A reference to a hash of attributes to be passed to L<DBI>'s L<prepare|DBI/prepare> or L<prepare_cached|DBI/prepare_cached> method when preparing the SQL statement.

=item B<share_db BOOL>

If true, C<db> will be passed to each L<Rose::DB::Object>-derived object when it is constructed.  Defaults to true.

=item B<sql SQL>

The SQL query string.  This parameter is required.

=back

Each column returned by the SQL query must be either a column or method name in C<object_class>.  Column names take precedence in the case of a conflict.

Returns a reference to an array of C<object_class> objects.

Examples:

    package Product::Manager;    
    use Product;
    use base 'Rose::DB::Object::Manager';
    sub object_class { 'Product' }
    ...

    $products = Product::Manager->get_objects_from_sql(<<"EOF");
    SELECT * FROM products WHERE sku % 2 != 0 ORDER BY status, type
    EOF

    $products = 
      Product::Manager->get_objects_from_sql(
        args => [ '2005-01-01' ],
        sql  => 'SELECT * FROM products WHERE release_date > ?');

=item B<get_objects_iterator [PARAMS]>

Accepts any valid L<get_objects|/get_objects> arguments, but return a L<Rose::DB::Object::Iterator> object, or undef if there was an error.

=item B<get_objects_iterator_from_sql [PARAMS]>

Accepts any valid L<get_objects_from_sql|/get_objects_from_sql> arguments, but return a L<Rose::DB::Object::Iterator> object, or undef if there was an error.

=item B<get_objects_sql [PARAMS]>

Accepts the same arguments as L<get_objects|/get_objects>, but return the SQL query string that would have been used to fetch the objects (in scalar context), or the SQL query string and a reference to an array of bind values (in list context).

=item B<make_manager_methods PARAMS>

Create convenience wrappers for L<Rose::DB::Object::Manager>'s L<get_objects|/get_objects>, L<get_objects_iterator|/get_objects_iterator>, and L<get_objects_count|/get_objects_count> class methods in the target class.  These wrapper methods will not overwrite any existing methods in the target class.  If there is an existing method with the same name, a fatal error will occur.

PARAMS can take several forms, depending on the calling context.  For a call to L<make_manager_methods|/make_manager_methods> to succeed, the following information must be determined:

=over 4

=item * B<object class>

The class of the L<Rose::DB::Object>-derived objects to be fetched or counted.

=item * B<base name> or B<method name>

The base name is a string used as the basis of the method names.  For example, the base name "products" might be used to create methods named "get_B<products>", "get_B<products>_count", "get_B<products>_iterator", "delete_B<products>", and "update_B<products>".

In the absence of a base name, an explicit method name may be provided instead.  The method name will be used as is.

=item * B<method types>

The types of methods that should be generated.  Each method type is a wrapper for a L<Rose::DB::Object::Manager> class method.  The mapping of method type names to actual L<Rose::DB::Object::Manager> class methods defaults to the following:

    Type        Method
    --------    ----------------------
    objects     get_objects()
    iterator    get_objects_iterator()
    count       get_objects_count()
    delete      delete_objects()
    update      update_objects()

You may override the L<auto_manager_method_name|Rose::DB::Object::ConventionManager/auto_manager_method_name> method in the L<object_class|/object_class>'s L<convention manager|Rose::DB::Object::Metadata/convention_manager> class to customize one or more of these names.

=item * B<target class>

The class that the methods should be installed in.

=back

Here are all of the different ways that each of those pieces of information can be provided, either implicitly or explicitly as part of PARAMS.

=over 4

=item * B<object class>

If an C<object_class> parameter is passed in PARAMS, then its value is used as the object class.  Example:

    $class->make_manager_methods(object_class => 'Product', ...);

If the C<object_class> parameter is not passed, and if the B<target class> inherits from L<Rose::DB::Object::Manager> and has also defined an C<object_class> method, then the return value of that method is used as the object class.  Example:

  package Product::Manager;

  use Rose::DB::Object::Manager;
  our @ISA = qw(Rose::DB::Object::Manager);

  sub object_class { 'Product' }

  # Assume object_class parameter is not part of the ... below
  __PACKAGE__->make_manager_methods(...);

In this case, the object class would be C<Product>.

Finally, if none of the above conditions are met, one final option is considered.  If the B<target class> inherits from L<Rose::DB::Object>, then the object class is set to the B<target class>.

If the object class cannot be determined in one of the ways described above, then a fatal error will occur.

=item * B<base name> or B<method name>

If a C<base_name> parameter is passed in PARAMS, then its value is used as the base name for the generated methods.  Example:

    $class->make_manager_methods(base_name => 'products', ...);

If the C<base_name> parameter is not passed, and if there is only one argument passed to the method, then the lone argument is used as the base name.  Example:

    $class->make_manager_methods('products');

(Note that, since the B<object class> must be derived somehow, this will only work in one of the situations (described above) where the B<object class> can be derived from the calling context or class.)

If a C<methods> parameter is passed with a hash ref value, then each key of the hash is used as the base name for the method types listed in the corresponding value.  (See B<method types> below for more information.)

If a key of the C<methods> hash ends in "()", then it is taken as the method name and is used as is.  For example, the key "foo" will be used as a base name, but the key "foo()" will be used as a method name.

If the base name cannot be determined in one of the ways described above, then the L<auto_manager_base_name|Rose::DB::Object::ConventionManager/auto_manager_base_name> method in the L<object_class|/object_class>'s L<convention manager|Rose::DB::Object::Metadata/convention_manager> is called on to supply a base name.

=item * B<method types>

If an explicit list of method types is not passed to the method, then all of the L<default_manager_method_types|/default_manager_method_types> are created.  Example:

    # Base name is determined by convention manager auto_manager_base_name()
    # method, all default method types created
    $class->make_manager_methods();

    # Base name is "products", all default method types created
    $class->make_manager_methods('products');

    # Base name is "products", all default method types created
    $class->make_manager_methods(base_name => products', ...);

(Again, note that the B<object class> must be derived somehow.)

If a C<methods> parameter is passed, then its value must be a reference to a hash whose keys are base names or method names, and whose values are method types or references to arrays of method types.

If a key ends in "()", then it is taken as a method name and is used as is.  Otherwise, it is used as a base name.  For example, the key "foo" will be used as a base name, but the key "foo()" will be used as a method name.

If a key is a method name and its value specifies more than one method type, then a fatal error will occur.  (It's impossible to have more than one method with the same name.)

Example:

    # Make the following methods:
    #
    # * Base name: products; method types: objects, iterators
    #
    #     get_products()
    #     get_products_iterator()
    #
    # * Method name: product_count; method type: count
    #
    #     product_count()
    #
    $class->make_manager_methods(...,
      methods =>
      {
        'products'        => [ qw(objects iterator) ],
        'product_count()' => 'count'
      });

If the value of the C<methods> parameter is not a reference to a hash, or if both the C<methods> and C<base_name> parameters are passed, then a fatal error will occur.

=item * B<target class>

If a C<target_class> parameter is passed in PARAMS, then its value is used as the target class.  Example:

    $class->make_manager_methods(target_class => 'Product', ...);

If a C<target_class> parameter is not passed, and if the calling class is not L<Rose::DB::Object::Manager>, then the calling class is used as the target class.  Otherwise, the class from which the method was called is used as the target class.  Examples:

    # Target class is Product, regardless of the calling
    # context or the value of $class
    $class->make_manager_methods(target_class => 'Product', ...);

    package Foo;

    # Target class is Foo: no target_class parameter is passed
    # and the calling class is Rose::DB::Object::Manager, so 
    # the class from which the method was called (Foo) is used.
    Rose::DB::Object::Manager->make_manager_methods(
      object_class => 'Bar',
      base_name    => 'Baz');

    package Bar;

    # Target class is Foo: no target_class parameter is passed 
    # and the calling class is not Rose::DB::Object::Manager,
    # so the calling class (Foo) is used.
    Foo->make_manager_methods(object_class => 'Bar',
                              base_name    => 'Baz');

=back

There's a lot of flexibility in this method's arguments (although some might use the word "confusion" instead), but the examples can be pared down to a few common usage scenarios.

The first is the recommended technique, as seen in the L<synopsis|/SYNOPSIS>. Create a separate manager class that inherits from L<Rose::DB::Object::Manager>, override the C<object_class> method to specify the class of the objects being fetched, and then pass a lone base name argument to the call to L<make_manager_methods|/make_manager_methods>.

  package Product::Manager;

  use Rose::DB::Object::Manager;
  our @ISA = qw(Rose::DB::Object::Manager);

  sub object_class { 'Product' }

  __PACKAGE__->make_manager_methods('products');

The second example is used to install object manager methods directly into a L<Rose::DB::Object>-derived class.  I do not recommend this practice; I consider it "semantically impure" for the class that represents a single object to also be the class that's used to fetch multiple objects.  Inevitably, classes grow, and I'd like the "object manager" class to be separate from the object class itself so they can grow happily in isolation, with no potential clashes.

Also, keep in mind that L<Rose::DB::Object> and L<Rose::DB::Object::Manager> have separate L<error_mode|/error_mode> settings which must be synchronized or otherwise dealt with.  Another advantage of using a separate L<Rose::DB::Object::Manager> subclass (as described earlier) is that you can override the L<error_mode|Rose::DB::Object::Manager/error_mode> in your L<Rose::DB::Object::Manager> subclass only, rather than overriding the base class L<Rose::DB::Object::Manager error_mode|Rose::DB::Object::Manager/error_mode>, which may affect other classes.

If none of that dissuades you, here's how to do it:

  package Product;

  use Rose::DB::Object:;
  our @ISA = qw(Rose::DB::Object);

  __PACKAGE__->make_manager_methods('products');

Finally, sometimes you don't want or need to use L<make_manager_methods|/make_manager_methods> at all.  In fact, this method did not exist in earlier versions of this module.  The formerly recommended way to use this class is  still perfectly valid: subclass it and then call through to the base class methods.

  package Product::Manager;

  use Rose::DB::Object::Manager;
  our @ISA = qw(Rose::DB::Object::Manager);

  sub get_products
  {
    shift->get_objects(object_class => 'Product', @_);
  }

  sub get_products_iterator
  {
    shift->get_objects_iterator(object_class => 'Product', @_);
  }

  sub get_products_count
  {
    shift->get_objects_count(object_class => 'Product', @_);
  }

  sub delete_products
  {
    shift->delete_objects(object_class => 'Product', @_);
  }

  sub update_products
  {
    shift->update_objects(object_class => 'Product', @_);
  }

Of course, these methods will all look very similar in each L<Rose::DB::Object::Manager>-derived class.  Creating these identically structured methods is exactly what L<make_manager_methods|/make_manager_methods> automates for you.  

But sometimes you want to customize these methods, in which case the "longhand" technique above becomes essential.  For example, imagine that we want to extend the code in the L<synopsis|/SYNOPSIS>, adding support for a C<with_categories> parameter to the C<get_products()> method.  

  Product::Manager->get_products(date_created    => '10/21/2001', 
                                 with_categories => 1);

  ...

  sub get_products
  {
    my($class, %args) @_;

    if(delete $args{'with_categories'}) # boolean flag
    {
      push(@{$args{'with_objects'}}, 'category');
    }

    Rose::DB::Object::Manager->get_objects(
      %args, object_class => 'Product')
  }

Here we've coerced the caller-friendly C<with_categories> boolean flag parameter into the C<with_objects =E<gt> [ 'category' ]> pair that L<Rose::DB::Object::Manager>'s L<get_objects|/get_objects> method can understand.

This is the typical evolution of an object manager method.  It starts out as being auto-generated by L<make_manager_methods|/make_manager_methods>, then becomes customized as new arguments are added.

=item B<make_manager_method_from_sql [ NAME =E<gt> SQL | PARAMS ]>

Create a class method in the calling class that will fetch objects using a custom SQL query.  The method created will return a reference to an array of objects or a L<Rose::DB::Object::Iterator> object, depending on whether the C<iterator> parameter is set (see below).

Pass either a method name and an SQL query string or name/value parameters as arguments.  Valid parameters are:

=over 4

=item B<iterator BOOL>

If true, the method created will return a L<Rose::DB::Object::Iterator> object.

=item B<object_class CLASS>

The class name of the L<Rose::DB::Object>-derived objects to be fetched.  Defaults to the value returned by the L<object_class|/object_class> class method.

=item B<params ARRAYREF>

To allow the method that will be created to accept named parameters (name/value pairs) instead of positional parameters, provide a reference to an array of parameter names in the order that they should be passed to the call to L<DBI>'s L<execute|DBI/execute> method.

=item B<method NAME>

The name of the method to be created.  This parameter is required.

=item B<prepare_cached BOOL>

If true, then L<DBI>'s L<prepare_cached|DBI/prepare_cached> method will be used (instead of the L<prepare|DBI/prepare> method) when preparing the SQL statement that will fetch the objects.  If omitted, the default value is determined by the L<dbi_prepare_cached|/dbi_prepare_cached> class method.

=item B<share_db BOOL>

If true, C<db> will be passed to each L<Rose::DB::Object>-derived object when it is constructed.  Defaults to true.

=item B<sql SQL>

The SQL query string.  This parameter is required.

=back

Each column returned by the SQL query must be either a column or method name in C<object_class>.  Column names take precedence in the case of a conflict.

Arguments passed to the created method will be passed to L<DBI>'s L<execute|DBI/execute> method when the query is run.  The number of arguments must exactly match the number of placeholders in the SQL query.  Positional parameters are required unless the C<params> parameter is used.  (See description above.)

Returns a code reference to the method created.

Examples:

    package Product::Manager;

    use base 'Rose::DB::Object::Manager';
    ...

    # Make method that takes no arguments
    __PACKAGE__->make_manager_method_from_sql(get_odd_products =><<"EOF");
    SELECT * FROM products WHERE sku % 2 != 0 
    EOF

    # Make method that takes one positional parameter
    __PACKAGE__->make_manager_method_from_sql(get_new_products =><<"EOF");
    SELECT * FROM products WHERE release_date > ?
    EOF

    # Make method that takes named parameters
    __PACKAGE__->make_manager_method_from_sql(
      method => 'get_named_products',
      params => [ qw(type name) ],
      sql    => <<"EOF");
    SELECT * FROM products WHERE type = ? AND name LIKE ?
    EOF

    ...

    $products = Product::Manager->get_odd_products();

    $products = Product::Manager->get_new_products('2005-01-01');

    $products = 
      Product::Manager->get_named_products(
        name => 'Kite%', 
        type => 'toy');

    # Make method that takes named parameters and returns an iterator
    __PACKAGE__->make_manager_method_from_sql(
      method   => 'get_named_products_iterator',
      iterator => 1,
      params   => [ qw(type name) ],
      sql      => <<"EOF");
    SELECT * FROM products WHERE type = ? AND name LIKE ?
    EOF

    $iterator = 
      Product::Manager->get_named_products_iterator(
        name => 'Kite%', 
        type => 'toy');

    while(my $product = $iterator->next)
    {
      ... # do something with $product

      $iterator->finish  if(...); # finish early?
    }

=item B<normalize_get_objects_args [ARGS]>

This method takes ARGS in the forms accepted by L<get_objects|/get_objects> (and other similar methods) and normalizes them into name/value pairs.  Since L<get_objects|/get_objects> can take arguments in many forms, this method is useful when overriding L<get_objects|/get_objects> in a custom L<Rose::DB::Object::Manager> subclass.  Example:


    package Product::Manager;

    use base 'Rose::DB::Object::Manager'; 

    use Product;

    sub object_class { 'Product' }
    ...

    sub get_products
    {
      my($class, %args) = shift->normalize_get_objects_args(@_);

      # Detect, extract, and handle custom argument
      if(delete $args{'active_only'})
      {
        push(@{$args{'query'}}, status => 'active');
      }

      return $class->get_objects(%args); # call through to normal method
    }

Now all of the following calls will work:

    $products =
      Product::Manager->get_products([ type => 'boat' ], sort_by => 'name');

    $products =
      Product::Manager->get_products({ name => { like => '%Dog%' } });

    $products =
      Product::Manager->get_products([ id => { gt => 123 } ], active_only => 1);

=item B<object_class>

Returns the class name of the L<Rose::DB::Object>-derived objects to be managed by this class.  Override this method in your subclass.  The default implementation returns undef.

=item B<perl_class_definition>

Attempts to create the Perl source code that is equivalent to the current class.  This works best for classes created via L<Rose::DB::Object::Metadata>'s L<make_manager_class|Rose::DB::Object::Metadata/make_manager_class> method, but it will also work most of the time for classes whose methods were created using L<make_manager_methods|/make_manager_methods>.

The Perl code is returned as a string.  Here's an example:

  package My::Product::Manager;

  use My::Product;

  use Rose::DB::Object::Manager;
  our @ISA = qw(Rose::DB::Object::Manager);

  sub object_class { 'My::Product' }

  __PACKAGE__->make_manager_methods('products');

  1;

=item B<update_objects [PARAMS]>

Update rows in a table fronted by a L<Rose::DB::Object>-derived class based on PARAMS, where PARAMS are name/value pairs.  Returns the number of rows updated, or undef if there was an error.

Valid parameters are:

=over 4

=item B<all BOOL>

If set to a true value, this parameter indicates an explicit request to update all rows in the table.  If both the C<all> and the C<where> parameters are passed, a fatal error will occur.

=item B<db DB>

A L<Rose::DB>-derived object used to access the database.  If omitted, one will be created by calling the L<init_db|Rose::DB::Object/init_db> method of the C<object_class>.

=item B<object_class CLASS>

The class name of the L<Rose::DB::Object>-derived class that fronts the table whose rows will to be updated.  This parameter is required; a fatal error will occur if it is omitted.  Defaults to the value returned by the L<object_class|/object_class> class method.

=item B<set PARAMS>

The names and values of the columns to be updated.  PARAMS should be a reference to a hash.  Each key of the hash should be a column name or column get/set method name.  If a value is a simple scalar, then it is passed through the get/set method that services the column before being incorporated into the SQL query.

If a value is a reference to a scalar, then it is dereferenced and incorporated into the SQL query as-is.

If a value is a reference to a hash, then it must contain a single key named "sql" and a corresponding value that will be incorporated into the SQL query as-is.

Example:

  $num_rows_updated =
    Product::Manager->update_products(
      set =>
      {
        end_date   => DateTime->now,
        region_num => { sql => 'region_num * -1' }
        count      => \q(count + 1),
        status     => 'defunct',
      },
      where =>
      [
        status  => [ 'stale', 'old' ],
        name    => { like => 'Wax%' }
        or =>
        [
          start_date => { gt => '2008-12-30' },
          end_date   => { gt => 'now' },
        ],
      ]);

The call above would execute an SQL statement something like the one shown below (depending on the database vendor, and assuming the current date was September 20th, 2005):

    UPDATE products SET
      end_date   = '2005-09-20',
      region_num = region_num * -1,
      count      = count + 1, 
      status     = 'defunct'
    WHERE
      status IN ('stale', 'old') AND
      name LIKE 'Wax%' AND
      (
        start_date > '2008-12-30' OR
        end_date   > '2005-09-20'
      )

=item B<where PARAMS>

The query parameters, passed as a reference to an array of name/value pairs.  These PARAMS are used to formulate the "where" clause of the SQL query that is used to update the rows in the table.  Arbitrarily nested boolean logic is supported.

For the complete list of valid parameter names and values, see the documentation for the C<query> parameter of the L<build_select|Rose::DB::Object::QueryBuilder/build_select> function in the L<Rose::DB::Object::QueryBuilder> module.

If this parameter is omitted, this method will refuse to update all rows in the table and a fatal error will occur.  To update all rows in a table, you must pass the C<all> parameter with a true value.  If both the C<all> and the C<where> parameters are passed, a fatal error will occur.

=back

=item B<strict_ops [BOOL]>

Get or set a boolean value that indicates whether using a comparison operator in the C<query> that is not listed in the L<Rose::DB::Object::QueryBuilder> documentation will cause a fatal error.  The default value is false.

=back

=head1 SUPPORT

For an informal overview of L<Rose::DB::Object>, including L<Rose::DB::Object::Manager>, consult the L<Rose::DB::Object::Tutorial>.

    perldoc Rose::DB::Object::Tutorial

Any L<Rose::DB::Object::Manager> questions or problems can be posted to the L<Rose::DB::Object> mailing list.  To subscribe to the list or view the archives, go here:

L<http://groups.google.com/group/rose-db-object>

Although the mailing list is the preferred support mechanism, you can also email the author (see below) or file bugs using the CPAN bug tracking system:

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Rose-DB-Object>

There's also a wiki and other resources linked from the Rose project home page:

L<http://rosecode.org>

=head1 AUTHOR

John C. Siracusa (siracusa@gmail.com)

=head1 LICENSE

Copyright (c) 2010 by John C. Siracusa.  All rights reserved.  This program is
free software; you can redistribute it and/or modify it under the same terms
as Perl itself.