aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Storage/OpenSim.DataStore.MonoSqlite/MonoSqliteDataStore.cs
blob: e1469d29a67d01a8a762b4fa63b765d29f6b37fd (plain)
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
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

using OpenSim.Region.Environment.Scenes;
using OpenSim.Region.Environment.LandManagement;
using OpenSim.Region.Environment;
using OpenSim.Region.Environment.Interfaces;
using OpenSim.Framework.Console;
using OpenSim.Framework.Types;
using OpenSim.Framework.Utilities;
using libsecondlife;

using System.Data;
using System.Data.SqlTypes;

using Mono.Data.SqliteClient;

namespace OpenSim.DataStore.MonoSqliteStorage
{
    public class MonoSqliteDataStore : IRegionDataStore
    {
        private const string primSelect = "select * from prims";
        private const string shapeSelect = "select * from primshapes";

        private DataSet ds;
        private SqliteDataAdapter primDa;
        private SqliteDataAdapter shapeDa;

        /***********************************************************************
         *
         *  Public Interface Functions
         *
         **********************************************************************/
        public void Initialise(string dbfile, string dbname)
        {
            string connectionString = "URI=file:" + dbfile + ",version=3";

            ds = new DataSet();

            MainLog.Instance.Verbose("DATASTORE", "Sqlite - connecting: " + dbfile);
            SqliteConnection conn = new SqliteConnection(connectionString);

            SqliteCommand primSelectCmd = new SqliteCommand(primSelect, conn);
            primDa = new SqliteDataAdapter(primSelectCmd);
            //            SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa);

            SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, conn);
            shapeDa = new SqliteDataAdapter(shapeSelectCmd);
            // SqliteCommandBuilder shapeCb = new SqliteCommandBuilder(shapeDa);


            // We fill the data set, now we've got copies in memory for the information
            // TODO: see if the linkage actually holds.
            // primDa.FillSchema(ds, SchemaType.Source, "PrimSchema");
            TestTables(conn);

            ds.Tables.Add(createPrimTable());
            setupPrimCommands(primDa, conn);
            primDa.Fill(ds.Tables["prims"]);
            MainLog.Instance.Verbose("DATASTORE", "Populated Prim Definitions");

            ds.Tables.Add(createShapeTable());
            setupShapeCommands(shapeDa, conn);

            // WORKAROUND: This is a work around for sqlite on
            // windows, which gets really unhappy with blob columns
            // that have no sample data in them.  At some point we
            // need to actually find a proper way to handle this.
            try
            {
                shapeDa.Fill(ds.Tables["primshapes"]);
            }
            catch (Exception)
            {
                MainLog.Instance.Verbose("DATASTORE", "Caught fill error on primshapes table");
            }
            MainLog.Instance.Verbose("DATASTORE", "Populated Prim Shapes");
            return;
        }

        public void StoreObject(SceneObjectGroup obj, LLUUID regionUUID)
        {
            foreach (SceneObjectPart prim in obj.Children.Values)
            {
                MainLog.Instance.Verbose("DATASTORE", "Adding obj: " + obj.UUID + " to region: " + regionUUID);
                addPrim(prim, obj.UUID, regionUUID);
            }

            // MainLog.Instance.Verbose("Attempting to do database update....");
            primDa.Update(ds, "prims");
            shapeDa.Update(ds, "primshapes");
            ds.AcceptChanges();
            // MainLog.Instance.Verbose("Dump of prims:", ds.GetXml());
        }

        public void RemoveObject(LLUUID obj, LLUUID regionUUID)
        {
            DataTable prims = ds.Tables["prims"];
            DataTable shapes = ds.Tables["primshapes"];

            string selectExp = "SceneGroupID = '" + obj.ToString() + "'";
            DataRow[] primRows = prims.Select(selectExp);
            foreach (DataRow row in primRows)
            {
                LLUUID uuid = new LLUUID((string)row["UUID"]);
                DataRow shapeRow = shapes.Rows.Find(uuid);
                if (shapeRow != null)
                {
                    shapeRow.Delete();
                }
                row.Delete();
            }

            primDa.Update(ds, "prims");
            shapeDa.Update(ds, "primshapes");
        }

        public List<SceneObjectGroup> LoadObjects(LLUUID regionUUID)
        {
            Dictionary<LLUUID, SceneObjectGroup> createdObjects = new Dictionary<LLUUID, SceneObjectGroup>();

            List<SceneObjectGroup> retvals = new List<SceneObjectGroup>();

            DataTable prims = ds.Tables["prims"];
            DataTable shapes = ds.Tables["primshapes"];

            string byRegion = "RegionUUID = '" + regionUUID.ToString() + "'";
            string orderByParent = "ParentID ASC";
            DataRow[] primsForRegion = prims.Select(byRegion, orderByParent);
            MainLog.Instance.Verbose("DATASTORE", "Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);

            foreach (DataRow primRow in primsForRegion)
            {
                try
                {
                    string uuid = (string)primRow["UUID"];
                    string objID = (string)primRow["SceneGroupID"];
                    if (uuid == objID) //is new SceneObjectGroup ?
                    {
                        SceneObjectGroup group = new SceneObjectGroup();
                        SceneObjectPart prim = buildPrim(primRow);
                        DataRow shapeRow = shapes.Rows.Find(prim.UUID);
                        if (shapeRow != null)
                        {
                            prim.Shape = buildShape(shapeRow);
                        }
                        else
                        {
                            Console.WriteLine("No shape found for prim in storage, so setting default box shape");
                            prim.Shape = BoxShape.Default;
                        }
                        group.AddPart(prim);
                        group.RootPart = prim;

                        createdObjects.Add(group.UUID, group);
                        retvals.Add(group);
                    }
                    else
                    {
                        SceneObjectPart prim = buildPrim(primRow);
                        DataRow shapeRow = shapes.Rows.Find(prim.UUID);
                        if (shapeRow != null)
                        {
                            prim.Shape = buildShape(shapeRow);
                        }
                        else
                        {
                            Console.WriteLine("No shape found for prim in storage, so setting default box shape");
                            prim.Shape = BoxShape.Default;
                        }
                        createdObjects[new LLUUID(objID)].AddPart(prim);
                    }
                }
                catch (Exception)
                {
                    foreach (DataColumn col in prims.Columns)
                    {
                        MainLog.Instance.Verbose("Col: " + col.ColumnName + " => " + primRow[col]);
                    }
                }
            }
            MainLog.Instance.Verbose("DATASTORE", "Sqlite - LoadObjects found " + prims.Rows.Count + " primitives");
             return retvals;
        }

        public void StoreTerrain(double[,] ter)
        {

        }

        public double[,] LoadTerrain()
        {
            return null;
        }

        public void RemoveLandObject(uint id)
        {

        }

        public void StoreParcel(Land parcel)
        {

        }

        public List<Land> LoadLandObjects()
        {
            return new List<Land>();
        }

        public void Shutdown()
        {
            // TODO: DataSet commit
        }

        //         public class TextureBlock
        //         {
        //             public byte[] TextureData;
        //             public byte[] ExtraParams = new byte[1];

        //             public TextureBlock(byte[] data)
        //             {
        //                 TextureData = data;
        //             }

        //             public TextureBlock()
        //             {

        //             }

        //             public string ToXMLString()
        //             {
        //                 StringWriter sw = new StringWriter();
        //                 XmlTextWriter writer = new XmlTextWriter(sw);
        //                 XmlSerializer serializer = new XmlSerializer(typeof(TextureBlock));
        //                 serializer.Serialize(writer, this);
        //                 return sw.ToString();
        //             }

        //             public static TextureBlock FromXmlString(string xmlData)
        //             {
        //                 TextureBlock textureEntry = null;
        //                 StringReader sr = new StringReader(xmlData);
        //                 XmlTextReader reader = new XmlTextReader(sr);
        //                 XmlSerializer serializer = new XmlSerializer(typeof(TextureBlock));
        //                 textureEntry = (TextureBlock)serializer.Deserialize(reader);
        //                 reader.Close();
        //                 sr.Close();
        //                 return textureEntry;
        //             }
        //         }

        /***********************************************************************
         *
         *  Database Definition Functions
         * 
         *  This should be db agnostic as we define them in ADO.NET terms
         *
         **********************************************************************/

        private void createCol(DataTable dt, string name, System.Type type)
        {
            DataColumn col = new DataColumn(name, type);
            dt.Columns.Add(col);
        }

        private DataTable createPrimTable()
        {
            DataTable prims = new DataTable("prims");

            createCol(prims, "UUID", typeof(System.String));
            createCol(prims, "RegionUUID", typeof(System.String));
            createCol(prims, "ParentID", typeof(System.Int32));
            createCol(prims, "CreationDate", typeof(System.Int32));
            createCol(prims, "Name", typeof(System.String));
            createCol(prims, "SceneGroupID", typeof(System.String));
            // various text fields
            createCol(prims, "Text", typeof(System.String));
            createCol(prims, "Description", typeof(System.String));
            createCol(prims, "SitName", typeof(System.String));
            createCol(prims, "TouchName", typeof(System.String));
            // permissions
            createCol(prims, "ObjectFlags", typeof(System.Int32));
            createCol(prims, "CreatorID", typeof(System.String));
            createCol(prims, "OwnerID", typeof(System.String));
            createCol(prims, "GroupID", typeof(System.String));
            createCol(prims, "LastOwnerID", typeof(System.String));
            createCol(prims, "OwnerMask", typeof(System.Int32));
            createCol(prims, "NextOwnerMask", typeof(System.Int32));
            createCol(prims, "GroupMask", typeof(System.Int32));
            createCol(prims, "EveryoneMask", typeof(System.Int32));
            createCol(prims, "BaseMask", typeof(System.Int32));
            // vectors
            createCol(prims, "PositionX", typeof(System.Double));
            createCol(prims, "PositionY", typeof(System.Double));
            createCol(prims, "PositionZ", typeof(System.Double));
            createCol(prims, "GroupPositionX", typeof(System.Double));
            createCol(prims, "GroupPositionY", typeof(System.Double));
            createCol(prims, "GroupPositionZ", typeof(System.Double));
            createCol(prims, "VelocityX", typeof(System.Double));
            createCol(prims, "VelocityY", typeof(System.Double));
            createCol(prims, "VelocityZ", typeof(System.Double));
            createCol(prims, "AngularVelocityX", typeof(System.Double));
            createCol(prims, "AngularVelocityY", typeof(System.Double));
            createCol(prims, "AngularVelocityZ", typeof(System.Double));
            createCol(prims, "AccelerationX", typeof(System.Double));
            createCol(prims, "AccelerationY", typeof(System.Double));
            createCol(prims, "AccelerationZ", typeof(System.Double));
            // quaternions
            createCol(prims, "RotationX", typeof(System.Double));
            createCol(prims, "RotationY", typeof(System.Double));
            createCol(prims, "RotationZ", typeof(System.Double));
            createCol(prims, "RotationW", typeof(System.Double));

            // Add in contraints
            prims.PrimaryKey = new DataColumn[] { prims.Columns["UUID"] };

            return prims;
        }

        private DataTable createShapeTable()
        {
            DataTable shapes = new DataTable("primshapes");
            createCol(shapes, "UUID", typeof(System.String));
            // shape is an enum
            createCol(shapes, "Shape", typeof(System.Int32));
            // vectors
            createCol(shapes, "ScaleX", typeof(System.Double));
            createCol(shapes, "ScaleY", typeof(System.Double));
            createCol(shapes, "ScaleZ", typeof(System.Double));
            // paths
            createCol(shapes, "PCode", typeof(System.Int32));
            createCol(shapes, "PathBegin", typeof(System.Int32));
            createCol(shapes, "PathEnd", typeof(System.Int32));
            createCol(shapes, "PathScaleX", typeof(System.Int32));
            createCol(shapes, "PathScaleY", typeof(System.Int32));
            createCol(shapes, "PathShearX", typeof(System.Int32));
            createCol(shapes, "PathShearY", typeof(System.Int32));
            createCol(shapes, "PathSkew", typeof(System.Int32));
            createCol(shapes, "PathCurve", typeof(System.Int32));
            createCol(shapes, "PathRadiusOffset", typeof(System.Int32));
            createCol(shapes, "PathRevolutions", typeof(System.Int32));
            createCol(shapes, "PathTaperX", typeof(System.Int32));
            createCol(shapes, "PathTaperY", typeof(System.Int32));
            createCol(shapes, "PathTwist", typeof(System.Int32));
            createCol(shapes, "PathTwistBegin", typeof(System.Int32));
            // profile
            createCol(shapes, "ProfileBegin", typeof(System.Int32));
            createCol(shapes, "ProfileEnd", typeof(System.Int32));
            createCol(shapes, "ProfileCurve", typeof(System.Int32));
            createCol(shapes, "ProfileHollow", typeof(System.Int32));
            // text TODO: this isn't right, but I'm not sure the right
            // way to specify this as a blob atm
            createCol(shapes, "Texture", typeof(System.Byte[]));
            createCol(shapes, "ExtraParams", typeof(System.Byte[]));

            shapes.PrimaryKey = new DataColumn[] { shapes.Columns["UUID"] };

            return shapes;
        }

        /***********************************************************************
         *  
         *  Convert between ADO.NET <=> OpenSim Objects
         *
         *  These should be database independant
         *
         **********************************************************************/

        private SceneObjectPart buildPrim(DataRow row)
        {
            // TODO: this doesn't work yet because something more
            // interesting has to be done to actually get these values
            // back out.  Not enough time to figure it out yet.
            SceneObjectPart prim = new SceneObjectPart();
            prim.UUID = new LLUUID((String)row["UUID"]);
            // explicit conversion of integers is required, which sort
            // of sucks.  No idea if there is a shortcut here or not.
            prim.ParentID = Convert.ToUInt32(row["ParentID"]);
            prim.CreationDate = Convert.ToInt32(row["CreationDate"]);
            prim.Name = (String)row["Name"];
            // various text fields
            prim.Text = (String)row["Text"];
            prim.Description = (String)row["Description"];
            prim.SitName = (String)row["SitName"];
            prim.TouchName = (String)row["TouchName"];
            // permissions
            prim.ObjectFlags = Convert.ToUInt32(row["ObjectFlags"]);
            prim.CreatorID = new LLUUID((String)row["CreatorID"]);
            prim.OwnerID = new LLUUID((String)row["OwnerID"]);
            prim.GroupID = new LLUUID((String)row["GroupID"]);
            prim.LastOwnerID = new LLUUID((String)row["LastOwnerID"]);
            prim.OwnerMask = Convert.ToUInt32(row["OwnerMask"]);
            prim.NextOwnerMask = Convert.ToUInt32(row["NextOwnerMask"]);
            prim.GroupMask = Convert.ToUInt32(row["GroupMask"]);
            prim.EveryoneMask = Convert.ToUInt32(row["EveryoneMask"]);
            prim.BaseMask = Convert.ToUInt32(row["BaseMask"]);
            // vectors
            prim.OffsetPosition = new LLVector3(
                                                Convert.ToSingle(row["PositionX"]),
                                                Convert.ToSingle(row["PositionY"]),
                                                Convert.ToSingle(row["PositionZ"])
                                                );
            prim.GroupPosition = new LLVector3(
                                               Convert.ToSingle(row["GroupPositionX"]),
                                               Convert.ToSingle(row["GroupPositionY"]),
                                               Convert.ToSingle(row["GroupPositionZ"])
                                               );
            prim.Velocity = new LLVector3(
                                          Convert.ToSingle(row["VelocityX"]),
                                          Convert.ToSingle(row["VelocityY"]),
                                          Convert.ToSingle(row["VelocityZ"])
                                          );
            prim.AngularVelocity = new LLVector3(
                                                 Convert.ToSingle(row["AngularVelocityX"]),
                                                 Convert.ToSingle(row["AngularVelocityY"]),
                                                 Convert.ToSingle(row["AngularVelocityZ"])
                                                 );
            prim.Acceleration = new LLVector3(
                                              Convert.ToSingle(row["AccelerationX"]),
                                              Convert.ToSingle(row["AccelerationY"]),
                                              Convert.ToSingle(row["AccelerationZ"])
                                              );
            // quaternions
            prim.RotationOffset = new LLQuaternion(
                                                   Convert.ToSingle(row["RotationX"]),
                                                   Convert.ToSingle(row["RotationY"]),
                                                   Convert.ToSingle(row["RotationZ"]),
                                                   Convert.ToSingle(row["RotationW"])
                                                   );

            return prim;
        }

        private void fillPrimRow(DataRow row, SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID)
        {
            row["UUID"] = prim.UUID;
            row["RegionUUID"] = regionUUID;
            row["ParentID"] = prim.ParentID;
            row["CreationDate"] = prim.CreationDate;
            row["Name"] = prim.Name;
            row["SceneGroupID"] = sceneGroupID; // the UUID of the root part for this SceneObjectGroup
            // various text fields
            row["Text"] = prim.Text;
            row["Description"] = prim.Description;
            row["SitName"] = prim.SitName;
            row["TouchName"] = prim.TouchName;
            // permissions
            row["ObjectFlags"] = prim.ObjectFlags;
            row["CreatorID"] = prim.CreatorID;
            row["OwnerID"] = prim.OwnerID;
            row["GroupID"] = prim.GroupID;
            row["LastOwnerID"] = prim.LastOwnerID;
            row["OwnerMask"] = prim.OwnerMask;
            row["NextOwnerMask"] = prim.NextOwnerMask;
            row["GroupMask"] = prim.GroupMask;
            row["EveryoneMask"] = prim.EveryoneMask;
            row["BaseMask"] = prim.BaseMask;
            // vectors
            row["PositionX"] = prim.OffsetPosition.X;
            row["PositionY"] = prim.OffsetPosition.Y;
            row["PositionZ"] = prim.OffsetPosition.Z;
            row["GroupPositionX"] = prim.GroupPosition.X;
            row["GroupPositionY"] = prim.GroupPosition.Y;
            row["GroupPositionZ"] = prim.GroupPosition.Z;
            row["VelocityX"] = prim.Velocity.X;
            row["VelocityY"] = prim.Velocity.Y;
            row["VelocityZ"] = prim.Velocity.Z;
            row["AngularVelocityX"] = prim.AngularVelocity.X;
            row["AngularVelocityY"] = prim.AngularVelocity.Y;
            row["AngularVelocityZ"] = prim.AngularVelocity.Z;
            row["AccelerationX"] = prim.Acceleration.X;
            row["AccelerationY"] = prim.Acceleration.Y;
            row["AccelerationZ"] = prim.Acceleration.Z;
            // quaternions
            row["RotationX"] = prim.RotationOffset.X;
            row["RotationY"] = prim.RotationOffset.Y;
            row["RotationZ"] = prim.RotationOffset.Z;
            row["RotationW"] = prim.RotationOffset.W;
        }

        private PrimitiveBaseShape buildShape(DataRow row)
        {
            PrimitiveBaseShape s = new PrimitiveBaseShape();
            s.Scale = new LLVector3(
                                    Convert.ToSingle(row["ScaleX"]),
                                    Convert.ToSingle(row["ScaleY"]),
                                    Convert.ToSingle(row["ScaleZ"])
                                    );
            // paths
            s.PCode = Convert.ToByte(row["PCode"]);
            s.PathBegin = Convert.ToUInt16(row["PathBegin"]);
            s.PathEnd = Convert.ToUInt16(row["PathEnd"]);
            s.PathScaleX = Convert.ToByte(row["PathScaleX"]);
            s.PathScaleY = Convert.ToByte(row["PathScaleY"]);
            s.PathShearX = Convert.ToByte(row["PathShearX"]);
            s.PathShearY = Convert.ToByte(row["PathShearY"]);
            s.PathSkew = Convert.ToSByte(row["PathSkew"]);
            s.PathCurve = Convert.ToByte(row["PathCurve"]);
            s.PathRadiusOffset = Convert.ToSByte(row["PathRadiusOffset"]);
            s.PathRevolutions = Convert.ToByte(row["PathRevolutions"]);
            s.PathTaperX = Convert.ToSByte(row["PathTaperX"]);
            s.PathTaperY = Convert.ToSByte(row["PathTaperY"]);
            s.PathTwist = Convert.ToSByte(row["PathTwist"]);
            s.PathTwistBegin = Convert.ToSByte(row["PathTwistBegin"]);
            // profile
            s.ProfileBegin = Convert.ToUInt16(row["ProfileBegin"]);
            s.ProfileEnd = Convert.ToUInt16(row["ProfileEnd"]);
            s.ProfileCurve = Convert.ToByte(row["ProfileCurve"]);
            s.ProfileHollow = Convert.ToByte(row["ProfileHollow"]);
            // text TODO: this isn't right] = but I'm not sure the right
            // way to specify this as a blob atm
            s.TextureEntry = (byte[])row["Texture"];
            s.ExtraParams = (byte[])row["ExtraParams"];
            // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            //             string texture = encoding.GetString((Byte[])row["Texture"]);
            //             if (!texture.StartsWith("<"))
            //             {
            //                 //here so that we can still work with old format database files (ie from before I added xml serialization)
            //                  LLObject.TextureEntry textureEntry = null;
            //                 textureEntry = new LLObject.TextureEntry(new LLUUID(texture));
            //                 s.TextureEntry = textureEntry.ToBytes();
            //             }
            //             else
            //             {
            //                 TextureBlock textureEntry = TextureBlock.FromXmlString(texture);
            //                 s.TextureEntry = textureEntry.TextureData;
            //                 s.ExtraParams = textureEntry.ExtraParams;
            // }

            return s;
        }

        private void fillShapeRow(DataRow row, SceneObjectPart prim)
        {
            PrimitiveBaseShape s = prim.Shape;
            row["UUID"] = prim.UUID;
            // shape is an enum
            row["Shape"] = 0;
            // vectors
            row["ScaleX"] = s.Scale.X;
            row["ScaleY"] = s.Scale.Y;
            row["ScaleZ"] = s.Scale.Z;
            // paths
            row["PCode"] = s.PCode;
            row["PathBegin"] = s.PathBegin;
            row["PathEnd"] = s.PathEnd;
            row["PathScaleX"] = s.PathScaleX;
            row["PathScaleY"] = s.PathScaleY;
            row["PathShearX"] = s.PathShearX;
            row["PathShearY"] = s.PathShearY;
            row["PathSkew"] = s.PathSkew;
            row["PathCurve"] = s.PathCurve;
            row["PathRadiusOffset"] = s.PathRadiusOffset;
            row["PathRevolutions"] = s.PathRevolutions;
            row["PathTaperX"] = s.PathTaperX;
            row["PathTaperY"] = s.PathTaperY;
            row["PathTwist"] = s.PathTwist;
            row["PathTwistBegin"] = s.PathTwistBegin;
            // profile
            row["ProfileBegin"] = s.ProfileBegin;
            row["ProfileEnd"] = s.ProfileEnd;
            row["ProfileCurve"] = s.ProfileCurve;
            row["ProfileHollow"] = s.ProfileHollow;
            // text TODO: this isn't right] = but I'm not sure the right
            // way to specify this as a blob atm

            // And I couldn't work out how to save binary data either
            // seems that the texture colum is being treated as a string in the Datarow 
            // if you do a .getType() on it, it returns string, while the other columns return correct type
            // MW[10-08-07]
            // Added following xml hack but not really ideal , also ExtraParams isn't currently part of the database
            // am a bit worried about adding it now as some people will have old format databases, so for now including that data in this xml data
            // MW[17-08-07]
            row["Texture"] = s.TextureEntry;
            row["ExtraParams"] = s.ExtraParams;
            // TextureBlock textureBlock = new TextureBlock(s.TextureEntry);
            //             textureBlock.ExtraParams = s.ExtraParams;
            //             System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            // row["Texture"] = encoding.GetBytes(textureBlock.ToXMLString());
        }

        private void addPrim(SceneObjectPart prim, LLUUID sceneGroupID, LLUUID regionUUID)
        {
            DataTable prims = ds.Tables["prims"];
            DataTable shapes = ds.Tables["primshapes"];

            DataRow primRow = prims.Rows.Find(prim.UUID);
            if (primRow == null)
            {
                primRow = prims.NewRow();
                fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
                prims.Rows.Add(primRow);
            }
            else
            {
                fillPrimRow(primRow, prim, sceneGroupID, regionUUID);
            }

            DataRow shapeRow = shapes.Rows.Find(prim.UUID);
            if (shapeRow == null)
            {
                shapeRow = shapes.NewRow();
                fillShapeRow(shapeRow, prim);
                shapes.Rows.Add(shapeRow);
            }
            else
            {
                fillShapeRow(shapeRow, prim);
            }
        }

        /***********************************************************************
         *
         *  SQL Statement Creation Functions
         *
         *  These functions create SQL statements for update, insert, and create.
         *  They can probably be factored later to have a db independant
         *  portion and a db specific portion
         *
         **********************************************************************/

        private SqliteCommand createInsertCommand(string table, DataTable dt)
        {
            /**
             *  This is subtle enough to deserve some commentary.
             *  Instead of doing *lots* and *lots of hardcoded strings
             *  for database definitions we'll use the fact that
             *  realistically all insert statements look like "insert
             *  into A(b, c) values(:b, :c) on the parameterized query
             *  front.  If we just have a list of b, c, etc... we can
             *  generate these strings instead of typing them out.
             */
            string[] cols = new string[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                DataColumn col = dt.Columns[i];
                cols[i] = col.ColumnName;
            }

            string sql = "insert into " + table + "(";
            sql += String.Join(", ", cols);
            // important, the first ':' needs to be here, the rest get added in the join
            sql += ") values (:";
            sql += String.Join(", :", cols);
            sql += ")";
            SqliteCommand cmd = new SqliteCommand(sql);

            // this provides the binding for all our parameters, so
            // much less code than it used to be
            foreach (DataColumn col in dt.Columns)
            {
                cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
            }
            return cmd;
        }

        private SqliteCommand createUpdateCommand(string table, string pk, DataTable dt)
        {
            string sql = "update " + table + " set ";
            string subsql = "";
            foreach (DataColumn col in dt.Columns)
            {
                if (subsql.Length > 0)
                { // a map function would rock so much here
                    subsql += ", ";
                }
                subsql += col.ColumnName + "= :" + col.ColumnName;
            }
            sql += subsql;
            sql += " where " + pk;
            SqliteCommand cmd = new SqliteCommand(sql);

            // this provides the binding for all our parameters, so
            // much less code than it used to be

            foreach (DataColumn col in dt.Columns)
            {
                cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
            }
            return cmd;
        }


        private string defineTable(DataTable dt)
        {
            string sql = "create table " + dt.TableName + "(";
            string subsql = "";
            foreach (DataColumn col in dt.Columns)
            {
                if (subsql.Length > 0)
                { // a map function would rock so much here
                    subsql += ",\n";
                }
                subsql += col.ColumnName + " " + sqliteType(col.DataType);
                if (col == dt.PrimaryKey[0])
                {
                    subsql += " primary key";
                }
            }
            sql += subsql;
            sql += ")";
            return sql;
        }

        /***********************************************************************
         *
         *  Database Binding functions
         *
         *  These will be db specific due to typing, and minor differences
         *  in databases.
         *
         **********************************************************************/

        ///<summary>
        /// This is a convenience function that collapses 5 repetitive
        /// lines for defining SqliteParameters to 2 parameters:
        /// column name and database type.
        ///        
        /// It assumes certain conventions like :param as the param
        /// name to replace in parametrized queries, and that source
        /// version is always current version, both of which are fine
        /// for us.
        ///</summary>
        ///<returns>a built sqlite parameter</returns>
        private SqliteParameter createSqliteParameter(string name, System.Type type)
        {
            SqliteParameter param = new SqliteParameter();
            param.ParameterName = ":" + name;
            param.DbType = dbtypeFromType(type);
            param.SourceColumn = name;
            param.SourceVersion = DataRowVersion.Current;
            return param;
        }

        private void setupPrimCommands(SqliteDataAdapter da, SqliteConnection conn)
        {
            da.InsertCommand = createInsertCommand("prims", ds.Tables["prims"]);
            da.InsertCommand.Connection = conn;

            da.UpdateCommand = createUpdateCommand("prims", "UUID=:UUID", ds.Tables["prims"]);
            da.UpdateCommand.Connection = conn;

            SqliteCommand delete = new SqliteCommand("delete from prims where UUID = :UUID");
            delete.Parameters.Add(createSqliteParameter("UUID", typeof(System.String)));
            delete.Connection = conn;
            da.DeleteCommand = delete;
        }

        private void setupShapeCommands(SqliteDataAdapter da, SqliteConnection conn)
        {
            da.InsertCommand = createInsertCommand("primshapes", ds.Tables["primshapes"]);
            da.InsertCommand.Connection = conn;

            da.UpdateCommand = createUpdateCommand("primshapes", "UUID=:UUID", ds.Tables["primshapes"]);
            da.UpdateCommand.Connection = conn;

            SqliteCommand delete = new SqliteCommand("delete from primshapes where UUID = :UUID");
            delete.Parameters.Add(createSqliteParameter("UUID", typeof(System.String)));
            delete.Connection = conn;
            da.DeleteCommand = delete;
        }

        private void InitDB(SqliteConnection conn)
        {
            string createPrims = defineTable(createPrimTable());
            string createShapes = defineTable(createShapeTable());

            SqliteCommand pcmd = new SqliteCommand(createPrims, conn);
            SqliteCommand scmd = new SqliteCommand(createShapes, conn);
            conn.Open();
            pcmd.ExecuteNonQuery();
            scmd.ExecuteNonQuery();
            conn.Close();
        }

        private bool TestTables(SqliteConnection conn)
        {
            SqliteCommand primSelectCmd = new SqliteCommand(primSelect, conn);
            SqliteDataAdapter pDa = new SqliteDataAdapter(primSelectCmd);
            SqliteCommand shapeSelectCmd = new SqliteCommand(shapeSelect, conn);
            SqliteDataAdapter sDa = new SqliteDataAdapter(shapeSelectCmd);

            DataSet tmpDS = new DataSet();
            try
            {
                pDa.Fill(tmpDS, "prims");
                sDa.Fill(tmpDS, "primshapes");
            }
            catch (Mono.Data.SqliteClient.SqliteSyntaxException)
            {
                MainLog.Instance.Verbose("DATASTORE", "SQLite Database doesn't exist... creating");
                InitDB(conn);
            }

            pDa.Fill(tmpDS, "prims");
            sDa.Fill(tmpDS, "primshapes");

            foreach (DataColumn col in createPrimTable().Columns)
            {
                if (!tmpDS.Tables["prims"].Columns.Contains(col.ColumnName))
                {
                    MainLog.Instance.Verbose("DATASTORE", "Missing required column:" + col.ColumnName);
                    return false;
                }
            }
            foreach (DataColumn col in createShapeTable().Columns)
            {
                if (!tmpDS.Tables["primshapes"].Columns.Contains(col.ColumnName))
                {
                    MainLog.Instance.Verbose("DATASTORE", "Missing required column:" + col.ColumnName);
                    return false;
                }
            }
            return true;
        }

        /***********************************************************************
         *
         *  Type conversion functions
         *
         **********************************************************************/

        private DbType dbtypeFromType(Type type)
        {
            if (type == typeof(System.String))
            {
                return DbType.String;
            }
            else if (type == typeof(System.Int32))
            {
                return DbType.Int32;
            }
            else if (type == typeof(System.Double))
            {
                return DbType.Double;
            }
            else if (type == typeof(System.Byte[]))
            {
                return DbType.Binary;
            }
            else
            {
                return DbType.String;
            }
        }

        // this is something we'll need to implement for each db
        // slightly differently.
        private string sqliteType(Type type)
        {
            if (type == typeof(System.String))
            {
                return "varchar(255)";
            }
            else if (type == typeof(System.Int32))
            {
                return "integer";
            }
            else if (type == typeof(System.Double))
            {
                return "float";
            }
            else if (type == typeof(System.Byte[]))
            {
                return "blob";
            }
            else
            {
                return "string";
            }
        }
    }
}