This file is indexed.

/usr/share/perl5/ORLite.pm is in liborlite-perl 1.51-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
package ORLite;

# See POD at end of file for documentation

use 5.006;
use strict;
use Carp              ();
use File::Spec   0.80 ();
use File::Path   2.08 ();
use File::Basename  0 ();
use Params::Util 0.33 ();
use DBI         1.607 ();
use DBD::SQLite  1.27 ();

use vars qw{$VERSION};
BEGIN {
	$VERSION = '1.51';
}

# Support for the 'prune' option
my @PRUNE = ();
END {
	foreach ( reverse @PRUNE ) {
		next unless -e $_;
		require File::Remove;
		File::Remove::remove( \1, $_ );
	}
}





#####################################################################
# Code Generation

sub import {
	my $class = ref($_[0]) || $_[0];

	# Check for debug mode
	my $DEBUG = 0;
	if ( defined Params::Util::_STRING($_[-1]) and $_[-1] eq '-DEBUG' ) {
		$DEBUG = 1;
		pop @_;
	}

	# Check params and apply defaults
	my %params = (
		# Simple defaults here, complex defaults later
		package    => scalar(caller),
		create     => 0,
		cleanup    => '',
		array      => 0,
		xsaccessor => 0,
		shim       => 0,
		tables     => 1,
		views      => 0,
		x_update   => 0,
	);
	if ( defined Params::Util::_STRING($_[1]) ) {
		# Support the short form "use ORLite 'db.sqlite'"
		$params{file} = $_[1];
	} elsif ( Params::Util::_HASHLIKE($_[1]) ) {
		%params = ( %params, %{$_[1]} );
	} else {
		Carp::croak("Missing, empty or invalid params HASH");
	}
	unless (
		defined Params::Util::_STRING($params{file})
		and (
			$params{create}
			or
			-f $params{file}
		)
	) {
		Carp::croak("Missing or invalid file param");
	}
	unless ( defined $params{readonly} ) {
		$params{readonly} = $params{create} ? 0 : ! -w $params{file};
	}
	unless ( Params::Util::_CLASS($params{package}) ) {
		Carp::croak("Missing or invalid package class");
	}

	# Check caching params
	my $cached = undef;
	my $pkg    = $params{package};
	if ( defined $params{cache} ) {
		# Caching is illogical or invalid in some situations
		if ( $params{prune} ) {
			Carp::croak("Cannot set a 'cache' directory while 'prune' enabled");
		}
		unless ( $params{user_version} ) {
			Carp::croak("Cannot set a 'cache' directory without 'user_version'");
		}

		# To make the caching work, the version be defined before ORLite is called.
		no strict 'refs';
		unless ( ${"$pkg\::VERSION"} ) {
			Carp::croak("Cannot set a 'cache' directory without a package \$VERSION");
		}

		# Build the cache file from the super path using an inlined Class::ISA
		my @queue = ( $class );
		my %seen  = ( $pkg => 1 );
		my @parts = ( $pkg => ${"$pkg\::VERSION"} );
		while ( @queue ) {
			my $c = Params::Util::_STRING(shift @queue) or next;
			push @parts, $c => ${"$c\::VERSION"};
			unshift @queue, grep { not $seen{$c}++ } @{"$c\::ISA"};
		}
		$cached = join '-', @parts, user_version => $params{user_version};
		$cached =~ s/[:.-]+/-/g;
		$cached = File::Spec->rel2abs(
			File::Spec->catfile( $params{cache}, "$cached.pm" )
		);
	}

	# Create the parent directory if needed
	my $file    = File::Spec->rel2abs($params{file});
	my $created = ! -f $params{file};
	if ( $created ) {
		my $dir = File::Basename::dirname($file);
		unless ( -d $dir ) {
			my @dirs = File::Path::mkpath( $dir, { verbose => 0 } );
			$class->prune(@dirs) if $params{prune};
		}
		$class->prune($file) if $params{prune};
	}

	# Connect to the database
	my $dsn = "dbi:SQLite:$file";
	my $dbh = DBI->connect( $dsn, undef, undef, {
		PrintError => 0,
		RaiseError => 1,
	} );

	# Schema custom creation support
	if ( $created and Params::Util::_CODELIKE($params{create}) ) {
		$params{create}->( $dbh );
	}

	# Check the schema version before generating
	my $user_version = $dbh->selectrow_arrayref('pragma user_version')->[0];
	if ( exists $params{user_version} and $user_version != $params{user_version} ) {
		Carp::croak("Schema user_version mismatch (got $user_version, wanted $params{user_version})");
	}

	# If caching and the cached version exists, load and shortcut.
	# Don't try to catch exceptions, just let them blow up.
	if ( $cached and -f $cached ) {
		$dbh->disconnect;
		require $cached;
		return 1;
	}

	# Prepare to generate code
	my $readonly   = $params{readonly};
	my $cleanup    = $params{cleanup};
	my $xsaccessor = $params{xsaccessor};
	my $array      = $params{array};

	# Generate the support package code
	my $code = <<"END_PERL";
package $pkg;

use strict;
use Carp              ();
use DBI         1.607 ();
use DBD::SQLite  1.27 ();

my \$DBH = undef;

sub orlite { '$VERSION' }

sub sqlite { '$file' }

sub dsn { '$dsn' }

sub dbh {
	\$DBH or \$_[0]->connect;
}

sub connect {
	DBI->connect( \$_[0]->dsn, undef, undef, {
		PrintError => 0,
		RaiseError => 1,
	} );
}

sub connected {
	defined \$DBH;
}

sub prepare {
	shift->dbh->prepare(\@_);
}

sub do {
	shift->dbh->do(\@_);
}

sub selectall_arrayref {
	shift->dbh->selectall_arrayref(\@_);
}

sub selectall_hashref {
	shift->dbh->selectall_hashref(\@_);
}

sub selectcol_arrayref {
	shift->dbh->selectcol_arrayref(\@_);
}

sub selectrow_array {
	shift->dbh->selectrow_array(\@_);
}

sub selectrow_arrayref {
	shift->dbh->selectrow_arrayref(\@_);
}

sub selectrow_hashref {
	shift->dbh->selectrow_hashref(\@_);
}

sub pragma {
	\$_[0]->do("pragma \$_[1] = \$_[2]") if \@_ > 2;
	\$_[0]->selectrow_arrayref("pragma \$_[1]")->[0];
}

sub iterate {
	my \$class = shift;
	my \$call  = pop;
	my \$sth   = \$class->prepare(shift);
	\$sth->execute(\@_);
	while ( \$_ = \$sth->fetchrow_arrayref ) {
		\$call->() or last;
	}
	\$sth->finish;
}

sub begin {
	\$DBH or
	\$DBH = \$_[0]->connect;
	\$DBH->begin_work;
}

sub rollback {
	\$DBH or return 1;
	\$DBH->rollback;
	\$DBH->disconnect;
	undef \$DBH;
	return 1;
}

sub rollback_begin {
	if ( \$DBH ) {
		\$DBH->rollback;
		\$DBH->begin_work;
	} else {
		\$_[0]->begin;
	}
	return 1;
}

END_PERL

	# If you are a read-write database, we even allow you
	# to commit your transactions.
	$code .= <<"END_PERL" unless $readonly;
sub commit {
	\$DBH or return 1;
	\$DBH->commit;
	\$DBH->disconnect;
	undef \$DBH;
	return 1;
}

sub commit_begin {
	if ( \$DBH ) {
		\$DBH->commit;
		\$DBH->begin_work;
	} else {
		\$_[0]->begin;
	}
	return 1;
}

END_PERL

	# Experimental update support
	if ( $params{x_update} ) {
		$code .= <<"END_PERL";

### EXPERIMENTAL
sub update {
	my \$class = shift;
	my \$table = shift;
	my \$set   = shift;
	my \@cols  = sort keys %\$set;
	my \$sql   = 'update "' . \$table . '" set '
	           . join ', ', map { "\\"\$_\\" = ?" } \@cols;
	   \$sql  .= ' ' . shift if \@_;
	return $pkg->do(
		\$sql, {},
		( map { \$set->{\$_} } \@cols ),
		\@_,
	);
}

END_PERL
	}

	# Cleanup and shutdown operations
	if ( $cleanup ) {
		$code .= <<"END_PERL";
END {
	if ( \$DBH ) {
		\$DBH->rollback;
		\$DBH->do('$cleanup');
		\$DBH->disconnect;
		undef \$DBH;
	} else {
		$pkg->do('$cleanup');
	}
}

END_PERL
	} else {
		$code .= <<"END_PERL";
END {
	$pkg->rollback if \$DBH;
}

END_PERL
	}

	# Optionally generate the table classes
	my $tables = undef;
	if ( $params{tables} ) {
		# Capture the raw schema table information
		$tables = $dbh->selectall_arrayref(
			'select * from sqlite_master where name not like ? and type in ( ?, ? )',
			{ Slice => {} }, 'sqlite_%', 'table', 'view',
		);
		my %tindex = map { $_->{name} => $_ } @$tables;

		# Capture the raw schema column information
		foreach my $table ( @$tables ) {
			# Convenience pre-quoted form of the table name
			$table->{qname} = '"' . $table->{name} . '"';

			# What will be the class for this table
			$table->{class} = $table->{name};
			if ( $table->{class} ne lc $table->{class} ) {
				$table->{class} =~ s/([a-z])([A-Z])/${1}_${2}/g;
				$table->{class} =~ s/_+/_/g;
			}
			$table->{class} = ucfirst lc $table->{class};
			$table->{class} =~ s/_([a-z])/uc($1)/ge;
			$table->{class} = "${pkg}::$table->{class}";

			# Load the column data
			my $columns = $table->{columns} = $dbh->selectall_arrayref(
				"pragma table_info('$table->{name}')",
			 	{ Slice => {} },
			);

			# Convenience escaping for the column names
			foreach my $c ( @$columns ) {
				$c->{qname} = "\"$c->{name}\"";
			}

			# Track array vs hash implementation on a per-table
			# basis so that we can force views to always be done
			# array-wise (to compensate for some weird SQLite
			# column quoting differences between tables and views
			$table->{array} = $array;
			if ( $table->{type} eq 'view' ) {
				$table->{array} = 1;
			}

			# Generate the object keys for the columns
			if ( $table->{array} ) {
				foreach my $i ( 0 .. $#$columns ) {
					$columns->[$i]->{xs}    = $i;
					$columns->[$i]->{key}   = "[$i]";
				}
			} else {
				foreach my $c ( @$columns ) {
					$c->{xs}  = "'$c->{name}'";
					$c->{key} = "{$c->{name}}";
				}
			}

			# Generate the primary key list
			$table->{pk}     = [ grep { $_->{pk} } @$columns ];
			$table->{pks}    = scalar @{$table->{pk}};
			$table->{create} = !! ( $table->{pks} and ! $readonly );

			# Generate the main SQL fragments
			$table->{sql_cols}   = join ', ', map { $_->{qname} } @$columns;
			$table->{sql_vals}   = join ', ', ( '?' ) x scalar @$columns;
			$table->{sql_select} = "select $table->{sql_cols} from $table->{qname}";
			$table->{sql_count}  = "select count(*) from $table->{qname}";
			$table->{sql_insert} =
				"insert into $table->{qname} " .
				"( $table->{sql_cols} ) " .
				"values ( $table->{sql_vals} )";
			$table->{sql_where} = join ' and ',
				map { "$_->{qname} = ?" } @{$table->{pk}};

			# Generate the new Perl fragments
			$table->{pl_new} = join "\n", map {
				$table->{array}
					? "\t\t\$attr{$_->{name}},"
					: "\t\t$_->{name} => \$attr{$_->{name}},"
			} @$columns;

			$table->{pl_insert} = join "\n", map {
				"\t\t\$self->$_->{key},"
			} @$columns;

			if ( $table->{pks} == 1 ) {
				$table->{pl_fill} = "\t\$self->$table->{pk}->[0]->{key} " .
					"= \$dbh->func('last_insert_rowid') " .
					"unless \$self->$table->{pk}->[0]->{key};";
			} else {
				$table->{pl_fill} = '';
			}

			$table->{pl_where} = join "\n", map {
				"\t\t\$self->$_->{key},"
			} @{$table->{pk}};
		}

		# Generate the foreign key metadata
		foreach my $table ( @$tables ) {
			# Locate the foreign keys
			my %fk     = ();
			my @fk_sql = $table->{sql} =~ /[(,]\s*(.+?REFERENCES.+?)\s*[,)]/g;

			# Extract the details
			foreach ( @fk_sql ) {
				unless ( /^(\w+).+?REFERENCES\s+(\w+)\s*\(\s*(\w+)/ ) {
					die "Invalid foreign key $_";
				}
				$fk{"$1"} = [ "$2", $tindex{"$2"}, "$3" ];
			}
			foreach ( @{$table->{columns}} ) {
				$_->{fk} = $fk{$_->{name}};
			}

			# One final code fragment we need the fk for
			$table->{pl_accessor} = join "\n",
				map { "\t\t$_->{name} => $_->{xs}," }
				grep { ! $_->{fk} } @{$table->{columns}};
		}

		# Generate the per-table code
		foreach my $table ( @$tables ) {
			my @columns = @{$table->{columns}};
			my $slice   = $table->{array}
				? '{}'
				: '{ Slice => {} }';

			# Generate the package header
			if ( $params{shim} ) {
				# Generate a shim-wrapper class
				$code .= <<"END_PERL";
package $table->{class};

\@$table->{class}::ISA = '$table->{class}::Shim';

package $table->{class}::Shim;

END_PERL
			} else {
				# Plain vanilla package header
				$code .= <<"END_PERL";
package $table->{class};

END_PERL
			}

			# Generate the common elements for all classes
			$code .= <<"END_PERL";
sub base { '$pkg' }

sub table { '$table->{name}' }

sub table_info {
	$pkg->selectall_arrayref(
		"pragma table_info('$table->{name}')",
		{ Slice => {} },
	);
}

sub select {
	my \$class = shift;
	my \$sql   = '$table->{sql_select} ';
	   \$sql  .= shift if \@_;
	my \$rows  = $pkg->selectall_arrayref( \$sql, $slice, \@_ );
	bless \$_, '$table->{class}' foreach \@\$rows;
	wantarray ? \@\$rows : \$rows;
}

sub count {
	my \$class = shift;
	my \$sql   = '$table->{sql_count} ';
	   \$sql  .= shift if \@_;
	$pkg->selectrow_array( \$sql, {}, \@_ );
}

END_PERL

			# Handle different versions, because arrayref acts funny
			if ( $table->{array} ) {
				$code .= <<"END_PERL";
sub iterate {
	my \$class = shift;
	my \$call  = pop;
	my \$sql   = '$table->{sql_select} ';
	   \$sql  .= shift if \@_;
	my \$sth   = $pkg->prepare(\$sql);
	\$sth->execute(\@_);
	while ( \$_ = \$sth->fetchrow_arrayref ) {
		\$_ = bless [ \@\$_ ], '$table->{class}';
		\$call->() or last;
	}
	\$sth->finish;
}

END_PERL
			} else {
				$code .= <<"END_PERL";
sub iterate {
	my \$class = shift;
	my \$call  = pop;
	my \$sql   = '$table->{sql_select} ';
	   \$sql  .= shift if \@_;
	my \$sth   = $pkg->prepare(\$sql);
	\$sth->execute(\@_);
	while ( \$_ = \$sth->fetchrow_hashref ) {
		bless \$_, '$table->{class}';
		\$call->() or last;
	}
	\$sth->finish;
}

END_PERL
			}

			# Add the primary key based single object loader
			if ( $table->{pks} ) {
				if ( $table->{array} ) {
					$code .= <<"END_PERL";
sub load {
	my \$class = shift;
	my \@row   = $pkg->selectrow_array(
		'$table->{sql_select} where $table->{sql_where}',
		undef, \@_,
	);
	unless ( \@row ) {
		Carp::croak("$table->{class} row does not exist");
	}
	bless \\\@row, '$table->{class}';
}

END_PERL
				} else {
					$code .= <<"END_PERL";
sub load {
	my \$class = shift;
	my \$row   = $pkg->selectrow_hashref(
		'$table->{sql_select} where $table->{sql_where}',
		undef, \@_,
	);
	unless ( \$row ) {
		Carp::croak("$table->{class} row does not exist");
	}
	bless \$row, '$table->{class}';
}

END_PERL
				}
			}

			# Generate the elements for tables with primary keys
			if ( $table->{create} ) {
				my $l = $table->{array} ? '['  : '{';
				my $r = $table->{array} ? ']'  : '}';
				$code .= <<"END_PERL";
sub new {
	my \$class = shift;
	my \%attr  = \@_;
	bless $l
$table->{pl_new}
	$r, \$class;
}

sub create {
	shift->new(\@_)->insert;
}

sub insert {
	my \$self = shift;
	my \$dbh  = $pkg->dbh;
	\$dbh->do( '$table->{sql_insert}', {},
$table->{pl_insert}
	);
$table->{pl_fill}
	return \$self;
}

sub delete {
	my \$self = shift;
	return $pkg->do(
		'delete from $table->{qname} where $table->{sql_where}',
		{},
$table->{pl_where}
	) if ref \$self;
	Carp::croak("Must use truncate to delete all rows") unless \@_;
	return $pkg->do(
		'delete from $table->{qname} ' . shift,
		{}, \@_,
	);
}

sub truncate {
	$pkg->do('delete from $table->{qname}');
}

END_PERL
			}

			if ( $table->{create} and $table->{array} ) {
				# Add an additional set method to avoid having
				# the user have to enter manual positions.
				$code .= <<"END_PERL";
sub set {
	my \$self = shift;
	my \$i    = {
$table->{pl_accessor}
	}->{\$_[0]};
	die "Bad name '\$_[0]'" unless defined \$i;
	\$self->[\$i] = \$_[1];
}

END_PERL
			}

			# Generate the boring accessors
			if ( $xsaccessor ) {
				my $type    = $table->{create} ? 'accessors' : 'getters';
				my $xsclass = $table->{array}
					? 'Class::XSAccessor::Array'
					: 'Class::XSAccessor';

				$code .= <<"END_PERL";
use $xsclass 1.05 {
	getters => {
$table->{pl_accessor}
	},
};

END_PERL
			} else {
				$code .= join "\n\n", map { <<"END_PERL" } grep { ! $_->{fk} } @columns;
sub $_->{name} {
	\$_[0]->$_->{key};
}
END_PERL
			}

			# Generate the foreign key accessors
			$code .= join "\n\n", map { <<"END_PERL" } grep { $_->{fk} } @columns;
sub $_->{name} {
	($_->{fk}->[1]->{class}\->select('where \"$_->{fk}->[1]->{pk}->[0]->{name}\" = ?', \$_[0]->$_->{key}))[0];
}
END_PERL

			# Add the experimental update method
			if ( $table->{create} and $params{x_update} ) {
				my @pk    = map { $_->{name} } @{$table->{pk}};
				my $wsql  = join ' and ', map { "\"$_\" = ?" } @pk;
				my $wattr = join ', ',    map { "\$self->$_" } @pk;
				my $set   = $table->{array}
					? '$self->set( $_ => $set{$_} ) foreach keys %set;'
					: '$self->{$_} = $set{$_} foreach keys %set;';
				$code .= <<"END_PERL";

### EXPERIMENTAL
sub update {
	my \$self = shift;
	my \%set  = \@_;
	my \$rows = $pkg->do(
		'update $table->{qname} set ' .
		join( ', ', map { "\\"\$_\\" = ?" } keys \%set ) .
		' where $wsql',
		{}, values \%set, $wattr,
	);
	unless ( \$rows == 1 ) {
		die "Expected to update 1 row, actually updated \$rows";
	}
	$set
	return 1;
}
END_PERL
			}
		}
	}

	# We are finished with the database
	$dbh->disconnect;

	# Start the post-table content again
	$code .= "\npackage $pkg;\n" if $params{tables};

	# Append any custom code for the user
	$code .= "\n$params{append}" if defined $params{append};

	# Load the overload classes for each of the tables
	if ( $tables ) {
		$code .= join( "\n",
			"local \$@ = undef;",
			map {
				"eval { require $_->{class} };"
			} @$tables
		);
	}

	# End the class normally
	$code .= "\n\n1;\n";

	# Save to the cache location if caching is enabled
	if ( $cached ) {
		my $dir = File::Basename::dirname($cached);
		unless ( -d $dir ) {
			File::Path::mkpath( $dir, { verbose => 0 } );
		}

		# Save a copy of the code to the file
		local *FILE;
		open( FILE, ">$cached" ) or Carp::croak("open($cached): $!");
		print FILE $code;
		close FILE;
	}

	# Compile the code
	local $@;
	if ( $^P and $^V >= 5.008009 ) {
		local $^P = $^P | 0x800;
		eval($code);
		die $@ if $@;
	} elsif ( $DEBUG ) {
		dval($code);
	} else {
		eval($code);
		die $@ if $@;
	}

	return 1;
}

sub dval {
	# Write the code to the temp file
	require File::Temp;
	my ($fh, $filename) = File::Temp::tempfile();
	$fh->print($_[0]);
	close $fh;
	require $filename;
	unlink $filename;

	# Print the debugging output
	# my @trace = map {
		# s/\s*[{;]$//;
		# s/^s/  s/;
		# s/^p/\np/;
		# "$_\n"
	# } grep {
		# /^(?:package|sub)\b/
	# } split /\n/, $_[0];
	# print STDERR @trace, "\nCode saved as $filename\n\n";

	return 1;
}

sub prune {
	my $class = shift;
	push @PRUNE, map { File::Spec->rel2abs($_) } @_;
}

1;

__END__

=pod

=head1 NAME

ORLite - Extremely light weight SQLite-specific ORM

=head1 SYNOPSIS

  package Foo;
  
  # Simplest possible usage
  
  use strict;
  use ORLite 'data/sqlite.db';
  
  my @awesome = Foo::Person->select(
     'where first_name = ?',
     'Adam',
  );
  
  package Bar;
  
  # All available options enabled or specified.
  # Some options shown are mutually exclusive,
  # this code would not actually run.
  
  use ORLite {
      package      => 'My::ORM',
      file         => 'data/sqlite.db',
      user_version => 12,
      readonly     => 1,
      create       => sub {
          my $dbh = shift;
          $dbh->do('CREATE TABLE foo ( bar TEXT NOT NULL )');
      },
      tables       => [ 'table1', 'table2' ],
      cleanup      => 'VACUUM',
      prune        => 1,
  };

=head1 DESCRIPTION

L<SQLite> is a light single file SQL database that provides an
excellent platform for embedded storage of structured data.

However, while it is superficially similar to a regular server-side SQL
database, SQLite has some significant attributes that make using it like
a traditional database difficult.

For example, SQLite is extremely fast to connect to compared to server
databases (1000 connections per second is not unknown) and is
particularly bad at concurrency, as it can only lock transactions at
a database-wide level.

This role as a superfast internal data store can clash with the roles and
designs of traditional object-relational modules like L<Class::DBI> or
L<DBIx::Class>.

What this situation would seem to need is an object-relation system that is
designed specifically for SQLite and is aligned with its idiosyncracies.

ORLite is an object-relation system specifically tailored for SQLite that
follows many of the same principles as the ::Tiny series of modules and
has a design and feature set that aligns directly to the capabilities of
SQLite.

Further documentation will be available at a later time, but the synopsis
gives a pretty good idea of how it works.

=head2 How ORLite Works

In short, ORLite discovers the schema of a SQLite database, and then uses
code generation to build a set of packages for talking to that database.

In the simplest form, your target root package "uses" ORLite, which will do
the schema discovery and code generation at compile-time.

When called, ORLite generates two types of packages.

Firstly, it builds database connectivity, transaction support, and other
purely database level functionality into your root namespace.

Secondly, it will create one sub-package underneath the namespace of the root
module for each table or view it finds in the database.

Once the basic table support has been generated, it will also try to load an
"overlay" module of the same name. Thus, by created a Foo::TableName module on
disk containing "extra" code, you can extend the original and add additional
functionality to it.

=head1 OPTIONS

ORLite takes a set of options for the class construction at compile time
as a HASH parameter to the "use" line.

As a convenience, you can pass just the name of an existing SQLite file
to load, and ORLite will apply defaults to all other options.

  # The following are equivalent
  
  use ORLite $filename;
  
  use ORLite {
      file => $filename,
  };

The behaviour of each of the options is as follows:

=head2 package

The optional C<package> parameter is used to provide the Perl root namespace to generate
the code for. This class does not need to exist as a module on disk,
nor does it need to have anything loaded or in the namespace.

By default, the package used is the package that is calling ORLite's import
method (typically via the C<use ORLite { ... }> line).

=head2 file

The compulsory C<file> parameter (the only compulsory parameter) provides
the path to the SQLite file to use for the ORM class tree.

If the file already exists, it must be a valid SQLite file match that
supported by the version of L<DBD::SQLite> that is installed on your
system.

L<ORLite> will throw an exception if the file does not exist, B<unless>
you also provide the C<create> option to signal that L<ORLite> should
create a new SQLite file on demand.

If the C<create> option is provided, the path provided must be creatable.
When creating the database, L<ORLite> will also create any missing
directories as needed.

=head2 user_version

When working with ORLite, the biggest risk to the stability of your code
is often the reliability of the SQLite schema structure over time.

When the database schema changes the code generated by ORLite will also
change. This can easily result in an unexpected change in the API of your
class tree, breaking the code that sits on top of those generated APIs.

To resolve this, L<ORLite> supports a feature called schema version-locking.

Via the C<user_version> SQLite pragma, you can set a revision for your
database schema, increasing the number each time to make a non-trivial
chance to your schema.

  SQLite> PRAGMA user_version = 7

When creating your L<ORLite> package, you should specificy this schema
version number via the C<user_version> option.

  use ORLite {
      file         => $filename,
      user_version => 7,
  };

When connecting to the SQLite database, the C<user_version> you provide
will be checked against the version in the schema. If the versions do
not match, then the schema has unexpectedly changed, and the code that
is generated by L<ORLite> would be different to the expected API.

Rather than risk potentially destructive errors caused by the changing
code, L<ORLite> will simply refuse to run and throw an exception.

Thus, using the C<user_version> feature allows you to write code against
a SQLite database with high-certainty that it will continue to work. Or
at the very least, that should the SQLite schema change in the future your
code fill fail quickly and safely instead of running away and causing
unknown behaviour.

By default, the C<user_version> option is false and the value of
the SQLite C<PRAGMA user_version> will B<not> be checked.

=head2 readonly

To conserve memory and reduce complexity, L<ORLite> will generate the API
differently based on the writability of the SQLite database.

Features like transaction support and methods that result in C<INSERT>,
C<UPDATE> and C<DELETE> queries will only be added if they can actually
be run, resulting in an immediate "no such method" exception at the Perl
level instead of letting the application do more work only to hit an
inevitable SQLite error.

By default, the C<reaodnly> option is based on the filesystem permissions
of the SQLite database (which matches SQLite's own writability behaviour).

However the C<readonly> option can be explicitly provided if you wish.
Generally you would do this if you are working with a read-write database,
but you only plan to read from it.

Forcing C<readonly> to true will halve the size of the code that is
generated to produce your ORM, reducing the size of any auto-generated
API documentation using L<ORLite::Pod> by a similar amount.

It also ensures that this process will only take shared read locks on the
database (preventing the chance of creating a dead-lock on the SQLite
database).

=head2 create

The C<create> option is used to expand L<ORLite> beyond just consuming
other people's databases to produce and operating on databases user the
direct control of your code.

The C<create> option supports two alternative forms.

If C<create> is set to a simple true value, an empty SQLite file will be
created if the location provided in the C<file> option does not exist.

If C<create> is set to a C<CODE> reference, this function will be executed
on the new database B<before> L<ORLite> attempts to scan the schema.

The C<CODE> reference will be passed a plain L<DBI> connection handle,
which you should operate on normally. Note that because C<create> is fired
before the code generation phase, none of the functionality produced by
the generated classes is available during the execution of the C<create>
code.

The use of C<create> option is incompatible with the C<readonly> option.

=head2 tables

The C<tables> option should be a reference to an array containing a list
of table names. For large or complex SQLite databases where you only need
to make use of a fraction of the schema limiting the set of tables
will reduce both the startup time needed to scan the structure of the
SQLite schema, and reduce the memory cost of the class tree.

If the C<tables> option is not provided, L<ORLite> will attempt to produce
a class for every table in the main schema that is not prefixed with 
with C<sqlite_>.

=head2 cache

  use ORLite {
      file         => 'dbi:SQLite:sqlite.db',
      user_version => 2,
      cache        => 'cache/directory',
  };

The C<cache> option is used to reduce the time needed to scan the SQLite
database table structures and generate the code for them, by saving the
generated code to a cache directory and loading from that file instead
of generating it each time from scratch.

=head2 cleanup

When working with embedded SQLite databases containing rapidly changing
state data, it is important for database performance and general health
to make sure you VACUUM or ANALYZE the database regularly.

The C<cleanup> option should be a single literal SQL statement.

If provided, this statement will be automatically run on the database
during C<END>-time, after the last transaction has been completed.

This will typically either by a full C<'VACUUM ANALYZE'> or the more
simple C<'VACUUM'>.

=head2 prune

In some situation, such as during test scripts, an application will only
need the created SQLite database temporarily. In these situations, the
C<prune> option can be provided to instruct L<ORLite> to delete the
SQLite database when the program ends.

If any directories were made in order to create the SQLite file, these
directories will be cleaned up and removed as well.

If C<prune> is enabled, you should generally not use C<cleanup> as any
cleanup operation will be made pointless when C<prune> deletes the file.

By default, the C<prune> option is set to false.

=head2 shim

In some situtations you may wish to make extensive changes to the behaviour
of the classes and methods generated by ORLite. Under normal circumstances
all code is generated into the table class directly, which can make
overriding method difficult.

The C<shim> option will make ORLite generate all of it's methods into a
separate C<Foo::TableName::Shim> class, and leave the main table class
C<Foo::TableName> as a transparent subclass of the shim.

This allows you to alter the behaviour of a table class without having
to do nasty tricks with symbol tables in order to alter or replace methods.

  package My::Person;
  
  # Write a log message when we create a new object
  sub create {
      my $class = shift;
      my $self  = SUPER::create(@_);
      my $name  = $self->name;
      print LOG "Created new person '$name'\n";
      return $self;
  }

The C<shim> option is global. It will alter the structure of all table
classes at once. However, unless you are making alterations to a class
the impact of this different class structure should be zero.

=head1 ROOT PACKAGE METHODS

All ORLite root packages receive an identical set of methods for
controlling connections to the database, transactions, and the issueing
of queries of various types to the database.

The example root package Foo::Bar is used in any examples.

All methods are static, ORLite does not allow the creation of a Foo::Bar
object (although you may wish to add this capability yourself).

=head2 dsn

  my $string = Foo::Bar->dsn;

The C<dsn> accessor returns the dbi connection string used to connect
to the SQLite database as a string.

=head2 dbh

  my $handle = Foo::Bar->dbh;

To reliably prevent potential SQLite deadlocks resulting from multiple
connections in a single process, each ORLite package will only ever
maintain a single connection to the database.

During a transaction, this will be the same (cached) database handle.

Although in most situations you should not need a direct DBI connection
handle, the C<dbh> method provides a method for getting a direct
connection in a way that is compatible with ORLite's connection
management.

Please note that these connections should be short-lived, you should
never hold onto a connection beyond the immediate scope.

The transaction system in ORLite is specifically designed so that code
using the database should never have to know whether or not it is in a
transation.

Because of this, you should B<never> call the -E<gt>disconnect method
on the database handles yourself, as the handle may be that of a
currently running transaction.

Further, you should do your own transaction management on a handle
provided by the <dbh> method.

In cases where there are extreme needs, and you B<absolutely> have to
violate these connection handling rules, you should create your own
completely manual DBI-E<gt>connect call to the database, using the connect
string provided by the C<dsn> method.

The C<dbh> method returns a L<DBI::db> object, or throws an exception on
error.

=head2 connect

  my $dbh = Foo::Bar->connect;

The C<connect> method is provided for the (extremely rare) situation in
which you need a raw connection to the database, evading the normal tracking
and management provided of the ORM.

The use of raw connections in this manner is strongly discouraged, as you
can create fatal deadlocks in SQLite if either the core ORM or the raw
connection uses a transaction at any time.

To summarise, do not use this method unless you B<REALLY> know what you are
doing.

B<YOU HAVE BEEN WARNED!>

=head2 connected

  my $active = Foo::Bar->connected;

The C<connected> method provides introspection of the connection status
of the library. It returns true if there is any connection or transaction
open to the database, or false otherwise.

=head2 begin

  Foo::Bar->begin;

The C<begin> method indicates the start of a transaction.

In the same way that ORLite allows only a single connection, likewise
it allows only a single application-wide transaction.

No indication is given as to whether you are currently in a transaction
or not, all code should be written neutrally so that it works either way
or doesn't need to care.

Returns true or throws an exception on error.

While transaction support is always built for every L<ORLite>-generated
class tree, if the database is opened C<readonly> the C<commit> method
will not exist at all in the API, and your only way of ending the
transaction (and the resulting persistent connection) will be C<rollback>.

=head2 commit

  Foo::Bar->commit;

The C<commit> method commits the current transaction. If called outside
of a current transaction, it is accepted and treated as a null operation.

Once the commit has been completed, the database connection falls back
into auto-commit state. If you wish to immediately start another
transaction, you will need to issue a separate -E<gt>begin call.

Returns true or throws an exception on error.

=head2 commit_begin

  Foo::Bar->begin;
  
  # Code for the first transaction...
  
  Foo::Bar->commit_begin;
  
  # Code for the last transaction...
  
  Foo::Bar->commit;

By default, L<ORLite>-generated code uses opportunistic connections.

Every <select> you call results in a fresh L<DBI> C<connect>, and a
C<disconnect> occurs after query processing and before the data is
returned. Connections are B<only> held open indefinitely during a
transaction, with an immediate C<disconnect> after your C<commit>.

This makes ORLite very easy to use in an ad-hoc manner, but can have
performance implications.

While SQLite itself can handle 1000 connections per second, the repeated
destruction and repopulation of SQLite's data page caches between your
statements (or between transactions) can slow things down dramatically.

The C<commit_begin> method is used to C<commit> the current transaction
and immediately start a new transaction, without disconnecting from the
database.

Its exception behaviour and return value is identical to that of a plain
C<commit> call.

=head2 rollback

The C<rollback> method rolls back the current transaction. If called outside
of a current transaction, it is accepted and treated as a null operation.

Once the rollback has been completed, the database connection falls back
into auto-commit state. If you wish to immediately start another
transaction, you will need to issue a separate -E<gt>begin call.

If a transaction exists at END-time as the process exits, it will be
automatically rolled back.

Returns true or throws an exception on error.

=head2 rollback_begin

  Foo::Bar->begin;
  
  # Code for the first transaction...
  
  Foo::Bar->rollback_begin;
  
  # Code for the last transaction...
  
  Foo::Bar->commit;

By default, L<ORLite>-generated code uses opportunistic connections.

Every <select> you call results in a fresh L<DBI> C<connect>, and a
C<disconnect> occurs after query processing and before the data is
returned. Connections are B<only> held open indefinitely during a
transaction, with an immediate C<disconnect> after your C<commit>.

This makes ORLite very easy to use in an ad-hoc manner, but can have
performance implications.

While SQLite itself can handle 1000 connections per second, the repeated
destruction and repopulation of SQLite's data page caches between your
statements (or between transactions) can slow things down dramatically.

The C<rollback_begin> method is used to C<rollback> the current transaction
and immediately start a new transaction, without disconnecting from the
database.

Its exception behaviour and return value is identical to that of a plain
C<commit> call.

=head2 do

  Foo::Bar->do(
      'insert into table (foo, bar) values (?, ?)',
      {},
      $foo_value,
      $bar_value,
  );

The C<do> method is a direct wrapper around the equivalent L<DBI> method,
but applied to the appropriate locally-provided connection or transaction.

It takes the same parameters and has the same return values and error
behaviour.

=head2 selectall_arrayref

The C<selectall_arrayref> method is a direct wrapper around the equivalent
L<DBI> method, but applied to the appropriate locally-provided connection
or transaction.

It takes the same parameters and has the same return values and error
behaviour.

=head2 selectall_hashref

The C<selectall_hashref> method is a direct wrapper around the equivalent
L<DBI> method, but applied to the appropriate locally-provided connection
or transaction.

It takes the same parameters and has the same return values and error
behaviour.

=head2 selectcol_arrayref

The C<selectcol_arrayref> method is a direct wrapper around the equivalent
L<DBI> method, but applied to the appropriate locally-provided connection
or transaction.

It takes the same parameters and has the same return values and error
behaviour.

=head2 selectrow_array

The C<selectrow_array> method is a direct wrapper around the equivalent
L<DBI> method, but applied to the appropriate locally-provided connection
or transaction.

It takes the same parameters and has the same return values and error
behaviour.

=head2 selectrow_arrayref

The C<selectrow_arrayref> method is a direct wrapper around the equivalent
L<DBI> method, but applied to the appropriate locally-provided connection
or transaction.

It takes the same parameters and has the same return values and error
behaviour.

=head2 selectrow_hashref

The C<selectrow_hashref> method is a direct wrapper around the equivalent
L<DBI> method, but applied to the appropriate locally-provided connection
or transaction.

It takes the same parameters and has the same return values and error
behaviour.

=head2 prepare

The C<prepare> method is a direct wrapper around the equivalent
L<DBI> method, but applied to the appropriate locally-provided connection
or transaction

It takes the same parameters and has the same return values and error
behaviour.

In general though, you should try to avoid the use of your own prepared
statements if possible, although this is only a recommendation and by
no means prohibited.

=head2 pragma

  # Get the user_version for the schema
  my $version = Foo::Bar->pragma('user_version');

The C<pragma> method provides a convenient method for fetching a pragma
for a datase. See the SQLite documentation for more details.

=head1 TABLE PACKAGE METHODS

When you use ORLite, your database tables will be available as 
objects named in a camel-cased fashion. So, if your model name
is Foo::Bar...

  use ORLite {
      package => 'Foo::Bar',
      file    => 'data/sqlite.db',
  };

... then a table named 'user' would be accessed as C<Foo::Bar::User>,
while a table named 'user_data' would become C<Foo::Bar::UserData>.

=head2 base

  my $namespace = Foo::Bar::User->base; # Returns 'Foo::Bar'

Normally you will only need to work directly with a table class,
and only with one ORLite package.

However, if for some reason you need to work with multiple ORLite packages
at the same time without hardcoding the root namespace all the time, you
can determine the root namespace from an object or table class with the
C<base> method.

=head2 table

  print Foo::Bar::UserData->table; # 'user_data'

While you should not need the name of table for any simple operations,
from time to time you may need it programatically. If you do need it,
you can use the C<table> method to get the table name.

=head2 table_info

  # List the columns in the underlying table
  my $columns = Foo::Bar::User->table_info;
  foreach my $c ( @$columns ) {
     print "Column $c->{name} $c->{type}";
     print " not null" if $c->{notnull};
     print " default $c->{dflt_value}" if defined $c->{dflt_value};
     print " primary key" if $c->{pk};
     print "\n";
  }

The C<table_info> method is a wrapper around the SQLite C<table_info>
pragma, and provides simplified access to the column metadata for the
underlying table should you need it for some advanced function that
needs direct access to the column list.

Returns a reference to an C<ARRAY> containing a list of columns, where
each column is a reference to a C<HASH> with the keys C<cid>, C<dflt_value>,
C<name>, C<notnull>, C<pk> and C<type>.

=head2 new

  my $user = Foo::Bar::User->new(
      name => 'Your Name',
      age  => 23,
  );

The C<new> constructor creates an anonymous object, without reading it
from or writing it to the database. It also won't do validation of any
kind, since ORLite is designed for use with embedded databases and
presumes that you know what you are doing.

=head2 insert

  my $user = Foo::Bar::User->new(
      name => 'Your Name',
      age  => 23,
  )->insert;

The C<insert> method takes an existing anonymous object and inserts it
into the database, returning the object as a convenience.

It provides the second half of the slower manual two-phase object
construction process.

If the table has an auto-incrementing primary key (and you have not
provided a value for it yourself) the identifier for the new record
will be fetched back from the database and set in your object.

  my $object = Foo::Bar::User->new( name => 'Foo' )->insert;
  
  print "Created new user with id " . $user->id . "\n";

=head2 create

  my $user = Foo::Bar::User->create(
      name => 'Your Name',
      age  => 23,
  );

While the C<new> + C<insert> methods are useful when you need to do
interesting constructor mechanisms, for most situations you already
have all the attributes ready and just want to create and insert the
record in a single step.

The C<create> method provides this shorthand mechanism and is just
the functional equivalent of the following.

  sub create {
      shift->new(@_)->insert;
  }

It returns the newly created object after it has been inserted.

=head2 load

  my $user = Foo::Bar::User->load( $id );

If your table has single column primary key, a C<load> method will be
generated in the class. If there is no primary key, the method is not
created.

The C<load> method provides a shortcut mechanism for fetching a single
object based on the value of the primary key. However it should only
be used for cases where your code trusts the record to already exists.

It returns a C<Foo::Bar::User> object, or throws an exception if the
object does not exist.

=head2 select

  my @users = Foo::Bar::User->select;
  
  my $users = Foo::Bar::User->select( 'where name = ?', @args );

The C<select> method is used to retrieve objects from the database.

In list context, returns an array with all matching elements.
In scalar context an array reference is returned with that same data.

You can filter the results or order them by passing SQL code to the method.

    my @users = DB::User->select( 'where name = ?', $name );

    my $users = DB::User->select( 'order by name' );

Because C<select> provides only the thinnest of layers around pure SQL
(it merely generates the "SELECT ... FROM table_name") you are free to use
anything you wish in your query, including subselects and function calls.

If called without any arguments, it will return all rows of the table in
the natural sort order of SQLite.

=head2 iterate

  Foo::Bar::User->iterate( sub {
      print $_->name . "\n";
  } );

The C<iterate> method enables the processing of large tables one record at
a time without loading having to them all into memory in advance.

This plays well to the strength of SQLite, allowing it to do the work of
loading arbitrarily large stream of records from disk while retaining the
full power of Perl when processing the records.

The last argument to C<iterate> must be a subroutine reference that will be
called for each element in the list, with the object provided in the topic
variable C<$_>.

This makes the C<iterate> code fragment above functionally equivalent to the
following, except with an O(1) memory cost instead of O(n).

    foreach ( Foo::Bar::User->select ) {
        print $_->name . "\n";
    }

You can filter the list via SQL in the same way you can with C<select>.

  Foo::Bar::User->iterate(
      'order by ?', 'name',
      sub {
          print $_->name . "\n";
      }
  );

You can also use it in raw form from the root namespace for better control.
Using this form also allows for the use of arbitrarily complex queries,
including joins. Instead of being objects, rows are provided as ARRAY
references when used in this form.

  Foo::Bar->iterate(
      'select name from user order by name',
      sub {
          print $_->[0] . "\n";
      }
  );

=head2 count

  my $everyone = Foo::Bar::User->count;
  
  my $young = Foo::Bar::User->count( 'where age <= ?', 13 );

You can count the total number of elements in a table by calling 
the C<count> method with no arguments. You can also narrow your
count by passing sql conditions to the method in the same manner
as with the C<select> method.

=head2 delete

  # Delete a single object from the database
  $user->delete;
  
  # Delete a range of rows from the database
  Foo::Bar::User->delete( 'where age <= ?', 13 );

The C<delete> method comes in two variations, depending on whether
you call it on a single object or an entire class.

When called as an instance methods C<delete> will delete the single
row representing that object, based on the primary key of that object.

The object that you delete will be left intact and untouched, and you
remain free to do with it whatever you wish.

When called as a static method on the class name C<delete> allows
the deletion of a range of zero or more records from that table.

It takes the same parameters for deleting as the C<select> method,
with the exception that you B<MUST> provide a condition parameter
and can B<NOT> use a conditionless C<delete> call to clear out the
entire table. This is done to limit accidental deletion.

=head2 truncate

  # Clear out all records from the table
  Foo::Bar::User->truncate;

The C<truncate> method takes no parameters and is used for only one
purpose, to completely empty a table of all rows.

Having a separate method from C<delete> not only prevents accidents,
but will also do the deletion via the direct SQLite C<TRUNCATE TABLE>
query. This uses a different deletion mechanism, and is
B<significantly> faster than a plain SQL C<DELETE>.

=head1 TO DO

- Support for intuiting reverse relations from foreign keys

- Document the 'create' and 'table' params

=head1 SUPPORT

Bugs should be reported via the CPAN bug tracker at

L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=ORLite>

For other issues, contact the author.

=head1 AUTHOR

Adam Kennedy E<lt>adamk@cpan.orgE<gt>

=head1 SEE ALSO

L<ORLite::Mirror>, L<ORLite::Migrate>, L<ORLite::Pod>

=head1 COPYRIGHT

Copyright 2008 - 2011 Adam Kennedy.

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.

=cut